Can I perform multiple assertions in pytest?

后端 未结 5 1883
轻奢々
轻奢々 2020-12-25 15:24

I\'m using pytest for my selenium tests and wanted to know if it\'s possible to have multiple assertions in a single test?

I call a function that compares multiple v

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-25 15:50

    As Jon Clements commented, you can fill a list of error messages and then assert the list is empty, displaying each message when the assertion is false.

    concretely, it could be something like that:

    def test_something(self):
        errors = []
    
        # replace assertions by conditions
        if not condition_1:
            errors.append("an error message")
        if not condition_2:
            errors.append("an other error message")
    
        # assert no error message has been registered, else print messages
        assert not errors, "errors occured:\n{}".format("\n".join(errors))
    

    The original assertions are replaced by if statements which append messages to an errors list in case condition are not met. Then you assert the errors list is empty (an empty list is False) and make the assertion message contains each message of the errors list.


    You could also make a test generator as described in the nose documentation. I did not find any pytest doc which describes it, but I know that pytest handled this exactly the same manner as nose.

提交回复
热议问题