简体   繁体   English

Pytest 断言与 Python 断言

[英]Pytest Assert vs Python Assert

I am using pytest asserts to validate data and data conditions.我正在使用pytest 断言来验证数据和数据条件。 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.我想知道这是否与Python 断言相同,使用 pytest 断言来验证任何测试条件是否是一种好习惯。

I could not find anywhere - NOT - to use pytest assert.我找不到任何地方——不是——使用 pytest 断言。

Thank you for your help谢谢您的帮助

From the pytest docs the assert is just the standard python assert.pytest 文档中,断言只是标准的 python 断言。 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.请注意,如果您使用 python 的断言,您可能需要检查某些对象的__eq__方法的实现,因为某些对象的默认设置是仅检查它们是否指向 memory 中的相同地址。

For example, say you have a class TestClass where num is a string and id is an int例如,假设您有一个 class TestClass ,其中num是字符串, id是 int

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

Now if you instantiate two instances of TestClass like so:现在,如果您像这样实例化两个 TestClass 实例:

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

Then assert test1 = test2 will give False by default as they are two separate objects.然后assert test1 = test2默认会给出 False 因为它们是两个独立的对象。

However, you can override the __eq__ method in a class like this:但是,您可以像这样覆盖 class 中的__eq__方法:

    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.然后assert test1 == test2给出 True。

Some other packages may have their own assert function and set of objects where this functionality is explicitly handled by the assert.其他一些包可能有自己的断言 function 和一组对象,其中此功能由断言显式处理。

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.除此之外,我更喜欢基本的 python 函数,因为大多数人应该知道如何使用它们,这对于其他软件包可能不正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM