I try to order my tests but the problem is that the test_add will be first and I need that the test_remove will be first. I try to use sortTestMethodsUsing but I still get test_add as the first test.
import unittest
class TestSum(unittest.TestCase):
def test_remove(self):
print("1")
def test_add(self):
print("2")
if __name__ == '__main__':
loader = unittest.TestLoader()
loader.sortTestMethodsUsing = None
unittest.main(testLoader=loader)
Related
Here is my Code, I'm not sure if I lack or miss some code but it is not skipping the test2.
import unittest
class AppTesting (unittest.TestCase):
skipYes = ""
def test_1(self):
print("Test 1: " + str(AppTesting.skipYes))
AppTesting.skipYes = "Yes"
print("Test 1: " + str(AppTesting.skipYes))
#unittest.skipIf(str(skipYes) == "Yes", "Skip condition")
def test_2(self):
print("Test 2 skipYes is: " + str(AppTesting.skipYes))
print("This is Test 2")
def test_3(self):
print("This is Test 3")
if __name__ == "__main__":
unittest.main()
Your decorator is evaluated when the module is loaded on the test run together with the test class definition, hence the skipYes variable at that point will always be an empty string "", as defined in the class.
Changing this variable inside the test methods won't make any difference, as the test runner has already collected what tests to run and what to skip.
As a solution, from Python 3.4 you can use subtests:
class MyTestCase(unittest.TestCase):
def test_some(self):
skipTest = False
with self.subTest('subtest1'):
self.assertTrue(False)
...
if not skipTest:
with self.subTest('subtest2'):
self.assertFalse(True)
DOCS: https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests
I have the below code:
master.py
def create():
master = falcon.API(middleware=Auth())
msg = Message()
master.add_route('/message', msg)
master = create()
if __name__ == '__main__':
httpd = simple_server.make_server("127.0.0.1", 8989, master)
process = Thread(target=httpd.serve_forever, name="master_process")
process.start()
#Some logic happens here
s_process = Thread(target=httpd.shutdown(), name="shut_process")
s_process.start()
s.join()
I tried to create the below test case for the below:
from falcon import testing
from master import create
#pytest.fixture(scope='module')
def client():
return testing.TestClient(create())
def test_post_message(client):
result = client.simulate_post('/message', headers={'token': "ubxuybcwe"}, body='{"message": "I'm here!"}') --> This line throws the error
assert result.status_code == 200
I tried running the above but get the below error:
TypeError: 'NoneType' object is not callable
I actually am unable to figure out how I should go about writing the test case for this.
Based on what #hoefling said, the below fixed it:
master.py
def create():
master = falcon.API(middleware=Auth())
msg = Message()
master.add_route('/message', msg)
return master
master = create()
if __name__ == '__main__':
httpd = simple_server.make_server("127.0.0.1", 8989, master)
process = Thread(target=httpd.serve_forever, name="master_process")
process.start()
#Some logic happens here
s_process = Thread(target=httpd.shutdown(), name="shut_process")
s_process.start()
s.join()
And then the test case works:
from falcon import testing
from master import create
#pytest.fixture(scope='module')
def client():
return testing.TestClient(create())
def test_post_message(client):
result = client.simulate_post('/message', headers={'token': "ubxuybcwe"},
body='{"message": "I'm here!"}')
assert result.status_code == 200
Thanks a lot #hoefling!
Here is my codes.
import unittest
import warnings
def function_that_raises_CustomWarning():
warnings.warn("warning")
return True
class test(unittest.TestCase):
def test(self):
is_this_True = False
is_CustomWarning_raised = False
try:
is_this_True = function_that_raises_CustomWarning()
except Warning:
is_CustomWarning_raised = True
self.assertTrue(is_this_True)
self.assertTrue(is_CustomWarning_raised)
if __name__ == "__main__":
unittest.main()
is_this_True in self.assertTrue(is_this_True) is False, hence failed the test.
What I want is for is_this_True in self.assertTrue(is_this_True) to be True. However, the return value is not "captured" since the value is returned after a warning is raised in function_that_raises_CustomWarning().
How can I return the value in function_that_raises_CustomWarning() but also "captured" the warning in except?
When I run your code with 3.6 on Windows, the failure is with self.assertTrue(is_CustomWarning_raised). By default, a warning is not an exception and cannot be caught with except:. The solution is to use assertWarns or assertWarnsRegex. I used the latter to show how it might be used to add an extra test.
import unittest
import warnings
def function_that_raises_CustomWarning():
warnings.warn("my warning")
return True
class test(unittest.TestCase):
def test(self):
is_this_True = False
with self.assertWarnsRegex(Warning, 'my warning'):
is_this_True = function_that_raises_CustomWarning()
self.assertTrue(is_this_True)
if __name__ == "__main__":
unittest.main()
I have 2 modules: test1.py and test2.py.
test1.py
import unittest
class ArithTest (unittest.TestCase):
def test_run (self):
""" Test addition and succeed. """
self.failUnless (1+1==2, 'one plus one fails!')
self.failIf (1+1 != 2, 'one plus one fails again!')
self.failUnlessEqual (1+1, 2, 'more trouble with one plus one!')
if __name__ == '__main__':
unittest.main()
test2.py
import unittest
class AlgTest (unittest.TestCase):
def test_alg (self):
""" Test addition and succeed. """
self.assertEqual(1+1, 2, '1+1 != 2? whaaat?')
self.assertEqual(6-5, 1, '6-5 != 5 wft python?')
if __name__ == '__main__':
unittest.main()
-Now-
I wanna create a new module test3.py to test test1.py and test2.py. I don't now how, i read on internet about suit tests but i don't understand.
I don't want to create one more method with calling tests, and call them on test3.py.
I wanna group them and call in test3.py and they run as unitests
test1.py
import unittest
class ArithTest (unittest.TestCase):
def test_run (self):
""" Test addition and succeed. """
self.failUnless (1+1==2, 'one plus one fails!')
self.failIf (1+1 != 2, 'one plus one fails again!')
self.failUnlessEqual (1+1, 2, 'more trouble with one plus one!')
def runTest(self):
self.test_run()
if __name__ == '__main__':
unittest.main()
test2.py
import unittest
class AlgTest (unittest.TestCase):
def test_alg (self):
""" Test addition and succeed. """
self.assertEqual(1+1, 2, '1+1 != 2? whaaat?')
self.assertEqual(6-5, 1, '6-5 != 5 wft python?')
def runTest(self):
self.test_alg()
if __name__ == '__main__':
unittest.main()
test3.py
from .test1 import ArithTest
from .test2 import AlgTest
import unittest
def suite_2():
suite = unittest.TestSuite()
suite.addTest(ArithTest())
suite.addTest(AlgTest())
return suite
if __name__ == '__main__':
runner = unittest.TextTestRunner()
test_suite = suite_2()
runner.run(test_suite)
Also add a __init__.py
Run it with python3 -m folder_name.test3
I tried to word the question right, but what I'm trying to do is check the stdout of a list after the while statement. I mock the user input for two iterations and break during the thirs iteration.
here is my run code.
def main():
pirateList = []
maxLengthList = 6
while len(pirateList) < maxLengthList:
item = input("Argh! Enter the item: ")
if item == "exit":
break;
else:
pirateList.append(item)
print(pirateList)
print(pirateList)
main()
here is my test code, i should be expecting [bow, arrow]
import unittest
from unittest.mock import patch
import io
import sys
from RunFile import main
class GetInputTest(unittest.TestCase):
#patch('builtins.input', side_effect=["bow", "arrow","exit"])
def test_output(self,m):
saved_stdout = sys.stdout
try:
out = io.StringIO()
sys.stdout = out
main()
output = out.getvalue().strip()
assert output.endswith('[bow, arrow]')
finally:
sys.stdout = saved_stdout
if __name__ == "__main__":
unittest.main()
when I run this code the program just gets hung up.No errors or tracks
The import statement you are having
from RunFile import main
Actually runs the main function, as it should, and asks for the input. You should have the standard if-clause there:
if __name__ == "__main__":
main()
You might also want to change the stdout handling, here is an example:
class GetInputTest(unittest.TestCase):
#patch('builtins.input', side_effect=["bow", "arrow","exit"])
#patch('sys.stdout', new_callable=StringIO)
def run_test_with_stdout_capture(self , mock_output, mock_input ):
main()
return mock_output.getvalue()
def test( self ):
print ("GOT: + " + self.run_test_with_stdout_capture())
if __name__ == "__main__":
unittest.main()
Do note that you cannot print inside the #patch sys.stdout -- it will get captured!