Python patch of a object creation not working - python-3.x

app.py
class UnderTest:
def one(self):
print('In one')
email = EmailSender(None, 'messwage');
email.send()
EmailSender.py
class EmailSender:
def __init__(self, config, message):
self.mess = message;
def send(self):
print("should not be invoked")
test_under_test.py
class test_under_test(TestCase):
#patch('EmailSender.EmailSender')
def test_one(self, email):
test = UnderTest()
email.send.return_value = None;
test.one();
The 'send' method of the EmailSender should not have invoked, but, it is being invoked. When i debug instead of the Mock object in the email variable in EmailSender.one method i see original object of EmailSender, the patch is not working as expected here. what should I do?

Related

DRF ViewSet extra action (`#action`) serializer_class

When I try to use Django Rest Framework extra actions on a viewset, I can not make the decorator's serializer_class work.
class ClientViewSet(ModelViewSet):
queryset = Client.objects.all()
serializer_class = ClientSerializer
def get_queryset(self):
# Do things
def get_serializer_class(self):
if self.action in ["create"]:
return CreateClientSerializer
elif self.action in ["retrieve"]:
return ClientDetailSerializer
return self.serializer_class
#action(detail=True, methods=["get"], serializer_class=ClientDetailSerializer)
def get_by_name(self, request, name=None):
"""
Get one Client searching by name.
#param request:
#param name: Client code
#return: Response
"""
queryset = get_object_or_404(Client, name__iexact=name)
serializer = self.get_serializer(queryset)
return Response(serializer.data)
So, even if the extra action is supposedly overriding the ViewSet default serializer class, I still get ClientSerializer instead of ClientDetailSerializer.
The official documentation states that...
The decorator allows you to override any viewset-level configuration such as permission_classes, serializer_class, filter_backends...:
My get_serializer_class override defaults to the ViewSet serializer_class attribute for my extra actions. If I understand correctly, this is basically what GenericAPIView get_serializer_class does under the hood:
def get_serializer_class(self):
"""
(...)
"""
assert self.serializer_class is not None, (
"'%s' should either include a `serializer_class` attribute, "
"or override the `get_serializer_class()` method."
% self.__class__.__name__
)
return self.serializer_class
I guess I'm missing something obvious here. Just can not figure out what...
Any help is appreciated. Thanks in advance :)
Why not use it like this? I'm guessing you're doing something wrong in get_serializer_class.
#action(detail=True, methods=["get"], serializer_class=ClientDetailSerializer)
def get_by_name(self, request, name=None):
"""
Get one Client searching by name.
#param request:
#param name: Client code
#return: Response
"""
object = get_object_or_404(Client, name__iexact=name)
serializer = ClientDetailSerializer(object)
return Response(serializer.data)
When you override the get_serializer_class without calling the super of this class, the super class doesn't run.
user this:
def get_serializer_class(self):
if self.action in ["create"]:
return CreateClientSerializer
elif self.action in ["retrieve"]:
return ClientDetailSerializer
return super().get_serializer_class()

'NoneType object has no attribute ' send'

My code is returning this error NoneType object has no attribute 'send'
here is my code
import discord
import os
from discord.ext import commands
client = discord.Client()
class Logging(commands.Cog):
"""Sets up logging for you guild"""
def __init__(self, client):
self.bot = client
async def __error(self, ctx, error):
if isinstance(error, commands.BadArgument):
await ctx.send(error)
#commands.Cog.listener()
async def on_message_delete(self, message,):
deleted = embed = discord.Embed(
description=f"Message deleted in {message.channel.mention}", color=0x4040EC
).set_author(name=message.author, url= discord.Embed.Empty, icon_url=message.author.avatar_url)
channel = client.get_channel(888600482317213786)
deleted.add_field(name="Message", value=message.content)
deleted.timestamp = message.created_at
await channel.send(embed=deleted)
def setup(client):
client.add_cog(Logging(client))
I am doing this in my cogs and not in the main.py
channel = client.get_channel(888600482317213786) should be channel = self.bot.get_channel(888600482317213786). Then check if channel is None.
I assume there is no indentation error in your actual code.

python class Multiple inheritance __init__ object has no attribute 'xxx'

i have class , it inheritance other tow class.
class Req(Proxy, Headers):
def __init__(self):
super().__init__()
class Proxy:
pass
class Headers:
def __init__(self):
self.kdl_proxy_params = config.kdl_proxy_params
def get_ua(self):
res = requests.get("https://dev.kdlapi.com/api/getua", params=self.kdl_proxy_params).json()
ua = res["data"]["ua_list"][0]
return ua
r = Req()
r.get_ua()
So I received the following error message
AttributeError: 'Req' object has no attribute 'kdl_proxy_params'
I feel that this is a question of multiple inheritance. I hope you can help me to solve my doubts.

Tons of Cog errors

In discord.py 1.0.1 (Only version Repl.it has), the cogs are giving me a hard time.
import discord
from discord.ext import commands
class Coding(commands, Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_ready(self):
print("Kahoot Bot 0.1 ALPHA")
client.remove_command("help")
#commands.command()
async def clear(self, ctx, amount = 5):
await ctx.channel.purge(limit = amount + 1)
#commands.command()
async def ping(self, ctx):
await ctx.send(f"Pong! {round(client.latency * 1000)}ms.")
#client.command(pass_context = True, aliases = ["print"])
async def printing(ctx, *, what_to_print):
await ctx.send(what_to_print)
print(what_to_print)
def setup(client):
client.add_cog(Coding(client))
The gist of the errors is:
A) client is not defined
B) init() should return None, not coroutine
I've tried changing all my code to bot and back to client, but nothing's helped. No idea what's going on.
You do the inheritance wrong. You dont inherit from class: "commands" and "Cog". You inherit from class: "commands.Cog". thus changing: class Coding(commands, Cog): to class Coding(commands.Cog): will fix some of the errors.
You also do the following wrong (the "client does not exist" error):
#commands.Cog.listener()
async def on_ready(self):
print("Kahoot Bot 0.1 ALPHA")
client.remove_command("help") # this line
When we want to access a class variable we use self. in the beginning of that variable to indicate that we are using the class variable. This case you dont use self.client. but client.
As client is not defined in that function it will give an error. But it is defined as a class variable (the "init" function). To access it use: self.client.

How can I run pytest in another folders in Python

In folder [Root]/src/app, I have a file services_factory.py, for example:
class Describing:
def __init__(self):
pass
def get_description(self):
pass
class APIService(Describing):
def __init__(self):
pass
def get_description(self):
return 'Here provide services for APIs'
class DatabaseService(Describing):
def __init__(self):
pass
def get_description(self):
return 'Here provide services for Database'
class Injector:
def __init__(self):
pass
def get_service(self, type='API'):
services = {
"API": APIService,
"DB": DatabaseService
}
return services[type]()
At the end of file services_factory.py, I add an unittest, ex:
def test_services_injector():
injector = Injector()
api_service = injector.get_service('API')
db_service = injector.get_service('DB')
assert api_service.get_description() == 'Here provide services for APIs'
assert db_service.get_description() == 'Here provide services for Database'
Then, cmd: $ pytest src/app/services_injector.py, it worked nicely.
But when I create a file test_services_factory.py in [Root]/tests/app, for example:
import unittest
from unittest.mock import patch
def test_services_injector():
assert 'a' == 'a'
I can't import the classes in my services_factory.py.
So, how can I quickly fix this problem?

Resources