I am trying to code a suite test, I have one module which runs unit test correctly but I intend to add more modules and test them at once, so I have coded the following code:
#main.py
import unittest
from test.Services import TestOS
if __name__ == '__main__':
suite = unittest.TestSuite()
suite.addTests( TestOS.TestOS() )
unittest.TextTestRunner().run(suite)
TestOS.py
import unittest
from app.Services.OS import OS
class TestOS(unittest.TestCase):
os = OS()
def setUp(self):
pass
def tearDown(self):
pass
def testOSName(self):
self.assertEquals(self.os.getPlatform(), 'Windows')
def testOSVersion(self):
self.assertEquals(self.os.getVersion(), '7')
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
After running it, I get this output:
Finding files... done.
Importing test modules ... done.
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
It didn't find any test, What's wrong with my code?
suite.addTest( TestOS.TestOS() ) works only if your testcase contains a runTest() function.
Otherwise you need a "TestLoader" to detect the functions of TestOS that start with "test*".
#main.py
import unittest
from test.Services import TestOS
if __name__ == '__main__':
suite = unittest.TestSuite()
tests = unittest.defaultTestLoader.loadTestsFromTestCase(TestOS)
suite.addTests(tests)
unittest.TextTestRunner().run(suite)
modify your setUp method as follows
def setUp(self):
self.os = OS()
pass
Related
How do you do a unittest on a unittest. I have a unittest and obviously when it is succesfully it generates an ok message in the terminal but I have struggled to find a way of creating a test for the test based upon that.
Basically looking for a way to test if the below test returns ok.
The Test Below:
import unittest
class TestSum(unittest.TestCase):
def test_sum(self):
self.assertEqual(2+2, 4)
if __name__ == '__main__':
unittest.main()
What this returns in the shell :
Ran 1 test in 0.000s
OK
First of all you have to have function that does the calculation, so you pass that function to the test case.
Example:
import unittest
# Defined the function that does the calculation
def sum_numbers(x, y):
return x + y
class TestSum(unittest.TestCase):
def test_sum(self):
self.assertEqual(sum_numbers(2, 2), 4)
if __name__ == '__main__':
unittest.main()
Now this test will evaluate to ok and you can add more test to test_sum
In the attached script why 0 testcases are running
import unittest
def smg():
def add(x, y):
return x + y
class SimpleTest(unittest.TestCase):
def testadd1(self):
self.assertEquals(add(4, 5), 9)
if __name__ == '__main__':
unittest.main()
smg()
Gives
Ran 0 tests in 0.000s
What can be done to fix it kindly assist
You might be interested with unittest.TextTestRunner:
A basic test runner implementation that outputs results to a stream.
Sample usage:
However, should you want to customize the building of your test suite, you can do it yourself:
def suite():
suite = unittest.TestSuite()
suite.addTest(WidgetTestCase('test_default_widget_size'))
suite.addTest(WidgetTestCase('test_widget_resize'))
return suite
if __name__ == '__main__':
runner = unittest.TextTestRunner()
runner.run(suite())
Sample run for your case.
src.py
def add(x, y):
print("Add", x, y)
return x + y
test_src.py
import unittest
from src import add
class SimpleTest(unittest.TestCase):
def testadd1(self):
self.assertEqual(add(4, 5), 9)
if __name__ == '__main__':
unittest.main()
Running tests is as how it's done normally
$ python test_src.py # Using unittest
Add 4 5
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
$ pytest -q # Using pytest
.
1 passed in 0.06s
Now if you want to manually call it via function.
run_tests.py
import unittest
import test_src
def suite():
suite = unittest.TestSuite()
suite.addTest(test_src.SimpleTest('testadd1'))
return suite
def run():
runner = unittest.TextTestRunner()
runner.run(suite())
# run() # Uncomment if you want to try to run it as a script e.g. <python run_tests.py>
You can now just import the file and call run() whenever you need:
$ python3
>>> import run_tests
>>> run_tests.run()
Add 4 5
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
>>>
Take out the code inside of smg function and then run tests from your command-line with python -m unittest <Your Filename>.py.
Your code will look like this:
import unittest
def add(x, y):
return x + y
class SimpleTest(unittest.TestCase):
def testadd1(self):
self.assertEquals(add(4, 5), 9)
if __name__ == '__main__':
unittest.main()
Also you may get a deprecation warning for assertEquals. You might want to change it to assertEqual instead.
I'm trying to test my code with unit tests, but when I try to run it it just says
Finding files... done.
Importing test modules ... done.
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
Why isn't it working?
from Graph import Graph
import unittest
class GraphTest:
def setUp(self):
self.graph = Graph()
for i in range(5):
self.graph.addNode(i,"Node"+i)
self.graph.addEdge(1,5,"Edge1,5")
self.graph.addEdge(5,1,"Edge5,1")
self.graph.addEdge(3,2,"Edge3,2")
def test_Connected(self):
self.assertTrue(self.graph.isConnected(1,5))
self.assertTrue(self.graph.isConnected(5,1))
self.assertTrue(self.graph.isConnected(3,2))
self.assertFalse(self.graph.isConnected(2,3))
self.assertFalse(self.graph.isConnected(1,4))
if __name__ == '__main__':
unittest.main()
You should make your GraphTest a subclass of unittest.TestCase
It's mentioned in the documentation (http://nose.readthedocs.org/en/latest/api/core.html) but there don't seem to be any examples, and trying it seems to run all tests in the cwd.
Try this:
test_module.py:
import logging
import sys
import nose
logging.basicConfig(level=logging.INFO)
#here are some tests in this module
def test_me():
pass
if __name__ == '__main__':
#This code will run the test in this file.'
module_name = sys.modules[__name__].__file__
logging.debug("running nose for package: %s", module_name)
result = nose.run(argv=[sys.argv[0],
module_name,
'-v'])
logging.info("all tests ok: %s", result)
python test_module.py will get you:
test_module.test_me ... ok
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
INFO:root:all tests ok: True
Here's a minimal version of a main for nose:
if __name__ == '__main__':
import nose
nose.run(defaultTest=__name__)
And a version for nose2:
if __name__ == '__main__':
import nose2
nose2.main()
nose has runmodule function. So following works.
if __name__ == '__main__':
import nose
nose.runmodule()
I need to make a big python suitecase consisted of other suitcases and testcase which I have already made to execute together.
How do I do this?
For example, here there is a suitecase (suiteFilter.py) which I want to add:
import testFilter1
import testFilter2
import unittest
import sys
def suite():
return unittest.TestSuite((\
unittest.makeSuite(testFilter1.TestFilter1),
unittest.makeSuite(testFilter2.TestFilter2),
))
if __name__ == "__main__":
result = unittest.TextTestRunner(verbosity=2).run(suite())
sys.exit(not result.wasSuccessful())
And a testcase structure (Invoice.py):
from selenium import selenium
import unittest, time, re
from setup_tests import filename, fileForNrTest, username, password, server_url
fileW=open(filename,'a')
class TestInvoice(unittest.TestCase):
def setUp(self):
self.verificationErrors = []
self.selenium = selenium("localhost", 4444, "*firefox", server_url)
self.selenium.start()
def test_invoice(self):
sel = self.selenium
[...]
def tearDown(self):
self.selenium.stop()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
Thank you!
You could give some additional information like the structure of your program / test cases and suites. The way I do it is define a suite() for each module. So I have say for UserServiceTest module:
def suite():
"""
Gather all the tests from this module in a test suite.
"""
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.makeSuite(UserServiceTest))
return test_suite
if __name__ == "__main__":
#So you can run tests from this module individually.
unittest.main()
Then I have a main test for each package:
def suite():
"""
Gather all the tests from this package in a test suite.
"""
test_suite = unittest.TestSuite()
test_suite.addTest(file_tests_main.suite())
test_suite.addTest(userservice_test.suite())
return test_suite
if __name__ == "__main__":
#So you can run tests from this package individually.
TEST_RUNNER = unittest.TextTestRunner()
TEST_SUITE = suite()
TEST_RUNNER.run(TEST_SUITE)
You can do this the recursevly until the root of your project. So main test from package A will gather all module in package A + main test from subpackages of package A and so on. I was assuming you-re using unittest since you didn't give any additional details but I think this structure can be applied to other python testing frameworks as well.
Edit: Well I'm not quite sure I fully understand your problem, but from what I can understand you want to add both the suite defined in suiteFilter.py and the testcase defined in Invoice.py in the same suite? If so why not just do in a mainTest.py for example:
import unittest
import suiteFilter
import Invoice
def suite()
test_suite = unittest.TestSuite()
test_suite.addTest(suiteFilter.suite())
test_suite.addTest(unittest.makeSuite(Invoice))
if __name__ == "__main__":
result = unittest.TextTestRunner(verbosity=2).run(suite())
sys.exit(not result.wasSuccessful())
You can add tests and suites all the same to a test_suite.