diff --git a/src/data_types/test_dictionaries.py b/src/data_types/test_dictionaries.py index da3b9cc8..a7ad2e39 100644 --- a/src/data_types/test_dictionaries.py +++ b/src/data_types/test_dictionaries.py @@ -39,6 +39,7 @@ def test_dictionary(): # To check whether a single key is in the dictionary, use the in keyword. assert 'apple' in fruits_dictionary + assert fruits_dictionary['apple'] == 'green' assert 'pineapple' not in fruits_dictionary # Change the apple color to "red". @@ -66,7 +67,7 @@ def test_dictionary(): # In addition, dict comprehensions can be used to create dictionaries from arbitrary key # and value expressions: - dictionary_via_expression = {x: x**2 for x in (2, 4, 6)} + dictionary_via_expression = {x: x**2 for x in range(10) if x % 2 == 0} assert dictionary_via_expression[2] == 4 assert dictionary_via_expression[4] == 16 assert dictionary_via_expression[6] == 36 diff --git a/src/data_types/test_lists.py b/src/data_types/test_lists.py index 33ffdbe9..29bcd8a2 100644 --- a/src/data_types/test_lists.py +++ b/src/data_types/test_lists.py @@ -29,7 +29,7 @@ def test_list_type(): assert squares[0] == 1 # indexing returns the item assert squares[-1] == 25 assert squares[-3:] == [9, 16, 25] # slicing returns a new list - + assert squares[4:] == [25] # All slice operations return a new list containing the requested elements. # This means that the following slice returns a new (shallow) copy of # the list: @@ -59,7 +59,7 @@ def test_list_type(): assert letters == ['a', 'b', 'f', 'g'] # clear the list by replacing all the elements with an empty list letters[:] = [] - assert letters == [] + assert not letters # The built-in function len() also applies to lists letters = ['a', 'b', 'c', 'd'] @@ -263,8 +263,8 @@ def test_list_comprehensions(): # Call a method on each element. fresh_fruit = [' banana', ' loganberry ', 'passion fruit '] - clean_fresh_fruit = [weapon.strip() for weapon in fresh_fruit] - assert clean_fresh_fruit == ['banana', 'loganberry', 'passion fruit'] + clean_fresh_fruit = [weapon.strip().replace("banana", "apple") for weapon in fresh_fruit] + assert clean_fresh_fruit == ['apple', 'loganberry', 'passion fruit'] # Create a list of 2-tuples like (number, square). square_tuples = [(x, x ** 2) for x in range(6)] @@ -299,6 +299,16 @@ def test_nested_list_comprehensions(): [4, 8, 12], ] + # Square and transpose of a matrix: + + squared_transposed_matrix = [[row[i]*row[i] for row in matrix] for i in range(len(matrix[0]))] + + assert squared_transposed_matrix == [ + [1, 25, 81], + [4, 36, 100], + [9, 49, 121], + [16, 64, 144] + ] # As we saw in the previous section, the nested listcomp is evaluated in the context of the # for that follows it, so this example is equivalent to: transposed = [] @@ -311,7 +321,11 @@ def test_nested_list_comprehensions(): [3, 7, 11], [4, 8, 12], ] - + assert list(zip(*squared_transposed_matrix)) == [ + (1, 4, 9, 16), + (25, 36, 49, 64), + (81, 100, 121, 144), + ] # which, in turn, is the same as: transposed = [] for i in range(4): diff --git a/src/data_types/test_numbers.py b/src/data_types/test_numbers.py index 66bb111c..e8344b4b 100644 --- a/src/data_types/test_numbers.py +++ b/src/data_types/test_numbers.py @@ -45,6 +45,7 @@ def test_booleans(): assert isinstance(true_boolean, bool) assert isinstance(false_boolean, bool) + assert(isinstance(true_boolean,int)) # Let's try to cast boolean to string. assert str(true_boolean) == "True" diff --git a/src/data_types/test_sets.py b/src/data_types/test_sets.py index 1dfb1329..339a12e5 100644 --- a/src/data_types/test_sets.py +++ b/src/data_types/test_sets.py @@ -19,8 +19,8 @@ def test_sets(): # It is also possible to use the set() constructor to make a set. # Note the double round-brackets - fruits_set_via_constructor = set(("apple", "banana", "cherry")) - + fruits_set_via_constructor = set(("apple", "banana", "cherry","strawberry","apple")) + assert fruits_set_via_constructor == {"apple", "banana", "cherry", "strawberry"} assert isinstance(fruits_set_via_constructor, set) @@ -65,6 +65,8 @@ def test_set_methods(): # Letters in first or second word but not both. assert first_char_set ^ second_char_set == {'r', 'd', 'b', 'm', 'z', 'l'} + # Letters in first or second but not in both + assert first_char_set.symmetric_difference(second_char_set) == {'r', 'd', 'b', 'm', 'z', 'l'} # Similarly to list comprehensions, set comprehensions are also supported: word = {char for char in 'abracadabra' if char not in 'abc'} assert word == {'r', 'd'} diff --git a/src/data_types/test_strings.py b/src/data_types/test_strings.py index ae86432f..cead2602 100644 --- a/src/data_types/test_strings.py +++ b/src/data_types/test_strings.py @@ -86,7 +86,7 @@ def test_string_type(): # However, out of range slice indexes are handled gracefully when used # for slicing: - assert word[4:42] == 'on' + assert word[:42] == 'Python' assert word[42:] == '' # Python strings cannot be changed — they are immutable. Therefore, @@ -135,8 +135,9 @@ def test_string_operators(): text = ( 'Put several strings within parentheses ' 'to have them joined together.' + ' Testing to add the third string.' ) - assert text == 'Put several strings within parentheses to have them joined together.' + assert text == 'Put several strings within parentheses to have them joined together. Testing to add the third string.' # If you want to concatenate variables or a variable and a literal, use +: prefix = 'Py' @@ -162,7 +163,7 @@ def test_string_methods(): assert hello_world_string.upper() == 'HELLO, WORLD!' # The replace() method replaces a string with another string. - assert hello_world_string.replace('H', 'J') == 'Jello, World!' + assert hello_world_string.replace('H', 'J').replace("W", "w") == 'Jello, world!' # The split() method splits the string into substrings if it finds instances of the separator. assert hello_world_string.split(',') == ['Hello', ' World!'] @@ -186,7 +187,11 @@ def test_string_methods(): my_tuple = ('John', 'Peter', 'Vicky') assert ', '.join(my_tuple) == 'John, Peter, Vicky' - # Returns True if all characters in the string are upper case. + + arr = ["1", "2", "3", "4", "5"] + assert ','.join(arr) == '1,2,3,4,5' + + # Returns True if all characters in the string are upper case. assert 'ABC'.isupper() assert not 'AbC'.isupper() @@ -221,7 +226,7 @@ def test_string_formatting(): no_votes = 43_132_495 # equivalent of 43132495 percentage = yes_votes / (yes_votes + no_votes) - assert '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage) == ' 42572654 YES votes 49.67%' + assert f'{yes_votes:8} YES votes {percentage:3.3%}' == '42572654 YES votes 49.673%' # When you don’t need fancy output but just want a quick display of some variables for debugging # purposes, you can convert any value to a string with the repr() or str() functions. The str() diff --git a/src/data_types/test_tuples.py b/src/data_types/test_tuples.py index b122824e..30a57d31 100644 --- a/src/data_types/test_tuples.py +++ b/src/data_types/test_tuples.py @@ -71,7 +71,7 @@ def test_tuples(): assert first_tuple_number == 12345 assert second_tuple_number == 54321 assert third_tuple_string == 'hello!' - + assert (first_tuple_number, second_tuple_number, third_tuple_string) == (12345, 54321, 'hello!') # This is called, appropriately enough, sequence unpacking and works for any sequence on the # right-hand side. Sequence unpacking requires that there are as many variables on the left # side of the equals sign as there are elements in the sequence. Note that multiple assignment diff --git a/src/data_types/test_type_casting.py b/src/data_types/test_type_casting.py index e5b1fef3..cb1ed385 100644 --- a/src/data_types/test_type_casting.py +++ b/src/data_types/test_type_casting.py @@ -25,7 +25,7 @@ def test_type_casting_to_integer(): assert int(1) == 1 assert int(2.8) == 2 - assert int('3') == 3 + assert int('399') == 399 def test_type_casting_to_float(): @@ -34,7 +34,7 @@ def test_type_casting_to_float(): assert float(1) == 1.0 assert float(2.8) == 2.8 assert float("3") == 3.0 - assert float("4.2") == 4.2 + assert float("4.20000") == 4.2 def test_type_casting_to_string(): diff --git a/src/exceptions/test_handle_exceptions.py b/src/exceptions/test_handle_exceptions.py index 342561a3..b784962d 100644 --- a/src/exceptions/test_handle_exceptions.py +++ b/src/exceptions/test_handle_exceptions.py @@ -39,7 +39,16 @@ def test_handle_exceptions(): # We should get here because of division by zero. exception_has_been_handled = True - assert exception_has_been_handled + exception_message = "No exception" + try: + result = 10 * (1 / 0) # division by zero + # We should not get here at all. + assert result + except Exception: + # We should get here because of division by zero. + exception_message = "Zero Division Exception" + + assert exception_message == "Zero Division Exception" # Let's simulate undefined variable access exception. exception_has_been_handled = False @@ -95,7 +104,7 @@ def test_handle_exceptions(): try: result = 10 # We should not get here at all. - assert result + assert result == 10 except NameError: # We should get here because of division by zero. exception_has_been_handled = True diff --git a/src/exceptions/test_raise_exceptions.py b/src/exceptions/test_raise_exceptions.py index 3d5ede1c..5b19022e 100644 --- a/src/exceptions/test_raise_exceptions.py +++ b/src/exceptions/test_raise_exceptions.py @@ -35,9 +35,11 @@ def test_user_defined_exception(): # that may occur in functions they define. class MyCustomError(Exception): """Example of MyCustomError exception.""" + type = "Exception" def __init__(self, message): super().__init__(message) self.message = message + custom_exception_is_caught = False @@ -47,3 +49,4 @@ def __init__(self, message): custom_exception_is_caught = True assert custom_exception_is_caught + assert MyCustomError.type == "Exception" diff --git a/src/standard_libraries/glob_files/new_file.c b/src/standard_libraries/glob_files/new_file.c new file mode 100644 index 00000000..e69de29b diff --git a/src/standard_libraries/test_datetime.py b/src/standard_libraries/test_datetime.py index 93d18aab..6dc93861 100644 --- a/src/standard_libraries/test_datetime.py +++ b/src/standard_libraries/test_datetime.py @@ -17,16 +17,22 @@ def test_datetime(): real_now = date.today() assert real_now - fake_now = date(2018, 8, 29) + fake_now = date(2022, 8, 5) - assert fake_now.day == 29 + assert fake_now.day == 5 assert fake_now.month == 8 - assert fake_now.year == 2018 - assert fake_now.ctime() == 'Wed Aug 29 00:00:00 2018' + assert fake_now.year == 2022 + assert fake_now.ctime() == 'Fri Aug 5 00:00:00 2022' + + fake_now = date(2018, 8, 29) + assert fake_now.strftime( '%m-%d-%y. %d %b %Y is a %A on the %d day of %B.' ) == '08-29-18. 29 Aug 2018 is a Wednesday on the 29 day of August.' + assert real_now.strftime( + '%m-%d-%y, %d %B %y is a %a on the %d day of %b' + ) == '08-05-22, 05 August 22 is a Fri on the 05 day of Aug' # Dates support calendar arithmetic. birthday = date(1964, 7, 31) age = fake_now - birthday diff --git a/src/standard_libraries/test_glob.py b/src/standard_libraries/test_glob.py index c236f73c..9a8a8297 100644 --- a/src/standard_libraries/test_glob.py +++ b/src/standard_libraries/test_glob.py @@ -19,3 +19,15 @@ def test_glob(): 'src/standard_libraries/glob_files/first_file.txt', 'src/standard_libraries/glob_files/second_file.txt' ]) + + assert sorted(glob.glob('src/standard_libraries/**/*.txt')) == sorted([ + 'src/standard_libraries/glob_files/first_file.txt', + 'src/standard_libraries/glob_files/second_file.txt' + ]) + + assert sorted(glob.glob('src/standard_libraries/glob_files/*')) == sorted([ + 'src/standard_libraries/glob_files/first_file.txt', + 'src/standard_libraries/glob_files/second_file.txt', + 'src/standard_libraries/glob_files/new_file.c' + ]) + \ No newline at end of file diff --git a/src/standard_libraries/test_json.py b/src/standard_libraries/test_json.py index 8ffdf302..ef134e24 100644 --- a/src/standard_libraries/test_json.py +++ b/src/standard_libraries/test_json.py @@ -7,6 +7,8 @@ import json +from pyparsing import null_debug_action + def test_json(): """JSON serialization.""" @@ -36,3 +38,7 @@ def test_json(): encoded_person_string = json.dumps(person_dictionary) assert encoded_person_string == json_string + assert json.dumps(None) == 'null' + assert json.dumps(3) == '3' + assert json.dumps(True) == 'true' + \ No newline at end of file diff --git a/src/standard_libraries/test_math.py b/src/standard_libraries/test_math.py index 3aa33648..8f2d2106 100644 --- a/src/standard_libraries/test_math.py +++ b/src/standard_libraries/test_math.py @@ -17,6 +17,8 @@ def test_math(): """ assert math.cos(math.pi / 4) == 0.70710678118654757 assert math.log(1024, 2) == 10.0 + assert math.pow(2,2) == 4 + assert math.sqrt(4) == 2 def test_random(): @@ -43,6 +45,9 @@ def test_random(): random_integer = random.randrange(6) # i.e. 4 assert 0 <= random_integer <= 6 + random_integer = random.randint(4,5) # i.e. 4 + assert 0 <= random_integer <= 5 + def test_statistics(): """Statistics. diff --git a/src/standard_libraries/test_re.py b/src/standard_libraries/test_re.py index ebee9bed..5877acca 100644 --- a/src/standard_libraries/test_re.py +++ b/src/standard_libraries/test_re.py @@ -12,14 +12,13 @@ def test_re(): """String Pattern Matching""" - assert re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') == [ - 'foot', - 'fell', - 'fastest' - ] - - assert re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') == 'cat in the hat' - + assert sorted(re.findall(r'\bw[a-z]*', 'which foot or hand wash fastest while')) == sorted([ + 'which', + 'wash', + 'while' + ]) + + assert re.sub(r'(\b[a-z]+) \1', r'\1', 'cat cat in in the the hat') == 'cat in the hat' # When only simple capabilities are needed, string methods are preferred because they are # easier to read and debug: assert 'tea for too'.replace('too', 'two') == 'tea for two' diff --git a/src/standard_libraries/test_zlib.py b/src/standard_libraries/test_zlib.py index 55335b58..8037a502 100644 --- a/src/standard_libraries/test_zlib.py +++ b/src/standard_libraries/test_zlib.py @@ -11,13 +11,13 @@ def test_zlib(): """zlib.""" - string = b'witch which has which witches wrist watch' - assert len(string) == 41 + string = b'witch which has witches wrist watch' + assert len(string) == 35 zlib_compressed_string = zlib.compress(string) - assert len(zlib_compressed_string) == 37 + assert len(zlib_compressed_string) == 36 zlib_decompressed_string = zlib.decompress(zlib_compressed_string) - assert zlib_decompressed_string == b'witch which has which witches wrist watch' + assert zlib_decompressed_string == b'witch which has witches wrist watch' - assert zlib.crc32(string) == 226805979 + assert zlib.crc32(string) == 505419916