Something is really happening and i couldnt resolve for a day almost
Examples are below: Trying a simple method calling from one class to another class to figure out the problem as i have experienced the notorious problem this morning as well... so have tried a simple method calling checks...
Two Class:
HomePageAlone
OnDemand
HomePageAlone - defined a test "def test_E_Access(self):" calls method in OnDemand i got the below error.
Code as follows:
HomePageAlone
from sikuli import *
from OnDemand import *
import OnDemand
class homePage(unittest.TestCase):
def setUp(self):
print("Test")
def test_E_Access(self):
callMethod = OnDemand()
callMethod.calc() # Line#15
suite = unittest.TestSuite()
suite.addTest(homePage('test_E_Access'))
unittest.TextTestRunner(verbosity=2).run(suite)
OnDemand
from sikuli import *
class OnDemand(object):
def setUp(self):
print("setup")
def calc(self):
print ("This is calling")
Log Message
======================================================================
ERROR: test_E_Access (main.homePage)
Traceback (most recent call last):
File "C:\DOCUME~1\Senthil.S\LOCALS~1\Temp\sikuli-6018543662740221054.py", line 15, in test_E_Access
callMethod.calc(self) # Line#15
AttributeError: 'OnDemand' object has no attribute 'calc'
Ran 1 test in 0.016s
FAILED (errors=1)
Another Try : i tried to use as the below snippet as your suggested - it always throws AttributeError: 'OnDemandPopular' object has no attribute 'calc'
import OnDemandPopular
ondemand = OnDemandPopular.OnDemandPopular()
ondemand.calc()
Please help
You should import OnDemand class from OnDemand module;
from OnDemand import OnDemand
HomePageAlone
import unittest
from OnDemand import OnDemand
class homePage(unittest.TestCase):
def setUp(self):
print("Test")
def test_E_Access(self):
callMethod = OnDemand()
callMethod.calc() # Line#15
suite = unittest.TestSuite()
suite.addTest(homePage('test_E_Access'))
unittest.TextTestRunner(verbosity=2).run(suite)
OnDemand
class OnDemand(object):
def setUp(self):
print("setup")
def calc(self):
print ("This is calling")
The Output is ;
This is calling
test_E_Access (HomePageAlone.homePage) ... ok
Test
This is calling
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Test
This is calling
Related
Consider the following three files.
# my_class.py
class MyClass:
def __init__(self):
pass
def do_thing(self):
return 5
# main.py
from my_class import MyClass
def my_func():
instance = MyClass()
instance.do_thing()
# test_main.py
from main import my_func
from unittest.mock import patch
#patch('main.MyClass')
def test_my_func(MockMyClass):
my_func()
MockMyClass.do_thing.assert_called_once()
AssertionError: Expected 'do_thing' to have been called once. Called 0 times.
I'm instantiating a class MyClass inside a driver function my_func and calling one of the class's methods do_thing. What I'd like to do is test that when the driver function is invoked, the method of the class is called exactly once. I'm encountering an assertion error that's giving me problems.
I've read a million and one SO posts and other resources online about Python mocks, but I'm not able to figure this out. I thought the trick was that the #patch decorator patches the namespace the module is imported into, not from [Python Mocking a function from an imported module. What am I doing wrong here?
The do_thing method is an instance method of MyClass, NOT class method. You assert MockMyClass.do_thing.assert_called_once() is not correct. Here is the unit test solution:
my_class.py:
class MyClass:
def __init__(self):
pass
def do_thing(self):
return 5
main.py:
from my_class import MyClass
def my_func():
instance = MyClass()
instance.do_thing()
test_main.py:
from main import my_func
import unittest
from unittest.mock import patch
class TestMain(unittest.TestCase):
#patch('main.MyClass')
def test_my_func(self, MockMyClass):
mock_my_class_instance = MockMyClass.return_value
my_func()
mock_my_class_instance.do_thing.assert_called_once()
if __name__ == '__main__':
unittest.main()
unit test results with coverage report:
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Name Stmts Miss Cover Missing
-----------------------------------------------------------------------
src/stackoverflow/60539392/main.py 4 0 100%
src/stackoverflow/60539392/my_class.py 5 2 60% 3, 6
src/stackoverflow/60539392/test_main.py 10 0 100%
-----------------------------------------------------------------------
TOTAL
so i've got a problem with my code.
File 1:
class Abc(object):
...
def function1(self):
#do something
def function2(self):
x = input()
return x+1
and now i'm trying to test function 2 so i wrote a test for it and i don't know what i am doing wrong:
from unittest.mock import patch
import unittest
from file1 import *
class TestBackend(unittest.TestCase):
def test_mode_first(self):
self.assertEqual(Abc().funcion1(), 30)
#patch('funcion2.input', create=True)
def test_mode_second(self, mocked_input):
mocked_input.side_effect = ["QWE"]
result = Abc().funcion2()
self.assertEqual(result, 10)
if __name__ == '__main__':
unittest.main()
i get ModuleNotFoundError: No module named 'function2'
so what i am doing wrong in here?
thanks for your help :)
You get ModuleNotFoundError because funcion2 is not a module. patch doc is clear about this:
target should be a string in the form 'package.module.ClassName'. The
target is imported and the specified object replaced with the new
object, so the target must be importable from the environment you are
calling patch() from. The target is imported when the decorated
function is executed, not at decoration time.
This works for me when executed with python3 -m unittest discover from the directory the files are in.
BTW you have a couple of typos in your example, e.g. Abc().funcion2(), note the missing t in funcion2.
Also, try not to use from … import *: https://docs.quantifiedcode.com/python-anti-patterns/maintainability/from_module_import_all_used.html#using-wildcard-imports-from-import
# file1.py
class Abc(object):
def function1(self):
return 30
def function2(self):
x = input()
return x + "1"
# test_file1.py
import unittest
from unittest.mock import patch
from file1 import Abc
class TestBackend(unittest.TestCase):
def test_mode_first(self):
self.assertEqual(Abc().function1(), 30)
#patch('builtins.input')
def test_mode_second(self, mocked_input):
mocked_input.return_value = "QWE"
result = Abc().function2()
self.assertEqual(result, "QWE1")
Using Python 2.7, and mock library
How can I test that certain patched object has been initialized with some specific arguments using mock?
Here some sample code and pseudo-code:
unittest.py :
import mock
#mock.patch('mylib.SomeObject')
def test_mytest(self, mock_someobject):
test1 = mock_someobject.return_value
test1 = method_inside_someobject.side_effect = ['something']
mylib.method_to_test()
# How can I assert that method_to_test instanced SomeObject with certain arguments?
# I further test things with that method_inside_someobject call, no problems there...
mylib.py :
from someobjectmodule import SomeObject
def method_to_test():
obj = SomeObject(arg1=val1, arg2=val2, arg3=val3)
obj.method_inside_someobject()
So, how can I test SomeObject was instanced with arg1=val1, arg2=val2, arg3=val3?
If you replaced a class with a mock, creating an instance is just another call. Assert that the right parameters have been passed to that call, for example, with mock.assert_called_with():
mock_someobject.assert_called_with(arg1=val1, arg2=val2, arg3=val3)
To illustrate, I've updated your MCVE to a working example:
test.py:
import mock
import unittest
import mylib
class TestMyLib(unittest.TestCase):
#mock.patch('mylib.SomeObject')
def test_mytest(self, mock_someobject):
mock_instance = mock_someobject.return_value
mock_instance.method_inside_someobject.side_effect = ['something']
retval = mylib.method_to_test()
mock_someobject.assert_called_with(arg1='foo', arg2='bar', arg3='baz')
self.assertEqual(retval, 'something')
if __name__ == '__main__':
unittest.main()
mylib.py:
from someobjectmodule import SomeObject
def method_to_test():
obj = SomeObject(arg1='foo', arg2='bar', arg3='baz')
return obj.method_inside_someobject()
someobjectmodule.py:
class SomeObject(object):
def method_inside_someobject(self):
return 'The real thing'
and running the test:
$ python test.py
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
I'm trying to set some tests for my server.
According to a friend's recommendation I wanna use unittest and mock. For this purpose I wrote some lines but when I try to execute the script I got an importError.
Traceback (most recent call last):
File "test_creds.py", line 146, in <module>
unittest.main()
AttributeError: 'module' object has no attribute 'main'
Do I have some mistake with the imports?
Thanks!
# coding=utf-8
import sys, os
import unittest, mock, kiss
from twisted.python import log
from twisted.trial import unittest
from twisted.cred import credentials
class CredentialsChecker(unittest.TestCase):
"""
Testing the server credentials handling
"""
def _setUp_databases(self):
username_1 = 'user_name'
password_1 = 'user_pass'
email_1 = 'user#mail.org'
create_user_profile = mock.Mock()
self.db = mock.Mock()
self.db.username = username_1
self.db.password = password_1
self.db.email = email_1
def setUp(self):
log.startLogging(sys.stdout)
log.msg(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Flushing database")
#management.execute_from_command_line(['manage.py', 'flush',\
#'--noinput'])
log.msg(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Populating database")
#management.execute_from_command_line(['manage.py', 'createsuperuser',\
#'--username', 'superuser_name', '--email', 'superuser_name#email.org',\
#'--noinput'])
self._setUp_databases()
log.msg(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Running tests")
return
"""
Log in with valid credentianls. The server should return True
"""
def test_GoodCredentials(self):
creds = credentials.UsernamePassword('user_name', 'user_pass')
checker = DjangoAuthChecker()
d = checker.requestAvatarId(creds)
if __name__ == '__main__':
unittest.main()
If you create an object inheriting from the class unittest.TestCase test you have to use the native Python unittest module.
I'm doing some tests. A bunch of my test functions have common setups, so I decided I should use #with_setup decorator from nose.tools. I've simplified my problem down to this:
from nose.tools import with_setup
class TestFooClass(unittest.TestCase):
def setup_foo_value(self):
self.foo = 'foobar'
#with_setup(setup_foo_value)
def test_something(self):
print self.foo
I get the following error:
$ python manage.py test tests/test_baz.py
E
======================================================================
ERROR: test_something (project.tests.test_baz.TestFooClass)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/user/Coding/project-backend/project/../project/tests/test_baz.py", line 17, in test_something
print self.foo
AttributeError: 'TestFooClass' object has no attribute 'foo'
----------------------------------------------------------------------
It's like setup_foo_value is not being run at all. Any help would be really appreciated!
According to the doc:
writing tests: "Please note that method generators are not supported in unittest.TestCase subclasses"
testing tools: "with_setup is useful only for test functions, not for test methods or inside of TestCase subclasses"
So you can either move your test method into a function, or add a setUp method to your class.
Try this modification. It worked for me.
from nose.tools import with_setup
def setup_foo_value(self):
self.foo = 'foobar'
#with_setup(setup_foo_value)
def test_something(self):
print self.foo
The initial idea can be implemented in the following way
import wrapt
#wrapt.decorator
def setup_foo_value(wrapped, instance, args, kwargs):
instance.foo = 'foobar'
return wrapped(*args, **kwargs)
class TestFooClass(unittest.TestCase):
#setup_foo_value
def test_something(self):
print self.foo
Important that It additionally uses wrapt Python module