Python unit test: Input data parsing and validation
10. Unit Test for Parsing and Validating Input Data
Write a Python unit test program to check if a function correctly parses and validates input data.
Sample Solution:
Python Code:
Sample Output:
Ran 2 tests in 0.001s OK
Explanation:
In the above exercise -
The parse_and_validate_input() function takes a data parameter and performs parsing and validation operations on it. The implementation details of this function are not shown, but you can customize it to fit your specific parsing and validation requirements.
The TestInputParsing class is a subclass of unittest.TestCase and contains test cases. We have two test cases: test_valid_input and test_invalid_input.
The parse_and_validate_input function takes a data parameter and performs the following checks:
- It checks if the data is a string using isinstance(data, str).
- It checks if the data is numeric by calling the isnumeric method on the string.
- It checks if the numerical value is greater than 0.
In the test_valid_input case, we provide valid input data "100", which satisfies all validation checks. Therefore, we expect the parse_and_validate_input function to return True, and the assertion self.assertTrue(result) will pass.
In the test_invalid_input case, we provide invalid input data "Hello", which fails the numeric check. Therefore, we expect the function to return False, and the assertion self.assertFalse(result) will pass.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python unit test program to verify that an input parser function correctly handles valid numeric strings and returns the proper numeric type.
- Write a Python unit test program to test a parser function's ability to validate and convert CSV input into a list of dictionaries.
- Write a Python unit test program to check edge cases in input parsing, such as empty strings, improperly formatted data, and null values.
- Write a Python unit test program to use parameterized tests for an input validation function, ensuring it correctly parses a variety of input formats.
Go to:
Previous: Database query result verification.
Next: Python Exception Handling.
Python Code Editor :
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.