Python Forum
Unwanted execution of unittest
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unwanted execution of unittest
#1
Question 
Hi Guys,

I`m trying to learn unit testing with the unittest libary.


I have created this modules:
  • unit_testing -> the "master"
  • test_demo_math_module
  • test_demo_physics_module
  • demo_math_module
  • demo_physics_module



unit_testing
#Imports
import unittest
import test_demo_math_module
import test_demo_physics_module


#create the master suite
master_suite = unittest.TestSuite()

#add sub suites
master_suite.addTest(test_demo_math_module.suite()) #add a suite object (created by the suite() function)
master_suite.addTest(test_demo_physics_module.suite())

#run the master suite
unittest.TextTestRunner(verbosity=2).run(master_suite)
demo_math_module
def my_cool_add(a: int, b: int):
    c = a + b
    return c


def my_cool_multiply(a: int, b: int):
    c = a * b
    return c
test_demo_math_module
""" demo module for developing unit test feature
started 11/2022

General Documentation:
https://docs.python.org/2/library/unittest.html
https://docs.python.org/3.10/library/unittest.html#unittest.TestProgram
https://docs.python.org/3/library/unittest.html#setupmodule-and-teardownmodule
"""

#Imports
import unittest
import demo_math_module as math



class Test_Math_Stuff(unittest.TestCase): #creating a test case ( basic buliding block / individual unit of testing)

    def setUp(self):
        self.pi = 3.14
        self.information = "I´m setting up stuff first, after this the tests below will run"

    def test_my_cool_add(self): #creating a individual test
        result = math.my_cool_add(1,1)
        self.assertEqual(result,2)

    def test_my_cool_multiply(self):  # creating a individual test
        result = math.my_cool_multiply(4, 4)
        self.assertEqual(result, 16)

    def tearDown(self):
        self.information = "I will destroy the stuff setted up (e.g. widgets, windows)"


class Test_Other_Stuff(unittest.TestCase):
    pass




#for the ease of running tests, as we will see later, it is a good idea to provide in each test module a callable object that returns a pre-built test suite:
def suite():
    suite = unittest.TestLoader().loadTestsFromTestCase(Test_Math_Stuff) #adds all Tests from the regarding instance to the suite
    return suite


if __name__ == "__main__":
    if True:
        unittest.TextTestRunner(verbosity=2).run(suite()) # run the test
Now I let test_demo_math_module run in slightly different variants, only changing the last 3 lines:
if __name__ == "__main__":
    if [b]True[/b]:
        unittest.TextTestRunner(verbosity=2).run(suite()) # run the test
Output:
C:\Users\spg9ba\.conda\envs\pydrogen\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2022.1.2\plugins\python-ce\helpers\pycharm\_jb_unittest_runner.py" --path U:/031_Python/040_Git_Repository/rbpydrogen/rbpydrogen/UnitTesting/test_demo_math_module.py Testing started at 10:56 ... Launching unittests with arguments python -m unittest U:/031_Python/040_Git_Repository/rbpydrogen/rbpydrogen/UnitTesting/test_demo_math_module.py in U:\031_Python\040_Git_Repository\rbpydrogen\rbpydrogen\UnitTesting Ran 2 tests in 0.010s OK Process finished with exit code 0
if __name__ == "__main__":
    if [b]False[/b]:
        unittest.TextTestRunner(verbosity=2).run(suite()) # run the test
Output:
C:\Users\spg9ba\.conda\envs\pydrogen\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2022.1.2\plugins\python-ce\helpers\pycharm\_jb_unittest_runner.py" --path U:/031_Python/040_Git_Repository/rbpydrogen/rbpydrogen/UnitTesting/test_demo_math_module.py Testing started at 10:58 ... Launching unittests with arguments python -m unittest U:/031_Python/040_Git_Repository/rbpydrogen/rbpydrogen/UnitTesting/test_demo_math_module.py in U:\031_Python\040_Git_Repository\rbpydrogen\rbpydrogen\UnitTesting Ran 2 tests in 0.072s OK Process finished with exit code 0
#if __name__ == "__main__":
    #if True:
unittest.TextTestRunner(verbosity=2).run(suite()) # run the test
Output:
test_my_cool_add (test_demo_math_module.Test_Math_Stuff) ... ok test_my_cool_multiply (test_demo_math_module.Test_Math_Stuff) ... ok ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK Ran 2 tests in 0.004s OK
My Questions:


-To me it seems the unit test is executed, although I do not call it. -> Why?
-To me it seems, that if __name__ == "__main__": is not entered as it should -> Why?
-My aim is, to be capable of let the single test modules run in verbose mode, and also together @ unit testing module. But: Not twice (e.g. unwanted run while import). What would be a correct way?
-does the architecture of the whole stuff make sense to you? Are there more elegant ways?



Thank you a lot for helping! Blush
Reply
#2
think about these statements in your code:
if __name__ == "__main__":
    if True:
        unittest.TextTestRunner(verbosity=2).run(suite()) # run the test
the statement if True, can also be written as if True == True
which, of course is always True

Should be written without that clause:
if __name__ == "__main__":
    unittest.TextTestRunner(verbosity=2).run(suite()) # run the test
Reply
#3
(Nov-08-2022, 11:45 AM)Larz60+ Wrote: think about these statements in your code:
if __name__ == "__main__":
    if True:
        unittest.TextTestRunner(verbosity=2).run(suite()) # run the test
the statement if True, can also be written as if True == True
which, of course is always True

Should be written without that clause:
absolutely, I´d just like to swap between True/False rather than commenting out sometimes. Bad Taste, I know  **angel** 
if __name__ == "__main__":
    unittest.TextTestRunner(verbosity=2).run(suite()) # run the test
Reply
#4
(Nov-08-2022, 11:57 AM)ThomasFab Wrote:
(Nov-08-2022, 11:45 AM)Larz60+ Wrote: think about these statements in your code:
if __name__ == "__main__":
    if True:
        unittest.TextTestRunner(verbosity=2).run(suite()) # run the test
the statement if True, can also be written as if True == True
which, of course is always True

Should be written without that clause:
if __name__ == "__main__":
    unittest.TextTestRunner(verbosity=2).run(suite()) # run the test

absolutely, I´d just like to swap between True/False rather than commenting out sometimes. Bad Taste, I know Angel
Reply
#5
Are you running the test using the test runner in pycharm? That does not run the test file as a python program. It imports the file and runs the test classes. Changing "if True:" to "if False:" had no effect because __name__ != "__main__". You never reached the if statement.

This is the module I want to test.
def x(y):
    return y

def y(x):
    return x
And this is my test program.
import unittest
import thing

class test_x(unittest.TestCase):
    def test_x(self):
        self.assertEqual(thing.x(5), 5)

class test_y(unittest.TestCase):
    def test_y(self):
        self.assertEqual(thing.y(5), 5)

class test_xy(unittest.TestCase):
    def test_xy(self):
        self.assertEqual(thing.x(5), thing.y(7))
In my vscode test runner I can run all the tests and it reports "2/3 tests passed (66.7%). The test runner automatically jumps to the first test that failed and opens up a message in the editor describing how the test failed. If multiple tests fail I can click on each fail and see the reason why.

I like the vscode test runner so much that I don't bother to write a test runner in the file. You probably noticed that already. If I did want to run my test program like a Python file, I would append this on the end.
if __name__ == "__main__":
    unittest.main()
Reply
#6
Quote:Are you running the test using the test runner in pycharm? That does not run the test file as a python program. It imports the file and runs the test classes. Changing "if True:" to "if False:" had no effect because __name__ != "__main__". You never reached the if statement.
aahh, good to know, thanks!


Your Suggestion
if __name__ == "__main__":
    unittest.main()
...seems not to work - still not entering the statement.

Also, if I write only
unittest.main(module=suite(), verbosity=2)

or
#unittest.main(verbosity=2)
at the end of the code, i get an error:
Error:
Testing started at 11:21 ... Launching unittests with arguments python -m unittest U:/031_Python/040_Git_Repository/rbpydrogen/rbpydrogen/UnitTesting/test_demo_math_module.py in U:\031_Python\040_Git_Repository\rbpydrogen\rbpydrogen\UnitTesting ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK Process finished with exit code 0 Empty suite
Is there any way to tell PyCharm to just run the module as a normal script?
Couldnt find anything @Run Config related to that...
Reply
#7
Quote:Your Suggestion...seems not to work - still not entering the statement.
It works fine. You aren't using it correctly.

No test runner is going to run code protected by if __name__ == "__main__": Your files are imported by the test runner, not run like scripts. In an imported file the name is not "__main__".

To run your test as a "normal" script, run it like a "normal" script.

python test_demo_math.py

The reporting stinks compared to running in a test runner, so I don't know why you would want this.
Reply
#8
seanhystad Wrote:The reporting stinks compared to running in a test runner, so I don't know why you would want this.

Take a situation (hypothetical or real) where you have many developers working on one large project (this happens quite often in the real world).

These developers may be spread throughout the world.

Many favorite and diverse IDE's will be used to develop the code.

using the
If __name__ == '__main__':
    ...
clause will allow each developer to include unittests for their code whch can be run by anyone else in the group, no matter which IDE they use.

The code will execute the tests within the '__name__' clause, if run standalone from any IDE terminal, however will not be run if the module is imported into another module as a library.

The unit tests travel with the code and anytime in the future may be relied on, to test individual modules for whatever purpose necessary. Updates to code being one pratical application.
Reply
#9
(Nov-10-2022, 09:41 AM)Larz60+ Wrote:
seanhystad Wrote:The reporting stinks compared to running in a test runner, so I don't know why you would want this.

Take a situation (hypothetical or real) where you have many developers working on one large project (this happens quite often in the real world).

These developers may be spread throughout the world.

Many favorite and diverse IDE's will be used to develop the code.

using the
If __name__ == '__main__':
    ...
clause will allow each developer to include unittests for their code whch can be run by anyone else in the group, no matter which IDE they use.

The code will execute the tests within the '__name__' clause, if run standalone from any IDE terminal, however will not be run if the module is imported into another module as a library.

The unit tests travel with the code and anytime in the future may be relied on, to test individual modules for whatever purpose necessary. Updates to code being one pratical application.


exactly. thanks Blush
Reply
#10
(Nov-08-2022, 10:12 AM)ThomasFab Wrote: I`m trying to learn unit testing with the unittest libary.
Would advice to look into and use pytest.
Example if i would test your math module.
from program import math_module
import pytest

def test_my_cool_add():
    result = math_module.my_cool_add(4, 4)
    assert result == 8
  
@pytest.mark.parametrize(    
    'n1, n2, expected', [
        (4, 4, 16),
        (45, 50, 2251),
        (1278, 9999, 12778722),
    ]
)
def test_my_cool_multiply(n1, n2, expected):  
    result = math_module.my_cool_multiply(n1, n2)
    assert result == expected 
I alwys run this from command line and pytest will use nice colors🎨
[Image: R2EfjC.png]

Make and error.
[Image: 9XSOPj.png]
Larz60+ likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  problem in using unittest akbarza 2 329 Feb-25-2024, 12:51 PM
Last Post: deanhystad
  unittest.mock for an api key silver 3 1,397 Aug-29-2022, 03:52 PM
Last Post: ndc85430
  Removing the unwanted data from a file jehoshua 14 4,100 Feb-01-2022, 09:56 PM
Last Post: jehoshua
  Ran 0 tests in 0.000s - unittest Peaches 8 5,124 Dec-31-2021, 08:58 AM
Last Post: Peaches
  HELP on Unwanted CSV Export Output | Using Selenium to Scrape soothsayerpg 0 1,275 Jun-13-2021, 12:23 PM
Last Post: soothsayerpg
Sad Problem with Unittest mhanusek 1 3,769 Nov-12-2020, 04:58 PM
Last Post: Gribouillis
  Unittest et patch mad31 2 2,139 Aug-09-2020, 06:16 AM
Last Post: mad31
  Unusual things to do with unittest/HTMLTestRunner AndyHolyer 0 2,148 Jul-29-2020, 02:43 PM
Last Post: AndyHolyer
  Test a class function via "unittest " Penguin827 1 1,625 Jul-10-2020, 08:31 AM
Last Post: Gribouillis
  How to eliminate unwanted spaces Mohan 5 2,895 Jun-04-2020, 08:34 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020