0

I'm implementing a unittest to check if certain strings in an application start with a legal prefix. For example as a test function body I now have:

strings_to_check = ['ID_PRIMARY','ID_FOREIGN','OBJ_NAME', 'SOMETHING_ELSE']
for s in strings_to_check:
    assert s.startswith('ID_') or\
           s.startswith('OBJ_')

But the AssertionError that is returned is quite verbose (the real code has more legal prefix option). I found this in the documentation, but that focusses on assertion between (custom) objects. Is there a way to write you own custom assertion function that returns a easier to read message?

1
  • Just writing assert s.startswith(...)... , f"{s} shall start with valid prefix" is not sufficient? What is the output you want to see? Commented Feb 10, 2020 at 16:17

1 Answer 1

2

You could do something like this:

def test_myex1(myfixture):
    myfixture.append(1)
    strings_to_check = ['ID_PRIMARY','ID_FOREIGN','OBJ_NAME', 'SOMETHING_ELSE']
    for s in strings_to_check:
        failing_string = f'variable s: {s} does not start with valid string'
        assert s.startswith('ID_') or s.startswith('OBJ_'), failing_string

Which produces a traceback like:

>           assert s.startswith('ID_') or s.startswith('OBJ_'), failing_string
E           AssertionError: variable s: SOMETHING_ELSE does not start with valid string

raisetest.py:6: AssertionError
Sign up to request clarification or add additional context in comments.

1 Comment

Ah nice, I didn't know you could add a custom text to the assert statement. I also found this question where a custom function is written that raises AssertionError: stackoverflow.com/questions/6655724/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.