I am trying some Python with selenium, I have some defined tests in simpleUsageUnittest.py:
import unittest
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class PythonOrgSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
# #unittest.skip("skip test_001")
def test_001_search_in_python_org(self):
driver = self.driver
driver.get("http://www.python.org")
self.assertIn("Python", driver.title)
elem = driver.find_element_by_name("q")
elem.send_keys("selenium")
elem.send_keys(Keys.RETURN)
# #unittest.skip("skip test_002")
def test_002_goole_and_stack_test_test(self):
driver_g = self.driver
driver_g.get("http://www.google.com")
self.assertIn("Google", driver_g.title)
body_g = driver_g.find_element_by_tag_name("body")
body_g.send_keys(Keys.CONTROL + 't')
driver_g.get("http://stackoverflow.com")
self.assertIn("Stack", driver_g.title)
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main(warnings = 'ignore')
Alone this set is working perfectly, but then I am trying to create some suite, testTestSuite.py:
import unittest
import simpleUsageUnittest
import sys
def suite():
testSuite = unittest.TestSuite()
testSuite.addTest(simpleUsageUnittest.PythonOrgSearch.setUp)
testSuite.addTest(simpleUsageUnittest.PythonOrgSearch.test_001_search_in_python_org)
testSuite.addTest(simpleUsageUnittest.PythonOrgSearch.test_002_goole_and_stack_test_test)
testSuite.addTest(simpleUsageUnittest.PythonOrgSearch.tearDown)
return testSuite
if __name__ == "__main__":
result = unittest.TextTestRunner(verbosity=2).run(suite())
sys.exit(not result.wasSuccessful())
And while running this suite I encounter AttributeError: 'TextTestResult' object has no attribute 'assertIn', and since I dont exactly understand it I cannot fix it ;) If I delete assertIn lines in simpleUsageUnittest.py - then it is working again, but it is of course not what I want to do! Also Asserts in Python 2.7 not working for me example assertIn was not a big help since I am using Python 3.3.5 and Selenium 2.41.0. Can someone explain it to me? Or direct what attributes can I use to save my assert? ;)
Full trace:
C:\Users\zzz\Python\selenium_tutorial>python testTestSuite.py
Traceback (most recent call last):
File "testTestSuite.py", line 14, in <module>
result = unittest.TextTestRunner(verbosity=2).run(suite())
File "C:\Python33\lib\unittest\runner.py", line 168, in run
test(result)
File "C:\Python33\lib\unittest\suite.py", line 67, in __call__
return self.run(*args, **kwds)
File "C:\Python33\lib\unittest\suite.py", line 105, in run
test(result)
File "C:\Users\zzz\Python\selenium_tutorial\simpleUsageUnittest.py", line
18, in test_001_search_in_python_org
self.assertIn("Python", driver.title)
AttributeError: 'TextTestResult' object has no attribute 'assertIn'
SOLUTION
OK, it looks like in my testTestSuite.py, while executing, TextTestRunner treats "self.asserIn" lines in simpleUsageUnittest.py as self == TextTestRunner not as self == TestCase (I dont know if I explain/understand it correctly, but it is how i see it ;)). Here is fixed testTestSuite.py:
import unittest
import simpleUsageUnittest
import sys
def suite():
testSuite = unittest.TestSuite()
testSuite.addTest(simpleUsageUnittest.PythonOrgSearch('test_001_search_in_python_org'))
testSuite.addTest(simpleUsageUnittest.PythonOrgSearch('test_002_goole_and_stack_test_test'))
return testSuite
if __name__ == "__main__":
result = unittest.TextTestRunner(verbosity=2).run(suite())
sys.exit(not result.wasSuccessful())
'setUp' and 'tearDown' are missing because they are called automatically after every 'test'.
SOLUTION
OK, it looks like in my testTestSuite.py, while executing, TextTestRunner treats "self.asserIn" lines in simpleUsageUnittest.py as self == TextTestRunner not as self == TestCase (I dont know if I explain/understand it correctly, but it is how i see it ;)). Here is fixed testTestSuite.py:
import unittest
import simpleUsageUnittest
import sys
def suite():
testSuite = unittest.TestSuite()
testSuite.addTest(simpleUsageUnittest.PythonOrgSearch('test_001_search_in_python_org'))
testSuite.addTest(simpleUsageUnittest.PythonOrgSearch('test_002_goole_and_stack_test_test'))
return testSuite
if __name__ == "__main__":
result = unittest.TextTestRunner(verbosity=2).run(suite())
sys.exit(not result.wasSuccessful())
'setUp' and 'tearDown' are missing because they are called automatically after every 'test'.
Related
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.
On executing this unittest getting
AttributeError: 'BaseUnit' object has no attribute 'driver'
import unittest
import redis
from selenium import webdriver
redis = redis.Redis(host='abc', port='123')
keys = redis.keys('*')
raw_baseunit = redis.get('test:baseunit')`enter code here`
class BaseUnit(unittest.TestCase):
def setup(self):
self.driver = webdriver.PhantomJS()
def test(self):
self.driver.get("myurl")
self.driver.find_element_by_id('username').send_keys("ngeo_pur1")
self.driver.find_element_by_id('password').send_keys("anything")
self.driver.find_element_by_xpath('html/body/div[1]/div[3]/div/section/div/form/ul/li[5]/div[2]/div/input').click()
self.driver.get("url")
self.driver.find_element_by_partial_link_text("18757424").click()
self.driver.find_element_by_xpath(".//*[#id='tabs']/nav/ul/li[2]/a/i").click()
Actual = self.driver.find_element_by_xpath(".//*[#id='subcat_baseModelSection.baseModelChoice']/div/div[1]").text
keys = redis.keys('*')
raw_baseunit = redis.get('test:baseUnit')
print "Actual Base Unit=",Actual
print "Expected Base Unit=",raw_baseunit
self.assetEquals(raw_baseunit,Actual)
def teardown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()
Tried changing the class name 'BaseUnit' as well
Try modifying the setup class's name to this. I just read the doc and the setup class is written with the U in uppercase
def setUp(self):
self.driver = webdriver.PhantomJS()
The methods you want to override in unittest.TestCase are setUp and tearDown (note the capital "U" and "D"), not setup and teardown.
Your all-lowercase setup method doesn't get called before the test methods run (if it gets called at all), so the self.driver attribute doesn't exist when then test method tries to use it.
So I've been having this issue for some time and can't find a solution.I have this run code which is pretty basic. I want to test for the expected output, "TEST" ,when I use side_effects to mock the input. The first time the input function is called I mock 'y' and then I mock '1' the second time it's called, which should then trigger the print statement. The problem is the output that is coming back is empty. I don't know whats going on, but when I run the main method manually and enter the inputs I get the expected output so I know the run code works as intended, but something funky is happening during the test.
here is my run code
def main():
newGame = input("")
if newGame == 'y':
print("1.Scallywag\n2.Crew\n3.Pirate")
difficulty = input("")
if difficulty == '1':
print("TEST")
main()
and here is my test code
import unittest
from unittest.mock import patch
import io
import sys
from Run import main
class MyTestCase(unittest.TestCase):
#patch('builtins.input', side_effects=['y','1'])
def test_output(self,m):
saved_stdout = sys.stdout
try:
out = io.StringIO()
sys.stdout = out
main()
output = out.getvalue().strip()
self.assertIn("TEST", output)
finally:
sys.stdout = saved_stdout
if __name__ == "__main__":
unittest.main()
and here is the AssertionError i get back along with the trace back, take note that its expecting "" which shouldn't be the case.
F
======================================================================
FAIL: test_output (__main__.MyTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python33\lib\unittest\mock.py", line 1087, in patched
return func(*args, **keywargs)
File "C:\Users\jsalce\Desktop\Testcases\Test.py", line 20, in test_output
self.assertIn("TEST", output)
AssertionError: 'TEST' not found in ''
----------------------------------------------------------------------
Ran 1 test in 0.006s
FAILED (failures=1)
Thank you all in advance
You patch for input does not work as required because you are not giving it a function. Try this:
import unittest
from unittest.mock import patch, MagicMock
import io
import sys
from Run import main
class MyTestCase(unittest.TestCase):
##patch('builtins.input', side_effects=['y','1'])
#patch('builtins.input', MagicMock(side_effect=['y','1']))
def test_output(self):
saved_stdout = sys.stdout
try:
out = io.StringIO()
sys.stdout = out
main()
output = out.getvalue().strip()
self.assertIn("TEST", output)
#I used equals to see if I am truly grabbing the stdout
#self.assertEquals("TEST", output)
finally:
sys.stdout = saved_stdout
if __name__ == "__main__":
unittest.main(verbosity=2)
And also, you do not need variable 'm' in your test_output signature.
Print("String", file=out)
Is what you're looking for, you'll need to pass out to main though.
I know it is a bit silly question, but using links provides below, I am still unable to create testsuite.
I have now two test cases (there will be much more), let assume that the name of there are:
class step1(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_case1(self):
[...]
if __name__ == "__main__":
unittest.main()
and:
class step2(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_case2(self):
[...]
if __name__ == "__main__":
unittest.main()
I want to create other file .py file: testsuite, which can aggregate test_case1, test_case2, test_case3...
I tried something like that, for example:
import unittest
import step1
import step2
def suite():
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.step1(test_case1))
test_suite.addTest(unittest.step2(test_case2))
if __name__ == "__main__":
result = unittest.TextTestRunner(verbosity=2).run(suite())
sys.exit(not result.wasSuccessful())
Error: AttributeError: 'module' object has no attribute 'step1'
You can use addTest() and pass TestCase instance to it, you also miss return statement:
def suite():
test_suite = unittest.TestSuite()
test_suite.addTest(step1())
test_suite.addTest(step2())
return test_suite
or, in one line using addTests():
test_suite.addTests([step1(), step2()])
I have a bunch of modules and for each module I have a unittest based test. I want to define the main in each module to run its tests, but I get import errors because of import loops (specifically when I use from mymodule import myclass in the test.
I suspect this is a solved problem, so - what should I put in my module's main to run its corresponding test?
If I understand you correctly, you've got a file (lets call it mymodule.py) that looks like this:
import unittest
from mymoduletests import MyModuleTests
class myclass(object):
def somefunction(self, x):
return x*x
if __name__ == '__main__':
unittest.main()
and a separate file (lets call it mymoduletests.py) that looks something like this:
import unittest
from mymodule import myclass
class MyModuleTests(unittest.TestCase):
def test_somefunction(self):
m = myclass()
self.assertEqual(4, m.somefunction(2))
If you run mymodule.py you get the following result:
Traceback (most recent call last):
File "mymodule.py", line 2, in <module>
from mymoduletests import MyModuleTests
File "/Users/srgerg/Desktop/p/mymoduletests.py", line 2, in <module>
from mymodule import myclass
File "/Users/srgerg/Desktop/p/mymodule.py", line 2, in <module>
from mymoduletests import MyModuleTests
ImportError: cannot import name MyModuleTests
However, if you change mymodule.py to this:
class myclass(object):
def somefunction(self, x):
return x*x
if __name__ == '__main__':
import unittest
from mymoduletests import MyModuleTests
unittest.main()
and then run it, you get:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Have I understood you correctly?