I am implementing the following class:
class TestInitializeConnection(TestMyDriver)
The super class (TestMyDriver) is a TestCase, meaning:
class TestMyDriver(test.TestCase):
the super class has an attribute named driver that basically is sort of a mock of the tested driver and it declared as follows:
self.driver = mocks.MyDriver()
now In my (TestInitializeConnection) I want to implement the following test:
def test_initialize_connection(self):
self.driver.initialize_connection(self.volume, self.connector)
Somewhere in the code of the function initialize_connection, there is a private method that is being called
specs = self._get_specs(volume)
and I want to make my test to tell this call of _get_specs(volume) to return a specific value, for example a dictionary with the value:
{'iops': 100, 'bandwith': 200}
What is the best way of doing so?
Thanks,
Matan
Just mock it out.
def test_initialize_connection(self):
with mock.patch.object(
self.driver,
'_get_specs',
return_value='your_fake_value') as mock_specs:
# Do something with self.driver
Related
I have a class ProductionClass with a method method_to_test which I want to test. Class ProductionClass has dependency to api, which I want to mock in the test.
from my_module.apis import api
class ProductionClass:
def method_to_test:
data = api.method_to_mock()
api.method_to_check_call(data)
The test code is as follows:
For api I have a mock class MockApi that I use by refering to it in the #patch decorator.
from unittest.mock import patch, MagicMock
class MockApi:
def method_to_mock():
return some_mock_data
def method_to_check_call(data):
pass
class TestClass:
#patch('my_module.apis.api', MagicMock(return_value=MockApi()))
def test_check_called_with(self):
from module_of_class_production_class.ProductionClass import method_to_test
mock_api = MockApi()
method_to_test()
some_data = { ... }
mock.method_to_check_call.assert_called_with(some_data)
The problem is that it does not work because mock_api is not the same instance of MockApi that is provided in the #patch decorator. Is there a better way to test that?
I have not tested this, but I think that your patch object will get passed as first argument to test_check_called_with like so:
#patch('my_module.apis.api', MagicMock(return_value=MockApi()))
def test_check_called_with(self, your_magic_mock):
# Rest of code
You can also use the with construct like so:
def test_check_called_with(self):
my_api = MockApi()
with patch('my_module.apis.api', MagicMock(return_value=my_api)) as my_mock_api:
# Your code here
You can checkout the official python documentation here for more details: https://docs.python.org/3/library/unittest.mock.html#quick-guide
I want to wrap the selenium webdriver in my own class, that each time I will call a method from my class it will handle calling and error handling to the webdriver class. what is the correct way to do it ?
class myClass():
browser = ... selenium web driver ...
def find_element_by_xpath(self, value):
try
browser.find_element_by_xpath(value)
except:
....
can myClass have the same method name ?
There are multiple valid ways to handle the calling and error handling of the webdriver class and yours should be fine.
Yes, myClass can have the same method names but you need to make sure you're calling the right thing. E.g
myClassInstance = myClass()
myClassInstance.find_element_by_xpath('thing')
will call browser.find_element_by_xpath just fine
I'm trying to complete my unit tests for the errbot plugin I am writing. Can anyone tell me how to mock out a helper method which is used by a botcmd method?
Example:
class ChatBot(BotPlugin):
#classmethod
def mycommandhelper(cls):
return 'This is my awesome commandz'
#botcmd
def mycommand(self, message, args):
return self.mycommandhelper()
How can I mock the mycommandhelper class when executing the my command class? In my case this class is performing some remote operations which should not be executed during unit testing.
A very simple/crude way would be to simply redefine the function that does the remote operations.
Example:
def new_command_helper(cls):
return 'Mocked!'
def test(self):
ch_bot = ChatBot()
ch_bot.mycommandhelper = new_command_helper
# Add your test logic
If you'd like to have this method mocked throughout all of your tests, simply do it in the setUp unittest method.
def new_command_helper(cls):
return 'Mocked!'
class Tests(unittest.TestCase):
def setUp(self):
ChatBot.mycommandhelper = new_command_helper
After a lot of fiddling around the following seems to work:
class TestChatBot(object):
extra_plugin_dir = '.'
def test_command(self, testbot):
def othermethod():
return 'O no'
plugin = testbot.bot.plugin_manager.get_plugin_obj_by_name('chatbot')
with mock.patch.object(plugin, 'mycommandhelper') as mock_cmdhelper:
mock_cmdhelper.return_value = othermethod()
testbot.push_message('!mycommand')
assert 'O no' in testbot.pop_message()
Although I believe using patch decorators would be cleaner.
I am quite new to Python (and stackoverflow) and I need some help. I have 2 classes as below
class baseClass(object):
def __init__(self):
self.attribute = None
def baseMethod(self):
return 'xxx' + str(self.attribute)
class classA(baseClass):
field = "test"
def __init__(self):
self.attribute = "attribute value"
And I would like to do something like below:
objectA = classA()
afterBaseMethod = objectA.baseMethod()
afterBaseMethod.field
But I'm getting error message
AttributeError: 'str' object has no attribute 'field'
In fact I would like for baseMethod() to return type objectA (so my child class type).
How can I change my class definitions to achieve that?
Sorry Guys, I was not precise enough what I want to do. In fact I would like to implement page object in python for webdriver testing. My code below.
from selenium import webdriver
########## classes definitions
class BasePageObject:
def __init__(self, driver):
self.locator = None
self.driver = driver
def getByLocator(self):
return self.driver.find_element_by_css_selector(self.locator)
class MainPage(BasePageObject):
def __init__(self, driver):
self.driver = driver
def getHeader(self):
# I expect here to receive HeaderPageObject, not WebElement (as returned by getByLocator())
return HeaderPageObject(self.driver).getByLocator()
class HeaderPageObject(BasePageObject):
def __init__(self, driver):
self.driver = driver
self.locator = '#header'
def doSomethingWithHeader(self):
pass
###########################
driver = webdriver.Firefox()
driver.get("https://www.linkedin.com")
mainPage = MainPage(driver)
header = mainPage.getHeader()
header.doSomethingWithHeader()
and when I run it I'm getting
header.doSomethingWithHeader()
AttributeError: 'WebElement' object has no attribute 'doSomethingWithHeader'
Your code as published simply defines the two classes, which means that you haven't even told us where this reported error occurs or what you did to induce it. But Python's class mechanism is well up to this task.
Objects know what type they are, so even when a method is inherited from a superclass it runs on the subclass instance (i.e. self will be an instance of the subclass). Here's some code to demonstrate - two classes, each of which use the base class to report their type:
class baseClass(object):
def baseMethod(self):
return type(self)
class classA(baseClass):
pass
b = baseClass()
print b.baseMethod()
a = classA()
print a.baseMethod()
which outputs
<class '__main__.baseClass'>
<class '__main__.classA'>
You can see that a classA object prints its type out correctly, so it knows what type of object made the call. I hope this tells you what you need to know.
If you want it to return the class from which it was called, you can do:
def baseMethod(self):
return self.__class__()
However, it's not clear from your post what else you want it to do. Your post just shows it returning a string that will be the same for every instance of your class. It's not clear what the purpose of baseMethod is.
I want to test this class using python unittest framework and also mockito.
class ISightRequestEngine(object):
def __init__(self, pInputString=None):
self.__params = (pInputString)
def openHTTPConnection(self):
pass
def __closeHTTPConnection(self):
pass
def testFunc(self):
print 'test function called'
def startEngine(self):
self.__params.parseinputString()
self.openHTTPConnection()
self.testFunc()
def processRequest(self, header = None):
pass
I wanted to test that function startEngine() calls testFunc().
Similar to what we do in our mocked class,
obj = mock(ISightRequestEngine)
obj.startEngine()
try:
verify(obj).startEngine()
except VerificationError:
Unfortunately this only verifies whether the startEngine function is called or not, but it does not give the actual function call and I cannot verify that whether the call to testFunc() has been made or not.
Is there any way to test this scenario?
I am new to testing world and framework.
In your example you are testing your mock.
You create a mock of ISightRequestingEngine
You call startEngine() method of that mock
You verify that the mocked object was called
What you want to do is:
Mock out testFunc()
Call startEngine()
Verify that testFunc() was called
I'm not familiar with mockito, but what from what I can make up from the documentation, I think you have to do something like the following:
from mockito import mock, verify
# Setup ---------------------------------------------
my_mock = mock(ISightRequestingEngine)
system_under_test = ISightRequestingEngine()
system_under_test.testFunc = my_mock.testfunc # Mock out only testFunc()
# Exercise ------------------------------------------
system_under_test.startEngine()
# Verify --------------------------------------------
verify(my_mock).testFunc()
Having similar such issue, where I am bit lost in writing the test case
class UserCompanyRateLimitValidation:
def __init__(self, user_public_key):
self.adapter = UserAdapter(user_public_key)
container = self.adapter.get_user_company_rate_limit()
super(UserCompanyRateLimitValidation, self).__init__(container,\
UserCompanyRateLimitValidation.TYPE)
I have to test this function. I have written test case something like this. I have tried to mock the UserAdapter class but I am not able to do so completely.
def test_case_1():
self.user_public_key = 'TEST_USER_PUBLIC_KEY_XXXXXX1234567890XXXXX'
UserAdapter_mock = mock(UserAdapter)
when(UserAdapter_mock).get_user_company_rate_limit().\
thenReturn(self.get_container_object())
self.test_obj = UserCompanyRateLimitValidation(self.user_public_key)
Here if you see I have mocked get_user_company_rate_limit() call from the testable function, container = self.adapter.get_user_company_rate_limit()
but I am still not able to figure out the way in which I can mock this call,
self.adapter = UserAdapter(user_public_key)