Is there a way to use Python unit test assertions outside of a TestCase?
Asked Answered
O

2

67

I need to create a fake helper class to be used in unit tests (injected into tested classes). Is there some way to use TestCase assertions in such class?

I would like to use the assertions for some common checks performed by the Fake class. Something like:

class FakeFoo(object):

  def do_foo(self, a, b):
    assertNotNull(a)
    ...
Orb answered 6/8, 2013 at 15:32 Comment(3)
Reference: https://mcmap.net/q/15596/-what-is-the-use-of-quot-assert-quot-in-pythonCowlick
Built-in assert would work if there is no other way, but TestCase assertions are more verbose and have few advantages over the built-in: https://mcmap.net/q/102468/-what-are-the-advantages-or-difference-in-assert-false-and-self-assertfalse/1031601Orb
You are right; I wanted to give a reference that would put some of that in perspective. I wasn't proposing such as a solution. Thanks for the second link. :)Cowlick
B
77

You can create a instance of unittest.TestCase() and call the methods on that.

import unittest

tc = unittest.TestCase()
tc.assertIsNotNone(a)

On older Python versions (Python 2.7 and earlier, 3.0, 3.1) you need to you pass in the name of an existing method on the class TestCase class (normally it's passed the name of a test method on a subclass). __init__ will do in this case:

tc = unittest.TestCase('__init__')
tc.assertIsNotNone(a)

However, you are probably looking for a good Mock library instead. mock would be a good choice.

Another option is to use pytest, which augments assert statements to provide the same or more context as unittest.TestCase() assertion methods; you'd simply write assert a is not None.

Bissell answered 6/8, 2013 at 15:33 Comment(1)
Since Python 3.2 you don't need to pass anything in the constructor. Documentation: "Changed in version 3.2: TestCase can be instantiated successfully without providing a methodName. This makes it easier to experiment with TestCase from the interactive interpreter."Receptor
J
0

You can use Pytest or Nosetest. Though I'don't know if they have 'assertNotNull' function. I know they can use 'assert' simply for assertion. Or you can use something like assertpy or ptest, if you like, you can search for them on github.

Jerryjerrybuild answered 28/8, 2019 at 7:47 Comment(1)
Welcome to SO! Please edit your question, and add e.g. some links and a bit of more explanations.Phenomena

© 2022 - 2024 — McMap. All rights reserved.