John
John

Reputation: 857

Python and pytest - check if a test passes or fails and execute code

I'm doing test automation with python and we have a test management tool. What we try to do is update the test cases in this management tool so that if a test fails the guys here can see it very quickly.

But the thing is that I can't figure out when I test has passed or failed. So my tests looks like this:

@decorator(testId = 5, comment = "Test fails or not")
    def test(self):
        # assert
        assert True == False

No i'm trying to solve it with a decorator but it didn't work out. So this test will fail and now I need to push that to a test management system online. Anybody a clue on how to do this? My decorator code looks like this:

def decorator(*args, **kwargs):
    print("Inside decorator")
    def inner(func):
        print("testId: ", kwargs["testId"])
        if "comment" in kwargs.keys():
            print("comment: ", kwargs["comment"])
        try:
            pass
        except AssertionError as assertionError:
            print("Assertion fails: " + str(assertionError))
            raise
        except Exception as ex:
            print("Something else failed")
            print("exception: " + str(ex))
            raise
        finally:
            print("ending")
        return func
    return inner

Upvotes: 1

Views: 1503

Answers (1)

John
John

Reputation: 857

After searching for a while, I made a better decorator. It looks like this:

import functools

def exception(function):
  @functools.wraps(function)
  def wrapper(*args, **kwargs):
    try:
      return function(*args, **kwargs)
    except:
      print("error in: " + function.__name__)
      raise
  return wrapper

@exception
def zero_divide():
    1 / 1
    a = AnObjectTHatDOESNTEXIST()

print("start")
zero_divide()
print("end")

Upvotes: 1

Related Questions