Python's unittest logic
Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test.
>>> class MyTest(unittest.TestCase):
def setUp(self):
self.i = 1
def testA(self):
self.i = 3
self.assertEqual(self.i, 3)
def testB(self):
self.assertEqual(self.i, 3)
>>> unittest.main()
.F
======================================================================
FAIL: testB (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<pyshell#61>", line 8, in testB
AssertionError: 1 != 3
----------------------------------------------------------------------
Ran 2 tests in 0.016s
Asked by: Miller852 | Posted: 28-01-2022
Answer 1
From http://docs.python.org/lib/minimal-example.html :
When a setUp() method is defined, the test runner will run that method prior to each test.
So setUp() gets run before both testA and testB, setting i to 1 each time. Behind the scenes, the entire test object is actually being re-instantiated for each test, with setUp() being run on each new instantiation before the test is executed.
Answered by: Edgar834 | Posted: 01-03-2022Answer 2
Each test is run using a new instance of the MyTest class. That means if you change self in one test, changes will not carry over to other tests, since self will refer to a different instance.
Additionally, as others have pointed out, setUp is called before each test.
Answered by: Abigail929 | Posted: 01-03-2022Answer 3
If I recall correctly in that test framework the setUp method is run before each test
Answered by: Chester836 | Posted: 01-03-2022Answer 4
From a methodological point of view, individual tests should be independent, otherwise it can produce more hard-to-find bugs. Imagine for instance that testA and testB would be called in a different order.
Answered by: Lucas173 | Posted: 01-03-2022Answer 5
The setUp method, as everyone else has said, runs before every test method you write. So, when testB runs, the value of i is 1, not 3.
You can also use a tearDown method which runs after every test method. However if one of your tests crashes, your tearDown method will never run.
Answered by: Dexter610 | Posted: 01-03-2022Similar questions
unit testing - use/run python's 2to3 as or like a unittest
I have used the 2to3 utility to convert code from the command line. What I would like to do is run it basically as a unittest. Even if it tests the file rather than parts(functions, methods...) as would be normal for a unittest.
It does not need to be a unittest and I don't what to automatically convert the files I just want to monitor the py3 compliance of files in a unittest like manor. I can't seem to find any d...
unit testing - How does Python's unittest module detect test cases?
I was wondering when we run unittest.main(), how does Python know what subclasses unittest.Testcase has?
For example, if I add a class FromRomanBadInput(unittest.TestCase), how does unittest know to run this?
unit testing - Using Python's UnitTest Mock for a new Object
I'm trying to learn how to use Mocks for Python. However I've been struggling with some basic application of it.
Let's say our piece of code that I want to test is this:
class ProductionClass:
def method(self):
newone=ProductionClass()
newone.something(1, 2, 3)
def something(self, a, b, c):
pass
def __init__(self):
print("Test")
Which hav...
unit testing - Having an issue with Python's unittest
I am learning Python and trying to test a Polynomial class I wrote using unittest. It seems like I am getting different results from directly running a test in Python and running a test using unittest and I don't understand what's going on.
import unittest
from w4_polynomial import Polynomial
class TestPolynomialClass(unittest.TestCase):
def setUp(self):
self.A = Polynomial()
self.A[1]...
unit testing - How can I only show the custom error message for Python's unittest module
Using Python's unittest module, the assertion
self.assertTrue(a > b - 0.5 && a < b + 0.5, "The two values did not agree")
outputs the following on failure:
AssertionError: False is not true : The two values did not agree
I don't want the False is not true to be printed. Ideally, AssertionError shouldn't ...
unit testing - Python's unittest and dynamic creation of test cases
This question already has answers here:
unit testing - use/run python's 2to3 as or like a unittest
I have used the 2to3 utility to convert code from the command line. What I would like to do is run it basically as a unittest. Even if it tests the file rather than parts(functions, methods...) as would be normal for a unittest.
It does not need to be a unittest and I don't what to automatically convert the files I just want to monitor the py3 compliance of files in a unittest like manor. I can't seem to find any d...
unit testing - Can Python's unittest test in parallel, like nose can?
Python's NOSE testing framework has the concept of running multiple tests in parallel.
The purpose of this is not to test concurrency in the code, but to make tests for code that has "no side-effects, no ordering issues, and no external dependencies" run faster. The performance gain comes from concurrent I/O waits when t...
unit testing - How does Python's unittest module detect test cases?
I was wondering when we run unittest.main(), how does Python know what subclasses unittest.Testcase has?
For example, if I add a class FromRomanBadInput(unittest.TestCase), how does unittest know to run this?
unit testing - Using Python's UnitTest Mock for a new Object
I'm trying to learn how to use Mocks for Python. However I've been struggling with some basic application of it.
Let's say our piece of code that I want to test is this:
class ProductionClass:
def method(self):
newone=ProductionClass()
newone.something(1, 2, 3)
def something(self, a, b, c):
pass
def __init__(self):
print("Test")
Which hav...
Python's unittest, classes and methods
There's a question I've been stuck on for days now:
Create a class called BankAccount
Create a constructor that takes in an integer and assigns this to a `balance` property.
Create a method called `deposit` that takes in cash deposit amount and updates the balance accordingly.
Create a method called `withdraw` that takes in cash withdrawal amount and updates the balance accordingly. if amount is greater tha...
unit testing - Having an issue with Python's unittest
I am learning Python and trying to test a Polynomial class I wrote using unittest. It seems like I am getting different results from directly running a test in Python and running a test using unittest and I don't understand what's going on.
import unittest
from w4_polynomial import Polynomial
class TestPolynomialClass(unittest.TestCase):
def setUp(self):
self.A = Polynomial()
self.A[1]...
unit testing - How can I only show the custom error message for Python's unittest module
Using Python's unittest module, the assertion
self.assertTrue(a > b - 0.5 && a < b + 0.5, "The two values did not agree")
outputs the following on failure:
AssertionError: False is not true : The two values did not agree
I don't want the False is not true to be printed. Ideally, AssertionError shouldn't ...
Python's unittest setUp function internal working
import unittest
class TestString(unittest.TestCase):
def setUp(self):
self.subject_list = ["Maths","Physics","Chemistry"]
def test_student_1(self):
self.assertListEqual(self.subject_list,["Maths","Physics","Chemistry"])
self.subject_list.remove("Maths")
def test_student_2(self):
self.assertListEqual(self.subject_list,["Physics","Chemistry"])
if __name__ == "__main__"...
Enforce testing order in python's unittest test suite
I have written code that finds all of the tests that can be run in a package and gathers them into a single test suite. The only thing is that some of the tests are dependent on other tests already being run.
That might seem like bad test architecture but what I'm testing is the startup and shutdown of an application. So I have tests that makes sure everything comes to life appropriately, and then another set of te...
smtp - Using Python's smtplib with Tor
I'm conducting experiments regarding e-mail spam. One of these experiments require sending mail thru Tor. Since I'm using Python and smtplib for my experiments, I'm looking for a way to use the Tor proxy (or other method) to perform that mail sending.
Ideas how this can be done?
How can I draw a bezier curve using Python's PIL?
I'm using Python's Imaging Library and I would like to draw some bezier curves.
I guess I could calculate pixel by pixel but I'm hoping there is something simpler.
Python's version of PHP's time() function
I've looked at the Python Time module and can't find anything that gives the integer of how many seconds since 1970 as PHP does with time().
Am I simply missing something here or is there a common way to do this that's simply not listed there?
C++ string diff (a la Python's difflib)
I'm trying to diff two strings to determine whether or not they solely vary in one numerical subset of the string structure; for example,
varies_in_single_number_field('foo7bar', 'foo123bar')
# Returns True, because 7 != 123, and there's only one varying
# number region between the two strings.
In Python I can use the difflib to accomplish this:
import difflib,...
scope - Getting "global name 'foo' is not defined" with Python's timeit
I'm trying to find out how much time it takes to execute a Python statement, so I looked online and found that the standard library provides a module called timeit that purports to do exactly that:
import timeit
def foo():
# ... contains code I want to time ...
def dotime():
t = timeit.Timer("foo()")
time = t.timeit(1)
...
regex - Python's re module - saving state?
One of the biggest annoyances I find in Python is the inability of the re module to save its state without explicitly doing it in a match object. Often, one needs to parse lines and if they comply a certain regex take out values from them by the same regex. I would like to write code like this:
if re.match('foo (\w+) bar (\d+)', line):
# do stuff with .group(1) and .group(2)
elif re.match('ba...
hash - How to set the crypto key for Python's MD5 module?
What is the Python equivalent of following Perl code?
hmac_md5_hex($login . "^" . $seq . "^" . $time . "^" . $amo . "^", $CryptoKey);
The Python hashlib.md5 doesn't seem to take an "cryptographic key" argument. It only accepts 1 argument.
pretty print - How do I get python's pprint to return a string instead of printing?
In other words, what's the sprintf equivalent to pprint?
Issue with PyAMF, Django, and Python's "property" feature
So far, I've had great success using PyAMF to communicate between my Flex front-end and my Django back-end. However, I believe I've encountered a bug. The following example (emphasis on the word "example") demonstrates the (potential) bug:
My Flex app contains the following VO:
package myproject.model.vo
{
[Bindable]
[RemoteClass(alias="myproject.models.Book")]
public class BookVO
...
class - What is the purpose of python's inner classes?
Python's inner/nested classes confuse me. Is there something that can't be accomplished without them? If so, what is that thing?
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python