How do I capture the result of assertion in a variable?

Question:

In pytest, I would like to capture, for example, the result of something like assert a==b in a variable.
Any idea how do I do that?

var = assert fruit1 == fruit2

does not capture the assert value in var.

Thanks in advance!

Tried

var = assert fruit1 == fruit2

Expecting the value of assert (true or false) to be captured so that I can post the result to database.

Asked By: Rag

||

Answers:

Assert doesn’t really have a value. To capture the value you need two lines:

var = fruit1 == fruit2

assert var

Since you’re trying to log to a database, the fact that assert doesn’t evaluate to anything won’t make your code less concise, as you can just bake it into your logging function:

def add_to_database(expression, con = "default_file.txt"):
    # not sure what database you're appending to so I'm going to write to text file.
    with open(con, 'a') as db:
        db.write(str(expression))
    return expression

assert add_to_database(fruit_1 == fruit_2)

This approach may give you the concision you’re looking for while retaining the ability to add a second argument to inform the assert error text. The other approach would be to put assert within the function, which would be more concise if you want the same error text every time.

If you’re trying to capture error text rather than the output of the expression you might try this:

def log_assert(expression, error_text = ""):
    try:
        assert expression, error_text
    except AssertionError as error:
        print(f"AssertionError: {error_text}") # replace print with whatever function writes to your database of errors
        raise error

fruit_1 = 'apple'
fruit_2 = 'Apple.'

log_assert(fruit_1 == fruit_2, "Not equal")

returns

AssertionError: Not equal <– from the print function, this is what would be logged

————————————————————————— AssertionError Traceback (most recent call
last) Cell In [41], line 11
8 fruit_1 == ‘apple’
9 fruit_2 == ‘Apple.’
—> 11 log_assert(fruit_1 == fruit_2, "Not equal")

Cell In [41], line 6, in log_assert(expression, error_text)
4 except AssertionError as error:
5 print(f"AssertionError: {error_text}") # replace print with whatever function writes to your database of errors
—-> 6 raise error

Cell In [41], line 3, in log_assert(expression, error_text)
1 def log_assert(expression, error_text = ""):
2 try:
—-> 3 assert expression, error_text
4 except AssertionError as error:
5 print(f"AssertionError: {error_text}") # replace print with whatever function writes to your database of errors

AssertionError: Not equal

Assert only raises the error text you feed into it and will return nothing in a try/except block if you don’t give it a second argument.

You can get more informative error messages by wrapping this function into a more specialized one

def log_assert_equal(var1, var2):
    log_assert(var1 == var2, f"{var1} is not equal to {var2}")

log_assert_equal(fruit_1, fruit_2)     

returns:
AssertionError: apple is not equal to Apple.

————————————————————————— AssertionError Traceback (most recent call
last) Cell In [47], line 1
—-> 1 log_assert_equal(fruit_1, fruit_2)

Cell In [42], line 2, in log_assert_equal(var1, var2)
1 def log_assert_equal(var1, var2):
—-> 2 log_assert(var1 == var2, f"{var1} is not equal to {var2}")

Cell In [41], line 6, in log_assert(expression, error_text)
4 except AssertionError as error:
5 print(f"AssertionError: {error_text}") # replace print with whatever function writes to your database of errors
—-> 6 raise error

Cell In [41], line 3, in log_assert(expression, error_text)
1 def log_assert(expression, error_text = ""):
2 try:
—-> 3 assert expression, error_text
4 except AssertionError as error:
5 print(f"AssertionError: {error_text}") # replace print with whatever function writes to your database of errors

AssertionError: apple is not equal to Apple.

I hope this wide net answered your question

Answered By: psychicesp

In newer versions of Python, you can use the Walrus operator:

https://realpython.com/python-walrus-operator/

assert (var := (fruit1 == fruit2))
print('var = ', var)
# output: var = True # otherwise, the code would have already crashed :)

The Walrus operator can also be used inside if-statements, nested expressions, arithmetic operations, etc.

Answered By: C-3PO
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.