Pytest Assert vs Python Assert

Viewed 682

I am using pytest asserts to validate data and data conditions. I wanted to know if this is the same as Python assert and is it a good practice to use pytest assert to validate any test condition.

I could not find anywhere - NOT - to use pytest assert.

Thank you for your help

1 Answers

From the pytest docs the assert is just the standard python assert. Other packages may have their own assert methods with custom functionality though.

Note that if you are using python's assert you may need to check the implementation of the __eq__ method for some objects as the default for some objects is to just check if they point to the same address in memory.

For example, say you have a class TestClass where num is a string and id is an int

class TestClass:
    def __init__(self, name, id):
        self._name = name
        self._id = id

Now if you instantiate two instances of TestClass like so:

test1 = TestClass("test", 1)
test2 = TestClass("test", 1)

Then assert test1 = test2 will give False by default as they are two separate objects.

However, you can override the __eq__ method in a class like this:

    class TestClass2:
        def __init__(self, name, id):
            self._name = name
            self._id = id

        def __eq__(self, other_test_class):
            return (self._name = other_test_class._name) and (self._id = other_test_class._id)

Now if you define:

test1 = TestClass2("test", 1)
test2 = TestClass2("test", 1)

Then assert test1 == test2 gives True.

Some other packages may have their own assert function and set of objects where this functionality is explicitly handled by the assert.

As for which to use that is mostly a matter of preference or who else you are working with. Best practice is to use the same methods your coworkers use. Outside of that, I would prefer base python functions because most should know how to use them, which may not be true for other packages.

Related