Tests from other files are run with unittest.main() - python

I am using spyder(3.3.4) to run some python(3.7) unit tests. I have two different scripts that use unittest and unittest.main() open in spyder: test_1.py and test_2.py. Both are saved in the same folder.
If I run test_1.py before ever running test_2.py, I get the expected results; only the tests in test_1.py are run.
If I then run test_2.py, the tests in test_2.py are run, but then the tests in test_1.py are run also. If I restart the Ipython kernel in between running test_1.py and running test_2.py, then only test_2.py runs, as expected. Weirdest of all, if I close test_1.py after running it, the output of test_1.py is still printed when running test_2.py.
Why is this happening?
I am guessing this has do to do with how the __name__ variable is saved in the IPython console or how unittest.main() searches for tests?
Here's the code for my two test scripts:
test_1.py:
import unittest
class TestStuff(unittest.TestCase):
def test_1(self):
print('test 1')
pass
def test_2(self):
print('test 2')
pass
if __name__ == '__main__':
unittest.main()
and test_2.py:
import unittest
class TestOtherStuff(unittest.TestCase):
def test_this(self):
print('this')
pass
def test_that(self):
print('that')
pass
if __name__ == '__main__':
unittest.main()
Thanks!

Related

On Running the test suite: Runs the test suite shows test passed Notification but displays "Empty Suite"

Here's my code but it shows no Tests found, and prints Empty Suite
import unittest
import time
from selenium import webdriver
class LoginTest(unittest.TestCase):
driver = webdriver.Chrome(executable_path="C:\\Users\\win\\Desktop\\chromedriver.exe")
#classmethod
def setUpClass(cls):
cls.driver = webdriver.Chrome(executable_path="C:\\Users\\win\\Desktop\\chromedriver.exe")
cls.driver.implicitly_wait(10)
def Test(self):
self.driver.get("https://opensource-demo.orangehrmlive.com/")
self.driver.find_element_by_id("txtPassword").send_keys("admin123")
self.driver.find_element_by_id("txtUsername").send_keys("Admin")
self.driver.find_element_by_id("btnLogin").click()
time.sleep(2)
#classmethod
def tearDownClass(cls):
cls.driver.close()
cls.driver.quit()
print("Test Complete")
if __name__ == '__main__':
unittest.main()
I wrote this code, but on running my Test Suite it displays as follows:
Testing started at 2:47 PM ...
C:\PycharmProject\OrangeHRM\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.3\plugins\python-ce\helpers\pycharm\_jb_unittest_runner.py" --target LoginTest.LoginTest
Launching unittests with arguments python -m unittest LoginTest.LoginTest in C:\PycharmProject\OrangeHRM\ScriptsDemo\Tests
Ran 0 tests in 0.000s
OK
Process finished with exit code 0
No Tests were found
Empty suite
In unittest library exists a naming convention that all the tests start with 'test', this informs the test runner about which methods represent tests.
You have to change your 'Test' method to 'test'

Running python unittests from TestSuite in PyCharm will not order the tests alphabetically, but running the same file in terminal will order them

I am working on writing unit tests, but they needed to run as I added them to the TestSuite. So my problem is when I run the testrunner.py from the PyCharm I get what I need, but if I run the same file from the terminal the tests will be sorted alphabetically, and that is bad for me.
For example: I have 2 tests, test_dummy_01.py and test_dummy_01 in the "tests/" folder of my Framework. Also I created the testrunner.py file where I add the TestDummy02 class first and after the TestDummy01 class. So when I run the the testrunner.py from PyCharm the test_dummy_02.py test will run first and the test_dummy_01.py by second which is good for me. Now I need the same behavior when I run the same file in the terminal, but it will always run the test_dummy_01.py file first. So please if anyone can help me?
Folder hierarchy of my files:
Project/
tests/
test_dummy_01.py
test_dummy_02.py
testrunner.py
The test_dummy_01.py test: - the test_dummy_02.py file is same as this
class TestDummy01(BaseTestCase):
def setUp(self):
super(TestDummy, self).setUp()
def test_dummy_01(self):
driver = self.driver
login = LoginPage(driver)
login.enter_username("Something")
def tearDown(self):
super(TestDummy, self).tearDown()
The testrunner.py file where I added the order
import sys
import unittest
from tests.test_dummy_01 import TestDummy01
from tests.test_dummy_02 import TestDummy02
def suite():
suite_x = unittest.TestSuite()
suite_x.addTest(unittest.makeSuite(TestDummy02)) # In PyCharm this test is runned first, but in Teminal this will run by second
suite_x.addTest(unittest.makeSuite(TestDummy01))
return suite_x
def run():
result = unittest.TextTestRunner(verbosity=2).run(suite())
if not result.wasSuccessful():
sys.exit(1)
if __name__ == '__main__':
run()
PyCharm terminal

Run unittest.main() from a python invoke task

I am trying to run some unittest tests via a Python Invoke library, but my poor knowledge of Python prevents me from doing so.
This is the sample code I have:
my_tests.py
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
def main():
unittest.main()
if __name__ == '__main__':
main()
tasks.py
from invoke import task
#task
def tests(ctx):
main()
#task
def other_task(ctx):
print("This is fine")
def main():
import my_tests
import unittest
unittest.main(module='my_tests')
if __name__ == '__main__':
main()
And this is what I get:
C:\ittle_projects\invoke_unittest>python my_tests.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.002s
OK
C:\ittle_projects\invoke_unittest>python tasks.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.001s
OK
C:\ittle_projects\invoke_unittest>inv tests
E
======================================================================
ERROR: tests (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module 'my_tests' has no attribute 'tests'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
The tests run fine from my_tests.py and from tasks.py, but when I use invoke stuff breaks.
How can I make it work or where should I look next?
The issue you are running into is that unittest.main() uses the command line arguments your program is called with to determine which tests to run. Since your program is being executed as inv tests, the first argument to your program is tests, so unittest is attempting to run tests for a module name tests which does not exist.
You can get around this by popping the last argument (tests) from the system arguments list:
import sys
from invoke import task
#task
def tests(ctx):
# Pop "tests" off the end of the system arguments
sys.argv.pop()
main()
#task
def other_task(ctx):
print("This is fine")
def main():
import my_tests
import unittest
unittest.main(module='my_tests')
if __name__ == '__main__':
main()

Python Unit-Testing: In Nose is there a way to skip a test case from nose.run()?

I am writing a set of test cases say Test1, Test2 in a test module.
Is there a way to skip Test1 or selectively execute only Test2 in that module using the command nose.main()?
My module contains,
test_module.py,
class Test1:
setUp(self):
print('setup')
tearDown(self):
print('teardown')
test(self):
print('test1')
class Test2:
setUp(self):
print('setup')
tearDown(self):
print('teardown')
test(self):
print('test2')
I run it from a different python file using,
if __name__ == '__main__':
nose.main('test_module')
The notion of skipping test and not running a test are different in the context of nose: skipped tests will be reported as skipped at the end of the test result. If you want to skip the test you would have to monkey patch your test module with decorators or do some other dark magic.
But if you want to just not run a test, you can do it the same way you would do it from the command line: using --exclude option. It takes a regular expression of the test you do not want to run. Something like this:
import sys
import nose
def test_number_one():
pass
def test_number_two():
pass
if __name__ == '__main__':
module_name = sys.modules[__name__].__file__
nose.main(argv=[sys.argv[0],
module_name,
'--exclude=two',
'-v'
])
Running the test will give you:
$ python stackoverflow.py
stackoverflow.test_number_one ... ok
----------------------------------------------------------------------
Ran 1 test in 0.002s
OK

Python unittesting: run tests in another module

I want to have the files of my application under the folder /Files, whereas the test units in /UnitTests, so that I have clearly separated app and test.
To be able to use the same module routes as the mainApp.py, I have created a testController.py in the root folder.
mainApp.py
testController.py
Files
|__init__.py
|Controllers
| blabla.py
| ...
UnitTests
|__init__.py
|test_something.py
So if in test_something.py I want to test one function that is in /Files/Controllers/blabla.py, I try the following:
import unittest
import Files.Controllers.blabla as blabla
class TestMyUnit(unittest.TestCase):
def test_stupid(self):
self.assertTrue(blabla.some_function())
if __name__ == '__main__':
unittest.main()
And then from the file testController.py, I execute the following code:
import TestUnits.test_something as my_test
my_test.unittest.main()
Which outputs no failures, but no tests executed
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
[Finished in 0.3s]
I have tried with a test that has no dependences, and if executed as "main" works, but when called from outside, outputs the same:
import unittest
def tested_unit():
return True
class TestMyUnit(unittest.TestCase):
def test_stupid(self):
self.assertTrue(tested_unit())
if __name__ == '__main__':
unittest.main()
Question: how do I get this to work?
The method unittest.main() looks at all the unittest.TestCase classes present in the context.
So you just need to import your test classes in your testController.py file and call unittest.main() in the context of this file.
So your file testController.py should simply look like this :
import unittest
from UnitTests.test_something import *
unittest.main()
In test_something.py, do this:
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestMyUnit, 'test'))
return suite
In testController.py, do this:
from TestUnits import test_something
def suite():
suite = unittest.TestSuite()
suite.addTest(test_something.suite())
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
There is a workaround of using subprocess.call() to run tests, like:
import subprocess
args = ["python", "test_something.py"]
subprocess.call(args)

Categories

Resources