Python unit test: Check list sorting
2. Unit Test for Sorted List in Ascending Order
Write a Python unit test program to check if a list is sorted in ascending order.
Sample Solution:
Python Code:
Sample Output:
Ran 2 tests in 0.001s FAILED (failures=2) Sorted list: [5, 7, 2, 8, 1, 9] Unsorted list: [1, 2, 3]
Ran 2 tests in 0.003s OK Sorted list: [1, 2, 3, 4, 5, 6, 7] Unsorted list: [5, 7, 2, 8, 1, 9]
Explanation:
In the above exercise, is_sorted_ascending(lst) function takes a list as input and returns True if the list is sorted in ascending order, and False otherwise. The TestSortedAscending class inherits from unittest.TestCase, and defines two test methods: test_sorted_list and test_unsorted_list.
Flowchart:


For more Practice: Solve these Related Problems:
- Write a Python unit test program that uses assertListEqual to verify a function correctly identifies a list sorted in ascending order.
- Write a Python unit test program that checks that an unsorted list is correctly detected as not being sorted in ascending order.
- Write a Python unit test program that tests the sorted order of lists with duplicate and single elements.
- Write a Python unit test program that confirms a sorting function leaves an already sorted list unchanged.
Go to:
Previous: Check prime number.
Next: Check equality of two lists.
Python Code Editor :
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.