Home > Back-end >  explanation of the function assert
explanation of the function assert

Time:02-02

I try to use function assert, but it's doesn't working. Writing "Assertion error". Can you explain why.

def parse(query: str) -> dict:
return {}

if __name__ == '__main__':
assert parse('https://example.com/path/to/page?name=ferret&color=purple') == {'name': 'ferret', 'color': 'purple'}
assert parse('https://example.com/path/to/page?name=ferret&color=purple&') == {'name': 'ferret', 'color': 'purple'}
assert parse('http://example.com/') == {}
assert parse('http://example.com/?') == {}
assert parse('http://example.com/?name=John') == {'name': 'John'}

def parse_cookie(query: str) -> dict:
return {}


if __name__ == '__main__':
assert parse_cookie('name=John;') == {'name': 'John'}
assert parse_cookie('') == {}
assert parse_cookie('name=John;age=28;') == {'name': 'John', 'age': '28'}
assert parse_cookie('name=John=User;age=28;') == {'name': 'John=User', 'age': '28'}

CodePudding user response:

assert does exactly that - it asserts that the expression following it is true. In your case it means that this expression is false (it returned None or a non-truthy value). It is typically used in testing code to, well, assert that test condition is true and fail a test otherwise.
Normally you do not use assert outside of tests though, the only exception would be a case where you test for a condition that absolutely must not happen and the program should be stopped if the control flow ever comes to evaluate that particular assert as true.

CodePudding user response:

Assert is used when debugging code, meaning if the condition is true then nothing will happen and if the condition is false then AssertionError is raised.
But keep in mind that stackoverflow is not a toturial website and you need to ask the question more specificly so we can help you with your code, Hope i helped :)

  • Related