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?

Peter Smit
  • 1,594
  • 1
  • 13
  • 27
  • Just writing `assert s.startswith(...)... , f"{s} shall start with valid prefix"` is not sufficient? What is the output you want to see? – MrBean Bremen Feb 10 '20 at 16:17

1 Answers1

1

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
Jack Thomson
  • 450
  • 4
  • 9
  • 1
    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: https://stackoverflow.com/questions/6655724/how-to-write-a-custom-assertfoo-method-in-python – Peter Smit Feb 11 '20 at 08:52