diff --git a/python2/contemplate_koans.py b/python2/contemplate_koans.py index 34e06d7bb..d49c6c214 100644 --- a/python2/contemplate_koans.py +++ b/python2/contemplate_koans.py @@ -10,26 +10,27 @@ # So thank guys! # +import unittest import sys if __name__ == '__main__': if sys.version_info >= (3, 0): print("\nThis is the Python 2 version of Python Koans, but you are " + - "running it with Python 3 or newer!\n\n" - "Did you accidentally use the wrong python script? \nTry:\n\n" + - " python contemplate_koans.py\n") + "running it with Python 3 or newer!\n\n" + "Did you accidentally use the wrong python script? \nTry:\n\n" + + " python contemplate_koans.py\n") else: if sys.version_info < (2, 7): print("\n" + - "********************************************************\n" + - "WARNING:\n" + - "This version of Python Koans was designed for " + - "Python 2.7 or greater.\n" + - "Your version of Python is older, so you may run into " + - "problems!\n\n" + - "But lets see how far we get...\n" + - "********************************************************\n") + "********************************************************\n" + + "WARNING:\n" + + "This version of Python Koans was designed for " + + "Python 2.7 or greater.\n" + + "Your version of Python is older, so you may run into " + + "problems!\n\n" + + "But lets see how far we get...\n" + + "********************************************************\n") from runner.mountain import Mountain diff --git a/python2/koans/about_asserts.py b/python2/koans/about_asserts.py index 61b53ada1..8905cb3b2 100644 --- a/python2/koans/about_asserts.py +++ b/python2/koans/about_asserts.py @@ -15,26 +15,26 @@ def test_assert_truth(self): # # http://bit.ly/about_asserts - self.assertTrue(False) # This should be true + self.assertTrue(True) # This should be true def test_assert_with_message(self): """ Enlightenment may be more easily achieved with appropriate messages. """ - self.assertTrue(False, "This should be true -- Please fix this") + self.assertTrue(True, "This should be true -- Please fix this") def test_fill_in_values(self): """ Sometimes we will ask you to fill in the values """ - self.assertEqual(__, 1 + 1) + self.assertEqual(2, 1 + 1) def test_assert_equality(self): """ To understand reality, we must compare our expectations against reality. """ - expected_value = __ + expected_value = 2 actual_value = 1 + 1 self.assertTrue(expected_value == actual_value) @@ -42,7 +42,7 @@ def test_a_better_way_of_asserting_equality(self): """ Some ways of asserting equality are better than others. """ - expected_value = __ + expected_value = 2 actual_value = 1 + 1 self.assertEqual(expected_value, actual_value) @@ -53,7 +53,7 @@ def test_that_unittest_asserts_work_the_same_way_as_python_asserts(self): """ # This throws an AssertionError exception - assert False + assert True def test_that_sometimes_we_need_to_know_the_class_type(self): """ @@ -72,7 +72,7 @@ def test_that_sometimes_we_need_to_know_the_class_type(self): # # See for yourself: - self.assertEqual(__, "naval".__class__) # It's str, not + self.assertEqual(str, "naval".__class__) # It's str, not # Need an illustration? More reading can be found here: # diff --git a/python2/koans/about_classes.py b/python2/koans/about_classes.py index 7b82e60d1..d69ebfe01 100644 --- a/python2/koans/about_classes.py +++ b/python2/koans/about_classes.py @@ -10,10 +10,10 @@ class Dog(object): def test_instances_of_classes_can_be_created_adding_parentheses(self): fido = self.Dog() - self.assertEqual(__, fido.__class__.__name__) + self.assertEqual('Dog', fido.__class__.__name__) def test_classes_have_docstrings(self): - self.assertMatch(__, self.Dog.__doc__) + self.assertMatch('Dogs need regular walkies. Never, ever let them drive', self.Dog.__doc__) # ------------------------------------------------------------------ @@ -26,12 +26,12 @@ def set_name(self, a_name): def test_init_method_is_the_constructor(self): dog = self.Dog2() - self.assertEqual(__, dog._name) + self.assertEqual('Paul', dog._name) def test_private_attributes_are_not_really_private(self): dog = self.Dog2() dog.set_name("Fido") - self.assertEqual(__, dog._name) + self.assertEqual('Fido', dog._name) # The _ prefix in _name implies private ownership, but nothing is truly # private in Python. @@ -39,11 +39,11 @@ def test_you_can_also_access_the_value_out_using_getattr_and_dict(self): fido = self.Dog2() fido.set_name("Fido") - self.assertEqual(__, getattr(fido, "_name")) + self.assertEqual('Fido', getattr(fido, "_name")) # getattr(), setattr() and delattr() are a way of accessing attributes # by method rather than through assignment operators - self.assertEqual(__, fido.__dict__["_name"]) + self.assertEqual('Fido', fido.__dict__["_name"]) # Yes, this works here, but don't rely on the __dict__ object! Some # class implementations use optimization which result in __dict__ not # showing everything. @@ -66,8 +66,8 @@ def test_that_name_can_be_read_as_a_property(self): fido = self.Dog3() fido.set_name("Fido") - self.assertEqual(__, fido.get_name()) # access as method - self.assertEqual(__, fido.name) # access as property + self.assertEqual('Fido', fido.get_name()) # access as method + self.assertEqual('Fido', fido.name) # access as property # ------------------------------------------------------------------ @@ -87,7 +87,7 @@ def test_creating_properties_with_decorators_is_slightly_easier(self): fido = self.Dog4() fido.name = "Fido" - self.assertEqual(__, fido.name) + self.assertEqual('Fido', fido.name) # ------------------------------------------------------------------ @@ -101,19 +101,19 @@ def name(self): def test_init_provides_initial_values_for_instance_variables(self): fido = self.Dog5("Fido") - self.assertEqual(__, fido.name) + self.assertEqual('Fido', fido.name) def test_args_must_match_init(self): - self.assertRaises(___, self.Dog5) # Evaluates self.Dog5() + self.assertRaises(TypeError, self.Dog5) # Evaluates self.Dog5() # THINK ABOUT IT: # Why is this so? - def test_different_objects_have_different_instance_variables(self): + def test_different_objects_have_difference_instance_variables(self): fido = self.Dog5("Fido") rover = self.Dog5("Rover") - self.assertEqual(____, rover.name == fido.name) + self.assertEqual(False, rover.name == fido.name) # ------------------------------------------------------------------ @@ -128,7 +128,7 @@ def __str__(self): # # Implement this! # - return __ + return self._name def __repr__(self): return "" @@ -136,7 +136,7 @@ def __repr__(self): def test_inside_a_method_self_refers_to_the_containing_object(self): fido = self.Dog6("Fido") - self.assertEqual(__, fido.get_self()) # Not a string! + self.assertEqual(fido, fido.get_self()) # Not a string! def test_str_provides_a_string_version_of_the_object(self): fido = self.Dog6("Fido") @@ -144,17 +144,17 @@ def test_str_provides_a_string_version_of_the_object(self): def test_str_is_used_explicitly_in_string_interpolation(self): fido = self.Dog6("Fido") - self.assertEqual(__, "My dog is " + str(fido)) + self.assertEqual('My dog is Fido', "My dog is " + str(fido)) def test_repr_provides_a_more_complete_string_version(self): fido = self.Dog6("Fido") - self.assertEqual(__, repr(fido)) + self.assertEqual('', repr(fido)) def test_all_objects_support_str_and_repr(self): seq = [1, 2, 3] - self.assertEqual(__, str(seq)) - self.assertEqual(__, repr(seq)) + self.assertEqual('[1, 2, 3]', str(seq)) + self.assertEqual('[1, 2, 3]', repr(seq)) - self.assertEqual(__, str("STRING")) - self.assertEqual(__, repr("STRING")) + self.assertEqual('STRING', str("STRING")) + self.assertEqual("'STRING'", repr("STRING")) diff --git a/python2/koans/about_comprehension.py b/python2/koans/about_comprehension.py index 4b372732a..3fb99f854 100644 --- a/python2/koans/about_comprehension.py +++ b/python2/koans/about_comprehension.py @@ -13,8 +13,8 @@ def test_creating_lists_with_list_comprehensions(self): comprehension = [delicacy.capitalize() for delicacy in feast] - self.assertEqual(__, comprehension[0]) - self.assertEqual(__, comprehension[2]) + self.assertEqual('Lambs', comprehension[0]) + self.assertEqual('Orangutans', comprehension[2]) def test_filtering_lists_with_list_comprehensions(self): feast = ['spam', 'sloths', 'orangutans', 'breakfast cereals', @@ -22,15 +22,15 @@ def test_filtering_lists_with_list_comprehensions(self): comprehension = [delicacy for delicacy in feast if len(delicacy) > 6] - self.assertEqual(__, len(feast)) - self.assertEqual(__, len(comprehension)) + self.assertEqual(5, len(feast)) + self.assertEqual(3, len(comprehension)) def test_unpacking_tuples_in_list_comprehensions(self): list_of_tuples = [(1, 'lumberjack'), (2, 'inquisition'), (4, 'spam')] comprehension = [ skit * number for number, skit in list_of_tuples ] - self.assertEqual(__, comprehension[0]) - self.assertEqual(__, len(comprehension[2])) + self.assertEqual('lumberjack', comprehension[0]) + self.assertEqual(16, len(comprehension[2])) def test_double_list_comprehension(self): list_of_eggs = ['poached egg', 'fried egg'] @@ -40,13 +40,13 @@ def test_double_list_comprehension(self): comprehension = [ '{0} and {1}'.format(egg, meat) for egg in list_of_eggs for meat in list_of_meats] - self.assertEqual(__, len(comprehension)) - self.assertEqual(__, comprehension[0]) + self.assertEqual(6, len(comprehension)) + self.assertEqual('poached egg and lite spam', comprehension[0]) def test_creating_a_set_with_set_comprehension(self): comprehension = { x for x in 'aabbbcccc'} - self.assertEqual(__, comprehension) # rememeber that set members are unique + self.assertEqual(set(['a', 'b', 'c']), comprehension) # rememeber that set members are unique def test_creating_a_dictionary_with_dictionary_comprehension(self): dict_of_weapons = {'first': 'fear', 'second': 'surprise', @@ -55,7 +55,7 @@ def test_creating_a_dictionary_with_dictionary_comprehension(self): dict_comprehension = { k.upper(): weapon for k, weapon in dict_of_weapons.iteritems() if weapon} - self.assertEqual(__, 'first' in dict_comprehension) - self.assertEqual(__, 'FIRST' in dict_comprehension) - self.assertEqual(__, len(dict_of_weapons)) - self.assertEqual(__, len(dict_comprehension)) + self.assertEqual(False, 'first' in dict_comprehension) + self.assertEqual(True, 'FIRST' in dict_comprehension) + self.assertEqual(5, len(dict_of_weapons)) + self.assertEqual(4, len(dict_comprehension)) diff --git a/python2/koans/about_control_statements.py b/python2/koans/about_control_statements.py index 921f0bf7f..961d91b05 100644 --- a/python2/koans/about_control_statements.py +++ b/python2/koans/about_control_statements.py @@ -11,13 +11,13 @@ def test_if_then_else_statements(self): result = 'true value' else: result = 'false value' - self.assertEqual(__, result) + self.assertEqual('true value', result) def test_if_then_statements(self): result = 'default value' if True: result = 'true value' - self.assertEqual(__, result) + self.assertEqual('true value', result) def test_while_statement(self): i = 1 @@ -25,7 +25,7 @@ def test_while_statement(self): while i <= 10: result = result * i i += 1 - self.assertEqual(__, result) + self.assertEqual(3628800, result) def test_break_statement(self): i = 1 @@ -34,7 +34,7 @@ def test_break_statement(self): if i > 10: break result = result * i i += 1 - self.assertEqual(__, result) + self.assertEqual(3628800, result) def test_continue_statement(self): i = 0 @@ -43,14 +43,14 @@ def test_continue_statement(self): i += 1 if (i % 2) == 0: continue result.append(i) - self.assertEqual(__, result) + self.assertEqual([1,3,5,7,9], result) def test_for_statement(self): phrase = ["fish", "and", "chips"] result = [] for item in phrase: result.append(item.upper()) - self.assertEqual([__, __, __], result) + self.assertEqual(['FISH', 'AND', 'CHIPS'], result) def test_for_statement_with_tuples(self): round_table = [ @@ -64,7 +64,7 @@ def test_for_statement_with_tuples(self): result.append("Contestant: '" + knight + \ "' Answer: '" + answer + "'") - text = __ + text = "Contestant: 'Robin' Answer: 'Blue! I mean Green!'" self.assertMatch(text, result[2]) diff --git a/python2/koans/about_decorating_with_classes.py b/python2/koans/about_decorating_with_classes.py index b8f67a573..7dd0082e1 100644 --- a/python2/koans/about_decorating_with_classes.py +++ b/python2/koans/about_decorating_with_classes.py @@ -20,21 +20,21 @@ def test_partial_that_wrappers_no_args(self): """ max = functools.partial(self.maximum) - self.assertEqual(__, max(7, 23)) - self.assertEqual(__, max(10, -10)) + self.assertEqual(23, max(7, 23)) + self.assertEqual(10, max(10, -10)) def test_partial_that_wrappers_first_arg(self): max0 = functools.partial(self.maximum, 0) - self.assertEqual(__, max0(-4)) - self.assertEqual(__, max0(5)) + self.assertEqual(0, max0(-4)) + self.assertEqual(5, max0(5)) def test_partial_that_wrappers_all_args(self): always99 = functools.partial(self.maximum, 99, 20) always20 = functools.partial(self.maximum, 9, 20) - self.assertEqual(__, always99()) - self.assertEqual(__, always20()) + self.assertEqual(99, always99()) + self.assertEqual(20, always20()) # ------------------------------------------------------------------ @@ -65,8 +65,8 @@ def test_decorator_with_no_arguments(self): # To clarify: the decorator above the function has no arguments, even # if the decorated function does - self.assertEqual(__, self.foo()) - self.assertEqual(__, self.parrot('pieces of eight')) + self.assertEqual('foo, foo', self.foo()) + self.assertEqual('PIECES OF EIGHT, PIECES OF EIGHT', self.parrot('pieces of eight')) # ------------------------------------------------------------------ @@ -78,7 +78,7 @@ def test_what_a_decorator_is_doing_to_a_function(self): #wrap the function with the decorator self.sound_check = self.doubleit(self.sound_check) - self.assertEqual(__, self.sound_check()) + self.assertEqual('Testing..., Testing...', self.sound_check()) # ------------------------------------------------------------------ @@ -110,11 +110,11 @@ def idler(self, num): pass def test_decorator_with_an_argument(self): - self.assertEqual(__, self.count_badly(2)) - self.assertEqual(__, self.count_badly.__doc__) + self.assertEqual(5, self.count_badly(2)) + self.assertEqual('Increments a value by one. Kind of.', self.count_badly.__doc__) def test_documentor_which_already_has_a_docstring(self): - self.assertEqual(__, self.idler.__doc__) + self.assertEqual('Idler: Does nothing', self.idler.__doc__) # ------------------------------------------------------------------ @@ -125,5 +125,5 @@ def homer(self): return "D'oh" def test_we_can_chain_decorators(self): - self.assertEqual(__, self.homer()) - self.assertEqual(__, self.homer.__doc__) + self.assertEqual("D'oh, D'oh, D'oh, D'oh", self.homer()) + self.assertEqual('DOH!', self.homer.__doc__) diff --git a/python2/koans/about_decorating_with_functions.py b/python2/koans/about_decorating_with_functions.py index c2bfe28f4..0b08d1aaa 100644 --- a/python2/koans/about_decorating_with_functions.py +++ b/python2/koans/about_decorating_with_functions.py @@ -14,8 +14,8 @@ def mediocre_song(self): return "o/~ We all live in a broken submarine o/~" def test_decorators_can_modify_a_function(self): - self.assertMatch(__, self.mediocre_song()) - self.assertEqual(__, self.mediocre_song.wow_factor) + self.assertMatch("o/~ We all live in a broken submarine o/~", self.mediocre_song()) + self.assertEqual('COWBELL BABY!', self.mediocre_song.wow_factor) # ------------------------------------------------------------------ @@ -29,4 +29,4 @@ def render_tag(self, name): return name def test_decorators_can_change_a_function_output(self): - self.assertEqual(__, self.render_tag('llama')) + self.assertEqual('', self.render_tag('llama')) diff --git a/python2/koans/about_deleting_objects.py b/python2/koans/about_deleting_objects.py index e8a556dc1..d2ee8be05 100644 --- a/python2/koans/about_deleting_objects.py +++ b/python2/koans/about_deleting_objects.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python + #!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * diff --git a/python2/koans/about_dice_project.py b/python2/koans/about_dice_project.py index c2710075f..124f33c6e 100644 --- a/python2/koans/about_dice_project.py +++ b/python2/koans/about_dice_project.py @@ -2,7 +2,6 @@ # -*- coding: utf-8 -*- from runner.koan import * - import random @@ -13,11 +12,16 @@ def __init__(self): @property def values(self): return self._values + + @values.setter + def values(self, value): + self._values = value def roll(self, n): # Needs implementing! # Tip: random.randint(min, max) can be used to generate random numbers - pass + self.values = [random.randint(1, 6) for x in range(0, n)] + class AboutDiceProject(Koan): diff --git a/python2/koans/about_dictionaries.py b/python2/koans/about_dictionaries.py index 8591b5439..8458665db 100644 --- a/python2/koans/about_dictionaries.py +++ b/python2/koans/about_dictionaries.py @@ -13,40 +13,40 @@ def test_creating_dictionaries(self): empty_dict = dict() self.assertEqual(dict, type(empty_dict)) self.assertEqual(dict(), empty_dict) - self.assertEqual(__, len(empty_dict)) + self.assertEqual(0, len(empty_dict)) def test_dictionary_literals(self): empty_dict = {} self.assertEqual(dict, type(empty_dict)) babel_fish = {'one': 'uno', 'two': 'dos'} - self.assertEqual(__, len(babel_fish)) + self.assertEqual(2, len(babel_fish)) def test_accessing_dictionaries(self): babel_fish = {'one': 'uno', 'two': 'dos'} - self.assertEqual(__, babel_fish['one']) - self.assertEqual(__, babel_fish['two']) + self.assertEqual('uno', babel_fish['one']) + self.assertEqual('dos', babel_fish['two']) def test_changing_dictionaries(self): babel_fish = {'one': 'uno', 'two': 'dos'} babel_fish['one'] = 'eins' - expected = {'two': 'dos', 'one': __} + expected = {'two': 'dos', 'one': 'eins'} self.assertEqual(expected, babel_fish) def test_dictionary_is_unordered(self): dict1 = {'one': 'uno', 'two': 'dos'} dict2 = {'two': 'dos', 'one': 'uno'} - self.assertEqual(____, dict1 == dict2) + self.assertEqual(True, dict1 == dict2) def test_dictionary_keys_and_values(self): babel_fish = {'one': 'uno', 'two': 'dos'} - self.assertEqual(__, len(babel_fish.keys())) - self.assertEqual(__, len(babel_fish.values())) - self.assertEqual(__, 'one' in babel_fish.keys()) - self.assertEqual(__, 'two' in babel_fish.values()) - self.assertEqual(__, 'uno' in babel_fish.keys()) - self.assertEqual(__, 'dos' in babel_fish.values()) + self.assertEqual(2, len(babel_fish.keys())) + self.assertEqual(2, len(babel_fish.values())) + self.assertEqual(True, 'one' in babel_fish.keys()) + self.assertEqual(False, 'two' in babel_fish.values()) + self.assertEqual(False, 'uno' in babel_fish.keys()) + self.assertEqual(True, 'dos' in babel_fish.values()) def test_making_a_dictionary_from_a_sequence_of_keys(self): cards = {}.fromkeys( @@ -54,6 +54,6 @@ def test_making_a_dictionary_from_a_sequence_of_keys(self): 'confused looking zebra'), 42) - self.assertEqual(__, len(cards)) - self.assertEqual(__, cards['green elf']) - self.assertEqual(__, cards['yellow dwarf']) + self.assertEqual(5, len(cards)) + self.assertEqual(42, cards['green elf']) + self.assertEqual(42, cards['yellow dwarf']) diff --git a/python2/koans/about_exceptions.py b/python2/koans/about_exceptions.py index dd2b3823f..abd046745 100644 --- a/python2/koans/about_exceptions.py +++ b/python2/koans/about_exceptions.py @@ -11,10 +11,10 @@ class MySpecialError(RuntimeError): def test_exceptions_inherit_from_exception(self): mro = self.MySpecialError.__mro__ - self.assertEqual(__, mro[1].__name__) - self.assertEqual(__, mro[2].__name__) - self.assertEqual(__, mro[3].__name__) - self.assertEqual(__, mro[4].__name__) + self.assertEqual('RuntimeError', mro[1].__name__) + self.assertEqual('StandardError', mro[2].__name__) + self.assertEqual('Exception', mro[3].__name__) + self.assertEqual('BaseException', mro[4].__name__) def test_try_clause(self): result = None @@ -23,15 +23,15 @@ def test_try_clause(self): except StandardError as ex: result = 'exception handled' - self.assertEqual(__, result) + self.assertEqual('exception handled', result) - self.assertEqual(____, isinstance(ex, StandardError)) - self.assertEqual(____, isinstance(ex, RuntimeError)) + self.assertEqual(True, isinstance(ex, StandardError)) + self.assertEqual(False, isinstance(ex, RuntimeError)) self.assertTrue(issubclass(RuntimeError, StandardError), \ "RuntimeError is a subclass of StandardError") - self.assertEqual(__, ex[0]) + self.assertEqual('Oops', ex[0]) def test_raising_a_specific_error(self): result = None @@ -40,8 +40,8 @@ def test_raising_a_specific_error(self): except self.MySpecialError as ex: result = 'exception handled' - self.assertEqual(__, result) - self.assertEqual(__, ex[0]) + self.assertEqual('exception handled', result) + self.assertEqual('My Message', ex[0]) def test_else_clause(self): result = None @@ -53,7 +53,7 @@ def test_else_clause(self): else: result = 'no damage done' - self.assertEqual(__, result) + self.assertEqual('no damage done', result) def test_finally_clause(self): result = None @@ -65,4 +65,4 @@ def test_finally_clause(self): finally: result = 'always run' - self.assertEqual(__, result) + self.assertEqual('always run', result) diff --git a/python2/koans/about_generators.py b/python2/koans/about_generators.py index 5fc239cae..2e4c82563 100644 --- a/python2/koans/about_generators.py +++ b/python2/koans/about_generators.py @@ -19,7 +19,7 @@ def test_generating_values_on_the_fly(self): n in ['crunchy', 'veggie', 'danish']) for bacon in bacon_generator: result.append(bacon) - self.assertEqual(__, result) + self.assertEqual(['crunchy bacon', 'veggie bacon', 'danish bacon'], result) def test_generators_are_different_to_list_comprehensions(self): num_list = [x * 2 for x in range(1, 3)] @@ -28,7 +28,7 @@ def test_generators_are_different_to_list_comprehensions(self): self.assertEqual(2, num_list[0]) # A generator has to be iterated through. - self.assertEqual(__, list(num_generator)[0]) + self.assertEqual(num_list[0], list(num_generator)[0]) # Both list comprehensions and generators can be iterated # though. However, a generator function is only called on the @@ -43,8 +43,8 @@ def test_generator_expressions_are_a_one_shot_deal(self): attempt1 = list(dynamite) attempt2 = list(dynamite) - self.assertEqual(__, list(attempt1)) - self.assertEqual(__, list(attempt2)) + self.assertEqual(['Boom!' for i in range(3)], list(attempt1)) + self.assertEqual([], list(attempt2)) # ------------------------------------------------------------------ @@ -58,12 +58,12 @@ def test_generator_method_will_yield_values_during_iteration(self): result = list() for item in self.simple_generator_method(): result.append(item) - self.assertEqual(__, result) + self.assertEqual(['peanut', 'butter', 'and', 'jelly'], result) def test_coroutines_can_take_arguments(self): result = self.simple_generator_method() - self.assertEqual(__, next(result)) - self.assertEqual(__, next(result)) + self.assertEqual('peanut', next(result)) + self.assertEqual('butter', next(result)) result.close() # ------------------------------------------------------------------ @@ -74,7 +74,7 @@ def square_me(self, seq): def test_generator_method_with_parameter(self): result = self.square_me(range(2, 5)) - self.assertEqual(__, list(result)) + self.assertEqual([4, 9, 16], list(result)) # ------------------------------------------------------------------ @@ -87,7 +87,7 @@ def sum_it(self, seq): def test_generator_keeps_track_of_local_variables(self): result = self.sum_it(range(2, 5)) - self.assertEqual(__, list(result)) + self.assertEqual([2, 5, 9], list(result)) # ------------------------------------------------------------------ @@ -105,7 +105,7 @@ def test_generators_can_take_coroutines(self): # section of http://www.python.org/dev/peps/pep-0342/ next(generator) - self.assertEqual(__, generator.send(1 + 2)) + self.assertEqual(3, generator.send(1 + 2)) def test_before_sending_a_value_to_a_generator_next_must_be_called(self): generator = self.generator_with_coroutine() @@ -113,7 +113,7 @@ def test_before_sending_a_value_to_a_generator_next_must_be_called(self): try: generator.send(1 + 2) except TypeError as ex: - self.assertMatch(__, ex[0]) + self.assertMatch("can't send non-None value to a just-started generator", ex[0]) # ------------------------------------------------------------------ @@ -131,11 +131,11 @@ def test_generators_can_see_if_they_have_been_called_with_a_value(self): generator2 = self.yield_tester() next(generator2) - self.assertEqual(__, next(generator2)) + self.assertEqual('no value', next(generator2)) def test_send_none_is_equivalent_to_next(self): generator = self.yield_tester() next(generator) # 'next(generator)' is exactly equivalent to 'generator.send(None)' - self.assertEqual(__, generator.send(None)) + self.assertEqual('no value', generator.send(None)) diff --git a/python2/koans/about_inheritance.py b/python2/koans/about_inheritance.py index e4310ad9a..e2fd108aa 100644 --- a/python2/koans/about_inheritance.py +++ b/python2/koans/about_inheritance.py @@ -24,31 +24,31 @@ def bark(self): return "yip" def test_subclasses_have_the_parent_as_an_ancestor(self): - self.assertEqual(____, issubclass(self.Chihuahua, self.Dog)) + self.assertEqual(True, issubclass(self.Chihuahua, self.Dog)) def test_this_subclass_ultimately_inherits_from_object_class(self): - self.assertEqual(____, issubclass(self.Chihuahua, object)) + self.assertEqual(True, issubclass(self.Chihuahua, object)) def test_instances_inherit_behavior_from_parent_class(self): chico = self.Chihuahua("Chico") - self.assertEqual(__, chico.name) + self.assertEqual('Chico', chico.name) def test_subclasses_add_new_behavior(self): chico = self.Chihuahua("Chico") - self.assertEqual(__, chico.wag()) + self.assertEqual('happy', chico.wag()) try: fido = self.Dog("Fido") fido.wag() except StandardError as ex: - self.assertMatch(__, ex[0]) + self.assertMatch("'Dog' object has no attribute 'wag'", ex[0]) def test_subclasses_can_modify_existing_behavior(self): chico = self.Chihuahua("Chico") - self.assertEqual(__, chico.bark()) + self.assertEqual('yip', chico.bark()) fido = self.Dog("Fido") - self.assertEqual(__, fido.bark()) + self.assertEqual('WOOF', fido.bark()) # ------------------------------------------------------------------ @@ -58,7 +58,7 @@ def bark(self): def test_subclasses_can_invoke_parent_behavior_via_super(self): ralph = self.BullDog("Ralph") - self.assertEqual(__, ralph.bark()) + self.assertEqual('WOOF, GRR', ralph.bark()) # ------------------------------------------------------------------ @@ -68,7 +68,7 @@ def growl(self): def test_super_works_across_methods(self): george = self.GreatDane("George") - self.assertEqual(__, george.growl()) + self.assertEqual('WOOF, GROWL', george.growl()) # --------------------------------------------------------- @@ -85,8 +85,8 @@ def test_base_init_does_not_get_called_automatically(self): try: name = snoopy.name except Exception as ex: - self.assertMatch(__, ex[0]) + self.assertMatch("'Pug' object has no attribute '_name'", ex[0]) def test_base_init_has_to_be_called_explicitly(self): boxer = self.Greyhound("Boxer") - self.assertEqual(__, boxer.name) + self.assertEqual('Boxer', boxer.name) diff --git a/python2/koans/about_iteration.py b/python2/koans/about_iteration.py index 3b7bfed79..c4e9a861b 100644 --- a/python2/koans/about_iteration.py +++ b/python2/koans/about_iteration.py @@ -14,20 +14,20 @@ def test_iterators_are_a_type(self): for num in it: fib += num - self.assertEqual(__, fib) + self.assertEqual(15, fib) def test_iterating_with_next(self): stages = iter(['alpha', 'beta', 'gamma']) try: - self.assertEqual(__, next(stages)) + self.assertEqual('alpha', next(stages)) next(stages) - self.assertEqual(__, next(stages)) + self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' - self.assertMatch(__, err_msg) + self.assertMatch('Ran out of iterations', err_msg) # ------------------------------------------------------------------ @@ -38,7 +38,7 @@ def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = map(self.add_ten, seq) - self.assertEqual(__, mapped_seq) + self.assertEqual([11, 12, 13], mapped_seq) def test_filter_selects_certain_items_from_a_list(self): def is_even(item): @@ -47,7 +47,7 @@ def is_even(item): seq = [1, 2, 3, 4, 5, 6] even_numbers = filter(is_even, seq) - self.assertEqual(__, even_numbers) + self.assertEqual([2, 4, 6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): @@ -57,12 +57,12 @@ def is_big_name(item): # NOTE This still iterates through the whole names, so not particularly # efficient - self.assertEqual([__], filter(is_big_name, names)[:1]) + self.assertEqual(["Clarence"], filter(is_big_name, names)[:1]) # Boring but effective for item in names: if is_big_name(item): - self.assertEqual(__, item) + self.assertEqual("Clarence", item) break # ------------------------------------------------------------------ @@ -75,10 +75,10 @@ def multiply(self, accum, item): def test_reduce_will_blow_your_mind(self): result = reduce(self.add, [2, 3, 4]) - self.assertEqual(__, result) + self.assertEqual(9, result) result2 = reduce(self.multiply, [2, 3, 4], 1) - self.assertEqual(__, result2) + self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. @@ -89,14 +89,14 @@ def test_use_pass_for_iterations_with_no_body(self): for num in range(1, 5): pass - self.assertEqual(__, num) + self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iteratable sequence result = map(self.add_ten, range(1, 4)) - self.assertEqual(__, list(result)) + self.assertEqual([11, 12, 13], list(result)) try: f = open("example_file.txt") @@ -105,7 +105,7 @@ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, f.readlines()) - self.assertEqual(__, list(upcase_lines)) + self.assertEqual(['THIS', 'IS', 'A', 'TEST'], list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. diff --git a/python2/koans/about_lambdas.py b/python2/koans/about_lambdas.py index dfc72f9e6..fb8352139 100644 --- a/python2/koans/about_lambdas.py +++ b/python2/koans/about_lambdas.py @@ -11,7 +11,7 @@ class AboutLambdas(Koan): def test_lambdas_can_be_assigned_to_variables_and_called_explicitly(self): add_one = lambda n: n + 1 - self.assertEqual(__, add_one(10)) + self.assertEqual(11, add_one(10)) # ------------------------------------------------------------------ @@ -22,8 +22,8 @@ def test_accessing_lambda_via_assignment(self): sausages = self.make_order('sausage') eggs = self.make_order('egg') - self.assertEqual(__, sausages(3)) - self.assertEqual(__, eggs(2)) + self.assertEqual('3 sausages', sausages(3)) + self.assertEqual('2 eggs', eggs(2)) def test_accessing_lambda_without_assignment(self): - self.assertEqual(__, self.make_order('spam')(39823)) + self.assertEqual('39823 spams', self.make_order('spam')(39823)) diff --git a/python2/koans/about_list_assignments.py b/python2/koans/about_list_assignments.py index 2c0267805..510fe2eaf 100644 --- a/python2/koans/about_list_assignments.py +++ b/python2/koans/about_list_assignments.py @@ -11,21 +11,21 @@ class AboutListAssignments(Koan): def test_non_parallel_assignment(self): names = ["John", "Smith"] - self.assertEqual(__, names) + self.assertEqual(["John", "Smith"], names) def test_parallel_assignments(self): first_name, last_name = ["John", "Smith"] - self.assertEqual(__, first_name) - self.assertEqual(__, last_name) + self.assertEqual('John', first_name) + self.assertEqual('Smith', last_name) def test_parallel_assignments_with_sublists(self): first_name, last_name = [["Willie", "Rae"], "Johnson"] - self.assertEqual(__, first_name) - self.assertEqual(__, last_name) + self.assertEqual(['Willie', 'Rae'], first_name) + self.assertEqual('Johnson', last_name) def test_swapping_with_parallel_assignment(self): first_name = "Roy" last_name = "Rob" first_name, last_name = last_name, first_name - self.assertEqual(__, first_name) - self.assertEqual(__, last_name) + self.assertEqual('Rob', first_name) + self.assertEqual('Roy', last_name) diff --git a/python2/koans/about_lists.py b/python2/koans/about_lists.py index 4d2588272..75cca1fb1 100644 --- a/python2/koans/about_lists.py +++ b/python2/koans/about_lists.py @@ -12,7 +12,7 @@ class AboutLists(Koan): def test_creating_lists(self): empty_list = list() self.assertEqual(list, type(empty_list)) - self.assertEqual(__, len(empty_list)) + self.assertEqual(0, len(empty_list)) def test_list_literals(self): nums = list() @@ -22,68 +22,68 @@ def test_list_literals(self): self.assertEqual([1], nums) nums[1:] = [2] - self.assertEqual([1, __], nums) + self.assertEqual([1, 2], nums) nums.append(333) - self.assertEqual([1, 2, __], nums) + self.assertEqual([1, 2, 333], nums) def test_accessing_list_elements(self): noms = ['peanut', 'butter', 'and', 'jelly'] - self.assertEqual(__, noms[0]) - self.assertEqual(__, noms[3]) - self.assertEqual(__, noms[-1]) - self.assertEqual(__, noms[-3]) + self.assertEqual('peanut', noms[0]) + self.assertEqual("jelly", noms[3]) + self.assertEqual('jelly', noms[-1]) + self.assertEqual("butter", noms[-3]) def test_slicing_lists(self): noms = ['peanut', 'butter', 'and', 'jelly'] - self.assertEqual(__, noms[0:1]) - self.assertEqual(__, noms[0:2]) - self.assertEqual(__, noms[2:2]) - self.assertEqual(__, noms[2:20]) - self.assertEqual(__, noms[4:0]) - self.assertEqual(__, noms[4:100]) - self.assertEqual(__, noms[5:0]) + self.assertEqual(['peanut'], noms[0:1]) + self.assertEqual(['peanut', 'butter'], noms[0:2]) + self.assertEqual([], noms[2:2]) + self.assertEqual(['and', 'jelly'], noms[2:20]) + self.assertEqual([], noms[4:0]) + self.assertEqual([], noms[4:100]) + self.assertEqual([], noms[5:0]) def test_slicing_to_the_edge(self): noms = ['peanut', 'butter', 'and', 'jelly'] - self.assertEqual(__, noms[2:]) - self.assertEqual(__, noms[:2]) + self.assertEqual(['and', 'jelly'], noms[2:]) + self.assertEqual(['peanut', 'butter'], noms[:2]) def test_lists_and_ranges(self): self.assertEqual(list, type(range(5))) - self.assertEqual(__, range(5)) - self.assertEqual(__, range(5, 9)) + self.assertEqual([0, 1, 2, 3, 4, ], range(5)) + self.assertEqual([5, 6, 7, 8], range(5, 9)) def test_ranges_with_steps(self): - self.assertEqual(__, range(0, 8, 2)) - self.assertEqual(__, range(1, 8, 3)) - self.assertEqual(__, range(5, -7, -4)) - self.assertEqual(__, range(5, -8, -4)) + self.assertEqual([0, 2, 4, 6], range(0, 8, 2)) + self.assertEqual([1, 4, 7], range(1, 8, 3)) + self.assertEqual([5, 1, -3], range(5, -7, -4)) + self.assertEqual([5, 1, -3, -7], range(5, -8, -4)) def test_insertions(self): knight = ['you', 'shall', 'pass'] knight.insert(2, 'not') - self.assertEqual(__, knight) + self.assertEqual(['you', 'shall', 'not', 'pass'], knight) knight.insert(0, 'Arthur') - self.assertEqual(__, knight) + self.assertEqual(['Arthur', 'you', 'shall', 'not', 'pass'], knight) def test_popping_lists(self): stack = [10, 20, 30, 40] stack.append('last') - self.assertEqual(__, stack) + self.assertEqual([10, 20, 30, 40, 'last'], stack) popped_value = stack.pop() - self.assertEqual(__, popped_value) - self.assertEqual(__, stack) + self.assertEqual('last', popped_value) + self.assertEqual([10, 20, 30, 40], stack) popped_value = stack.pop(1) - self.assertEqual(__, popped_value) - self.assertEqual(__, stack) + self.assertEqual(20, popped_value) + self.assertEqual([10,30,40], stack) # Notice that there is a "pop" but no "push" in python? @@ -99,8 +99,8 @@ def test_use_deques_for_making_queues(self): queue = deque([1, 2]) queue.append('last') - self.assertEqual(__, list(queue)) + self.assertEqual([1, 2, 'last'], list(queue)) popped_value = queue.popleft() - self.assertEqual(__, popped_value) - self.assertEqual(__, list(queue)) + self.assertEqual(1, popped_value) + self.assertEqual([2, 'last'], list(queue)) diff --git a/python2/koans/about_method_bindings.py b/python2/koans/about_method_bindings.py index dfa87894f..cbeac90a8 100644 --- a/python2/koans/about_method_bindings.py +++ b/python2/koans/about_method_bindings.py @@ -20,47 +20,47 @@ def method(self): class AboutMethodBindings(Koan): def test_methods_are_bound_to_an_object(self): obj = Class() - self.assertEqual(__, obj.method.im_self == obj) + self.assertEqual(True, obj.method.im_self == obj) def test_methods_are_also_bound_to_a_function(self): obj = Class() - self.assertEqual(__, obj.method()) - self.assertEqual(__, obj.method.im_func(obj)) + self.assertEqual('parrot', obj.method()) + self.assertEqual('parrot', obj.method.im_func(obj)) def test_functions_have_attributes(self): - self.assertEqual(__, len(dir(function))) - self.assertEqual(__, dir(function) == dir(Class.method.im_func)) + self.assertEqual(31, len(dir(function))) + self.assertEqual(True, dir(function) == dir(Class.method.im_func)) def test_bound_methods_have_different_attributes(self): obj = Class() - self.assertEqual(__, len(dir(obj.method))) + self.assertEqual(23, len(dir(obj.method))) def test_setting_attributes_on_an_unbound_function(self): function.cherries = 3 - self.assertEqual(__, function.cherries) + self.assertEqual(3, function.cherries) def test_setting_attributes_on_a_bound_method_directly(self): obj = Class() try: obj.method.cherries = 3 except AttributeError as ex: - self.assertMatch(__, ex[0]) + self.assertMatch("'instancemethod' object has no attribute 'cherries'", ex[0]) def test_setting_attributes_on_methods_by_accessing_the_inner_function(self): obj = Class() obj.method.im_func.cherries = 3 - self.assertEqual(__, obj.method.cherries) + self.assertEqual(3, obj.method.cherries) def test_functions_can_have_inner_functions(self): function2.get_fruit = function - self.assertEqual(__, function2.get_fruit()) + self.assertEqual('pineapple', function2.get_fruit()) def test_inner_functions_are_unbound(self): function2.get_fruit = function try: cls = function2.get_fruit.im_self except AttributeError as ex: - self.assertMatch(__, ex[0]) + self.assertMatch("'function' object has no attribute 'im_self'", ex[0]) # ------------------------------------------------------------------ @@ -77,8 +77,8 @@ def test_get_descriptor_resolves_attribute_binding(self): # binding_owner = obj # owner_type = cls - self.assertEqual(__, bound_obj.__class__.__name__) - self.assertEqual(__, binding_owner.__class__.__name__) + self.assertEqual('BoundClass', bound_obj.__class__.__name__) + self.assertEqual('AboutMethodBindings', binding_owner.__class__.__name__) self.assertEqual(AboutMethodBindings, owner_type) # ------------------------------------------------------------------ @@ -95,4 +95,4 @@ def __set__(self, obj, val): def test_set_descriptor_changes_behavior_of_attribute_assignment(self): self.assertEqual(None, self.color.choice) self.color = 'purple' - self.assertEqual(__, self.color.choice) + self.assertEqual('purple', self.color.choice) diff --git a/python2/koans/about_methods.py b/python2/koans/about_methods.py index fd924f9c9..1a3f3de30 100644 --- a/python2/koans/about_methods.py +++ b/python2/koans/about_methods.py @@ -14,7 +14,7 @@ def my_global_function(a, b): class AboutMethods(Koan): def test_calling_a_global_function(self): - self.assertEqual(__, my_global_function(2, 3)) + self.assertEqual(5, my_global_function(2, 3)) # NOTE: Wrong number of arguments is not a SYNTAX error, but a # runtime error. @@ -24,7 +24,7 @@ def test_calling_functions_with_wrong_number_of_arguments(self): except Exception as exception: # NOTE: The .__name__ attribute will convert the class # into a string value. - self.assertEqual(__, exception.__class__.__name__) + self.assertEqual('TypeError', exception.__class__.__name__) self.assertMatch( r'my_global_function\(\) takes exactly 2 arguments \(0 given\)', exception[0]) @@ -34,7 +34,7 @@ def test_calling_functions_with_wrong_number_of_arguments(self): except Exception as e: # Note, watch out for parenthesis. They need slashes in front! - self.assertMatch(__, e[0]) + self.assertMatch( r'my_global_function\(\) takes exactly 2 arguments \(3 given\)', e[0]) # ------------------------------------------------------------------ @@ -42,7 +42,7 @@ def pointless_method(self, a, b): sum = a + b def test_which_does_not_return_anything(self): - self.assertEqual(__, self.pointless_method(1, 2)) + self.assertEqual(None, self.pointless_method(1, 2)) # Notice that methods accessed from class scope do not require # you to pass the first "self" argument? @@ -52,8 +52,8 @@ def method_with_defaults(self, a, b='default_value'): return [a, b] def test_calling_with_default_values(self): - self.assertEqual(__, self.method_with_defaults(1)) - self.assertEqual(__, self.method_with_defaults(1, 2)) + self.assertEqual([1, 'default_value'], self.method_with_defaults(1)) + self.assertEqual([1, 2], self.method_with_defaults(1, 2)) # ------------------------------------------------------------------ @@ -61,9 +61,9 @@ def method_with_var_args(self, *args): return args def test_calling_with_variable_arguments(self): - self.assertEqual(__, self.method_with_var_args()) + self.assertEqual((), self.method_with_var_args()) self.assertEqual(('one', ), self.method_with_var_args('one')) - self.assertEqual(__, self.method_with_var_args('one', 'two')) + self.assertEqual(('one', 'two'), self.method_with_var_args('one', 'two')) # ------------------------------------------------------------------ @@ -74,13 +74,13 @@ def test_functions_without_self_arg_are_global_functions(self): def function_with_the_same_name(a, b): return a * b - self.assertEqual(__, function_with_the_same_name(3, 4)) + self.assertEqual(12, function_with_the_same_name(3, 4)) def test_calling_methods_in_same_class_with_explicit_receiver(self): def function_with_the_same_name(a, b): return a * b - self.assertEqual(__, self.function_with_the_same_name(3, 4)) + self.assertEqual(7, self.function_with_the_same_name(3, 4)) # ------------------------------------------------------------------ @@ -93,10 +93,10 @@ def another_method_with_the_same_name(self): return 42 def test_that_old_methods_are_hidden_by_redefinitions(self): - self.assertEqual(__, self.another_method_with_the_same_name()) + self.assertEqual(42, self.another_method_with_the_same_name()) def test_that_overlapped_method_is_still_there(self): - self.assertEqual(__, self.link_to_overlapped_method()) + self.assertEqual(10, self.link_to_overlapped_method()) # ------------------------------------------------------------------ @@ -104,21 +104,21 @@ def empty_method(self): pass def test_methods_that_do_nothing_need_to_use_pass_as_a_filler(self): - self.assertEqual(__, self.empty_method()) + self.assertEqual(None, self.empty_method()) def test_pass_does_nothing_at_all(self): "You" "shall" "not" pass - self.assertEqual(____, "Still got to this line" != None) + self.assertEqual(True, "Still got to this line" != None) # ------------------------------------------------------------------ def one_line_method(self): return 'Madagascar' def test_no_indentation_required_for_one_line_statement_bodies(self): - self.assertEqual(__, self.one_line_method()) + self.assertEqual('Madagascar', self.one_line_method()) # ------------------------------------------------------------------ @@ -127,7 +127,7 @@ def method_with_documentation(self): return "ok" def test_the_documentation_can_be_viewed_with_the_doc_method(self): - self.assertMatch(__, self.method_with_documentation.__doc__) + self.assertMatch("A string placed at the beginning of a function is used for documentation", self.method_with_documentation.__doc__) # ------------------------------------------------------------------ @@ -144,13 +144,13 @@ def __password(self): def test_calling_methods_in_other_objects(self): rover = self.Dog() - self.assertEqual(__, rover.name()) + self.assertEqual('Fido', rover.name()) def test_private_access_is_implied_but_not_enforced(self): rover = self.Dog() # This is a little rude, but legal - self.assertEqual(__, rover._tail()) + self.assertEqual('wagging', rover._tail()) def test_double_underscore_attribute_prefixes_cause_name_mangling(self): """Attributes names that start with a double underscore get @@ -160,10 +160,10 @@ def test_double_underscore_attribute_prefixes_cause_name_mangling(self): #This may not be possible... password = rover.__password() except Exception as ex: - self.assertEqual(__, ex.__class__.__name__) + self.assertEqual('AttributeError', ex.__class__.__name__) # But this still is! - self.assertEqual(__, rover._Dog__password()) + self.assertEqual('password', rover._Dog__password()) # Name mangling exists to avoid name clash issues when subclassing. # It is not for providing effective access protection diff --git a/python2/koans/about_modules.py b/python2/koans/about_modules.py index ddd1be9ff..ae5ec076f 100644 --- a/python2/koans/about_modules.py +++ b/python2/koans/about_modules.py @@ -17,21 +17,21 @@ def test_importing_other_python_scripts_as_modules(self): import local_module # local_module.py duck = local_module.Duck() - self.assertEqual(__, duck.name) + self.assertEqual('Daffy', duck.name) def test_importing_attributes_from_classes_using_from_keyword(self): from local_module import Duck duck = Duck() # no module qualifier needed this time - self.assertEqual(__, duck.name) + self.assertEqual('Daffy', duck.name) def test_we_can_import_multiple_items_at_once(self): import jims, joes jims_dog = jims.Dog() joes_dog = joes.Dog() - self.assertEqual(__, jims_dog.identify()) - self.assertEqual(__, joes_dog.identify()) + self.assertEqual('jims dog', jims_dog.identify()) + self.assertEqual('joes dog', joes_dog.identify()) def test_importing_all_module_attributes_at_once(self): """ @@ -43,20 +43,20 @@ def test_importing_all_module_attributes_at_once(self): goose = Goose() hamster = Hamster() - self.assertEqual(__, goose.name) - self.assertEqual(__, hamster.name) + self.assertEqual('Mr Stabby', goose.name) + self.assertEqual('Phil', hamster.name) def test_modules_hide_attributes_prefixed_by_underscores(self): try: private_squirrel = _SecretSquirrel() except NameError as ex: - self.assertMatch(__, ex[0]) + self.assertMatch("global name '_SecretSquirrel' is not defined", ex[0]) def test_private_attributes_are_still_accessible_in_modules(self): from local_module import Duck # local_module.py duck = Duck() - self.assertEqual(__, duck._password) + self.assertEqual('password', duck._password) # module level attribute hiding doesn't affect class attributes # (unless the class itself is hidden). @@ -65,14 +65,14 @@ def test_a_modules_XallX_statement_limits_what_wildcards_will_match(self): # 'Goat' is on the __all__ list goat = Goat() - self.assertEqual(__, goat.name) + self.assertEqual('George', goat.name) # How about velociraptors? lizard = _Velociraptor() - self.assertEqual(__, lizard.name) + self.assertEqual('Cuddles', lizard.name) # SecretDuck? Never heard of her! try: duck = SecretDuck() except NameError as ex: - self.assertMatch(__, ex[0]) + self.assertMatch("global name 'SecretDuck' is not defined", ex[0]) diff --git a/python2/koans/about_monkey_patching.py b/python2/koans/about_monkey_patching.py index 65bd461d9..3c0979a68 100644 --- a/python2/koans/about_monkey_patching.py +++ b/python2/koans/about_monkey_patching.py @@ -15,7 +15,7 @@ def bark(self): def test_as_defined_dogs_do_bark(self): fido = self.Dog() - self.assertEqual(__, fido.bark()) + self.assertEqual('WOOF', fido.bark()) # ------------------------------------------------------------------ @@ -27,8 +27,8 @@ def wag(self): self.Dog.wag = wag fido = self.Dog() - self.assertEqual(__, fido.wag()) - self.assertEqual(__, fido.bark()) + self.assertEqual('HAPPY', fido.wag()) + self.assertEqual('WOOF', fido.bark()) # ------------------------------------------------------------------ @@ -36,7 +36,7 @@ def test_most_built_in_classes_cannot_be_monkey_patched(self): try: int.is_even = lambda self: (self % 2) == 0 except StandardError as ex: - self.assertMatch(__, ex[0]) + self.assertMatch("can't set attributes of built-in/extension type 'int'", ex[0]) # ------------------------------------------------------------------ @@ -46,5 +46,5 @@ class MyInt(int): def test_subclasses_of_built_in_classes_can_be_be_monkey_patched(self): self.MyInt.is_even = lambda self: (self % 2) == 0 - self.assertEqual(____, self.MyInt(1).is_even()) - self.assertEqual(____, self.MyInt(2).is_even()) + self.assertEqual(False, self.MyInt(1).is_even()) + self.assertEqual(True, self.MyInt(2).is_even()) diff --git a/python2/koans/about_multiple_inheritance.py b/python2/koans/about_multiple_inheritance.py index b204c85c5..446a93e6c 100644 --- a/python2/koans/about_multiple_inheritance.py +++ b/python2/koans/about_multiple_inheritance.py @@ -88,7 +88,7 @@ def here(self): def test_normal_methods_are_available_in_the_object(self): jeff = self.Spiderpig() - self.assertMatch(__, jeff.speak()) + self.assertMatch('This looks like a job for Spiderpig!', jeff.speak()) def test_base_class_methods_are_also_available_in_the_object(self): jeff = self.Spiderpig() @@ -96,22 +96,22 @@ def test_base_class_methods_are_also_available_in_the_object(self): jeff.set_name("Rover") except: self.fail("This should not happen") - self.assertEqual(____, jeff.can_climb_walls()) + self.assertEqual(True, jeff.can_climb_walls()) def test_base_class_methods_can_affect_instance_variables_in_the_object(self): jeff = self.Spiderpig() - self.assertEqual(__, jeff.name) + self.assertEqual('Jeff', jeff.name) jeff.set_name("Rover") - self.assertEqual(__, jeff.name) + self.assertEqual('Rover', jeff.name) def test_left_hand_side_inheritance_tends_to_be_higher_priority(self): jeff = self.Spiderpig() - self.assertEqual(__, jeff.color()) + self.assertEqual('pink', jeff.color()) def test_super_class_methods_are_higher_priority_than_super_super_classes(self): jeff = self.Spiderpig() - self.assertEqual(__, jeff.legs()) + self.assertEqual(8, jeff.legs()) def test_we_can_inspect_the_method_resolution_order(self): # @@ -120,10 +120,10 @@ def test_we_can_inspect_the_method_resolution_order(self): mro = type(self.Spiderpig()).__mro__ self.assertEqual('Spiderpig', mro[0].__name__) self.assertEqual('Pig', mro[1].__name__) - self.assertEqual(__, mro[2].__name__) - self.assertEqual(__, mro[3].__name__) - self.assertEqual(__, mro[4].__name__) - self.assertEqual(__, mro[5].__name__) + self.assertEqual('Spider', mro[2].__name__) + self.assertEqual('Animal', mro[3].__name__) + self.assertEqual('Nameable', mro[4].__name__) + self.assertEqual('object', mro[5].__name__) def test_confirm_the_mro_controls_the_calling_order(self): jeff = self.Spiderpig() @@ -133,7 +133,7 @@ def test_confirm_the_mro_controls_the_calling_order(self): self.assertMatch('Pig', next.here()) next = super(AboutMultipleInheritance.Pig, jeff) - self.assertMatch(__, next.here()) + self.assertMatch('Spider', next.here()) # Hang on a minute?!? That last class name might be a super class of # the 'jeff' object, but its hardly a superclass of Pig, is it? diff --git a/python2/koans/about_new_style_classes.py b/python2/koans/about_new_style_classes.py index 6a2077580..8244bee7b 100644 --- a/python2/koans/about_new_style_classes.py +++ b/python2/koans/about_new_style_classes.py @@ -18,15 +18,14 @@ class NewStyleClass(object): pass def test_new_style_classes_inherit_from_object_base_class(self): - self.assertEqual(____, issubclass(self.NewStyleClass, object)) - self.assertEqual(____, issubclass(self.OldStyleClass, object)) + self.assertEqual(True, issubclass(self.NewStyleClass, object)) + self.assertEqual(False, issubclass(self.OldStyleClass, object)) def test_new_style_classes_have_more_attributes(self): - self.assertEqual(__, len(dir(self.OldStyleClass))) - self.assertEqual(__, self.OldStyleClass.__doc__) - self.assertEqual(__, self.OldStyleClass.__module__) - - self.assertEqual(__, len(dir(self.NewStyleClass))) + self.assertEqual(2, len(dir(self.OldStyleClass))) + self.assertEqual('An old style class', self.OldStyleClass.__doc__) + self.assertEqual('koans.about_new_style_classes' , self.OldStyleClass.__module__) + self.assertEqual(18, len(dir(self.NewStyleClass))) # To examine the available attributes, run # 'dir()' # from a python console @@ -34,7 +33,7 @@ def test_new_style_classes_have_more_attributes(self): # ------------------------------------------------------------------ def test_old_style_classes_have_type_but_no_class_attribute(self): - self.assertEqual(__, type(self.OldStyleClass).__name__) + self.assertEqual('classobj', type(self.OldStyleClass).__name__) try: cls = self.OldStyleClass.__class__.__name__ @@ -42,23 +41,24 @@ def test_old_style_classes_have_type_but_no_class_attribute(self): pass # What was that error message from the exception? - self.assertMatch(__, ex[0]) + self.assertMatch("class OldStyleClass has no attribute '__class__'", ex[0]) def test_new_style_classes_have_same_class_as_type(self): new_style = self.NewStyleClass() - self.assertEqual(__, self.NewStyleClass.__class__) + self.assertEqual(type(self.NewStyleClass), self.NewStyleClass.__class__) self.assertEqual( - __, + True, type(self.NewStyleClass) == self.NewStyleClass.__class__) # ------------------------------------------------------------------ def test_in_old_style_instances_class_is_different_to_type(self): old_style = self.OldStyleClass() - self.assertEqual(__, old_style.__class__.__name__) - self.assertEqual(__, type(old_style).__name__) + self.assertEqual('OldStyleClass', old_style.__class__.__name__) + self.assertEqual('instance', type(old_style).__name__) def test_new_style_instances_have_same_class_as_type(self): new_style = self.NewStyleClass() - self.assertEqual(__, new_style.__class__.__name__) - self.assertEqual(__, type(new_style) == new_style.__class__) + self.assertEqual('NewStyleClass', new_style.__class__.__name__) + self.assertEqual(True, type(new_style) == new_style.__class__) + diff --git a/python2/koans/about_none.py b/python2/koans/about_none.py index e64164dbd..498da5cee 100644 --- a/python2/koans/about_none.py +++ b/python2/koans/about_none.py @@ -12,11 +12,11 @@ class AboutNone(Koan): def test_none_is_an_object(self): "Unlike NULL in a lot of languages" - self.assertEqual(__, isinstance(None, object)) + self.assertEqual(True, isinstance(None, object)) def test_none_is_universal(self): "There is only one None" - self.assertEqual(__, None is None) + self.assertEqual(True, None is None) def test_what_exception_do_you_get_when_calling_nonexistent_methods(self): """ @@ -37,15 +37,15 @@ def test_what_exception_do_you_get_when_calling_nonexistent_methods(self): # Need a recap on how to evaluate __class__ attributes? # https://github.com/gregmalcolm/python_koans/wiki/Class-Attribute - self.assertEqual(__, ex.__class__) + self.assertEqual(AttributeError, ex.__class__) # What message was attached to the exception? # (HINT: replace __ with part of the error message.) - self.assertMatch(__, ex.args[0]) + self.assertMatch("'NoneType' object has no attribute 'some_method_none_does_not_know_about'", ex.args[0]) def test_none_is_distinct(self): """ None is distinct from other things which are False. """ - self.assertEqual(____, None is not 0) - self.assertEqual(____, None is not False) + self.assertEqual(True, None is not 0) + self.assertEqual(True, None is not False) diff --git a/python2/koans/about_packages.py b/python2/koans/about_packages.py index 99293ebd7..4581d814a 100644 --- a/python2/koans/about_packages.py +++ b/python2/koans/about_packages.py @@ -30,20 +30,20 @@ def test_subfolders_can_form_part_of_a_module_package(self): from a_package_folder.a_module import Duck duck = Duck() - self.assertEqual(__, duck.name) + self.assertEqual('Donald', duck.name) def test_subfolders_become_modules_if_they_have_an_init_module(self): # Import ./a_package_folder/__init__.py from a_package_folder import an_attribute - self.assertEqual(__, an_attribute) + self.assertEqual(1984, an_attribute) def test_subfolders_without_an_init_module_are_not_part_of_the_package(self): # Import ./a_normal_folder/ try: import a_normal_folder except ImportError as ex: - self.assertMatch(__, ex[0]) + self.assertMatch("No module named a_normal_folder", ex[0]) # ------------------------------------------------------------------ @@ -51,7 +51,7 @@ def test_use_absolute_imports_to_import_upper_level_modules(self): # Import /contemplate_koans.py import contemplate_koans - self.assertEqual(__, contemplate_koans.__name__) + self.assertEqual('contemplate_koans', contemplate_koans.__name__) # contemplate_koans.py is the root module in this package because its # the first python module called in koans. @@ -65,4 +65,4 @@ def test_import_a_module_in_a_subfolder_using_an_absolute_path(self): # Import contemplate_koans.py/koans/a_package_folder/a_module.py from koans.a_package_folder.a_module import Duck - self.assertEqual(__, Duck.__module__) + self.assertEqual('koans.a_package_folder.a_module', Duck.__module__) diff --git a/python2/koans/about_regex.py b/python2/koans/about_regex.py index 3a0a57092..95678d2eb 100755 --- a/python2/koans/about_regex.py +++ b/python2/koans/about_regex.py @@ -63,8 +63,8 @@ def test_matching_literal_text_not_case_sensitivity(self): string = "Hello, my name is Felix or felix and this koan " + \ "is based on Ben's book: Regular Expressions in 10 minutes." - self.assertEqual(re.findall("felix", string), __) - self.assertEqual(re.findall("felix", string, re.IGNORECASE), __) + self.assertEqual(re.findall("felix", string, 20), __) + self.assertEqual(re.findall("felix", string, 10), __) def test_matching_any_character(self): """ diff --git a/python2/koans/about_scope.py b/python2/koans/about_scope.py index aca08058f..7cdff14a3 100644 --- a/python2/koans/about_scope.py +++ b/python2/koans/about_scope.py @@ -20,18 +20,18 @@ def test_dog_is_not_available_in_the_current_scope(self): try: fido = Dog() except Exception as ex: - self.assertMatch(__, ex[0]) + self.assertMatch("global name 'Dog' is not defined", ex[0]) def test_you_can_reference_nested_classes_using_the_scope_operator(self): fido = jims.Dog() # name 'jims' module name is taken from jims.py filename rover = joes.Dog() - self.assertEqual(__, fido.identify()) - self.assertEqual(__, rover.identify()) + self.assertEqual('jims dog', fido.identify()) + self.assertEqual('joes dog', rover.identify()) - self.assertEqual(____, type(fido) == type(rover)) - self.assertEqual(____, jims.Dog == joes.Dog) + self.assertEqual(False, type(fido) == type(rover)) + self.assertEqual(False, jims.Dog == joes.Dog) # ------------------------------------------------------------------ @@ -39,26 +39,26 @@ class str(object): pass def test_bare_bones_class_names_do_not_assume_the_current_scope(self): - self.assertEqual(____, AboutScope.str == str) + self.assertEqual(False, AboutScope.str == str) def test_nested_string_is_not_the_same_as_the_system_string(self): - self.assertEqual(____, self.str == type("HI")) + self.assertEqual(False, self.str == type("HI")) def test_str_without_self_prefix_stays_in_the_global_scope(self): - self.assertEqual(____, str == type("HI")) + self.assertEqual(True, str == type("HI")) # ------------------------------------------------------------------ PI = 3.1416 def test_constants_are_defined_with_an_initial_uppercase_letter(self): - self.assertAlmostEqual(_____, self.PI) + self.assertAlmostEqual(3.1416, self.PI) # Note, floating point numbers in python are not precise. # assertAlmostEqual will check that it is 'close enough' def test_constants_are_assumed_by_convention_only(self): self.PI = "rhubarb" - self.assertEqual(_____, self.PI) + self.assertEqual('rhubarb', self.PI) # There aren't any real constants in python. Its up to the developer # to keep to the convention and not modify them. @@ -75,13 +75,13 @@ def test_incrementing_with_local_counter(self): global counter start = counter self.increment_using_local_counter(start) - self.assertEqual(____, counter == start + 1) + self.assertEqual(False, counter == start + 1) def test_incrementing_with_global_counter(self): global counter start = counter self.increment_using_global_counter() - self.assertEqual(____, counter == start + 1) + self.assertEqual(True, counter == start + 1) # ------------------------------------------------------------------ @@ -89,4 +89,4 @@ def test_incrementing_with_global_counter(self): deadly_bingo = [4, 8, 15, 16, 23, 42] def test_global_attributes_can_be_created_in_the_middle_of_a_class(self): - self.assertEqual(__, deadly_bingo[5]) + self.assertEqual(42, deadly_bingo[5]) diff --git a/python2/koans/about_scoring_project.py b/python2/koans/about_scoring_project.py index da51563b4..3bd45ec7c 100644 --- a/python2/koans/about_scoring_project.py +++ b/python2/koans/about_scoring_project.py @@ -12,19 +12,27 @@ # # * A set of three ones is 1000 points # +# [1,1,1] == 1000 pt +# # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # +# [x, x, x] for x <> 1 == 100 * x +# # * A one (that is not part of a set of three) is worth 100 points. # +# [1, x, y] == 100 pt +# # * A five (that is not part of a set of three) is worth 50 points. # +# [5, x, y] == 50 pt +# # * Everything else is worth 0 points. # # # Examples: # -# score([1, 1, 1, 5, 1]) => 1150 points +# score([1, 1, 1, 5, 1]) => 1150 points # score([2, 3, 4, 6, 2]) => 0 points # score([3, 4, 5, 3, 3]) => 350 points # score([1, 5, 1, 2, 4]) => 250 points @@ -34,8 +42,39 @@ # Your goal is to write the score method. def score(dice): - # You need to write this method - pass + score = 0 + + def make_count(seed): + + def count(list): + counter = 0 + for i in list: + if i == seed: + counter += 1 + return counter + return count + + counts = [make_count(x)(dice) for x in range(1,7)] + + for pos, x in enumerate(counts, start = 1): + + if pos == 1: + if x >= 3: + score += 1000 + x -= 3 + score += x * 100 + + if pos == 5: + if x >= 3: + score += 500 + x -= 3 + score += x * 50 + + elif x >= 3: + score += pos * 100 + + return score + class AboutScoringProject(Koan): diff --git a/python2/koans/about_sets.py b/python2/koans/about_sets.py index 86403d5d5..4af15f985 100644 --- a/python2/koans/about_sets.py +++ b/python2/koans/about_sets.py @@ -11,13 +11,13 @@ def test_sets_make_keep_lists_unique(self): there_can_only_be_only_one = set(highlanders) - self.assertEqual(__, there_can_only_be_only_one) + self.assertEqual(set(['Ramirez', 'Matunas', 'MacLeod', 'Malcolm']), there_can_only_be_only_one) def test_sets_are_unordered(self): - self.assertEqual(set([__, __, __, __, __]), set('12345')) + self.assertEqual(set(['1', '2', '3','4', '5']), set('12345')) def test_convert_the_set_into_a_list_to_sort_it(self): - self.assertEqual(__, sorted(set('13245'))) + self.assertEqual(['1','2','3','4','5'], sorted(set('13245'))) # ------------------------------------------------------------------ @@ -25,19 +25,19 @@ def test_set_have_arithmetic_operators(self): scotsmen = set(['MacLeod', 'Wallace', 'Willie']) warriors = set(['MacLeod', 'Wallace', 'Leonidas']) - self.assertEqual(__, scotsmen - warriors) - self.assertEqual(__, scotsmen | warriors) - self.assertEqual(__, scotsmen & warriors) - self.assertEqual(__, scotsmen ^ warriors) + self.assertEqual(set(['Willie']), scotsmen - warriors) + self.assertEqual(set(['MacLeod', 'Wallace', 'Willie', 'Leonidas']), scotsmen | warriors) + self.assertEqual(set(['MacLeod', 'Wallace']), scotsmen & warriors) + self.assertEqual(set(['Willie', 'Leonidas']), scotsmen ^ warriors) # ------------------------------------------------------------------ def test_we_can_query_set_membership(self): - self.assertEqual(__, 127 in set([127, 0, 0, 1])) - self.assertEqual(__, 'cow' not in set('apocalypse now')) + self.assertEqual(True, 127 in set([127, 0, 0, 1])) + self.assertEqual(True, 'cow' not in set('apocalypse now')) def test_we_can_compare_subsets(self): - self.assertEqual(__, set('cake') <= set('cherry cake')) - self.assertEqual(__, set('cake').issubset(set('cherry cake'))) + self.assertEqual(True, set('cake') <= set('cherry cake')) + self.assertEqual(True, set('cake').issubset(set('cherry cake'))) - self.assertEqual(__, set('cake') > set('pie')) + self.assertEqual(False, set('cake') > set('pie')) diff --git a/python2/koans/about_string_manipulation.py b/python2/koans/about_string_manipulation.py index c395309cc..22dcacd7d 100644 --- a/python2/koans/about_string_manipulation.py +++ b/python2/koans/about_string_manipulation.py @@ -10,13 +10,13 @@ def test_use_format_to_interpolate_variables(self): value1 = 'one' value2 = 2 string = "The values are {0} and {1}".format(value1, value2) - self.assertEqual(__, string) + self.assertEqual('The values are one and 2', string) def test_formatted_values_can_be_shown_in_any_order_or_be_repeated(self): value1 = 'doh' value2 = 'DOH' string = "The values are {1}, {0}, {0} and {1}!".format(value1, value2) - self.assertEqual(__, string) + self.assertEqual('The values are DOH, doh, doh and DOH!', string) def test_any_python_expression_may_be_interpolated(self): import math # import a standard python module with math functions @@ -24,24 +24,24 @@ def test_any_python_expression_may_be_interpolated(self): decimal_places = 4 string = "The square root of 5 is {0:.{1}f}".format(math.sqrt(5), \ decimal_places) - self.assertEqual(__, string) + self.assertEqual('The square root of 5 is 2.2361', string) def test_you_can_get_a_substring_from_a_string(self): string = "Bacon, lettuce and tomato" - self.assertEqual(__, string[7:10]) + self.assertEqual('let', string[7:10]) def test_you_can_get_a_single_character_from_a_string(self): string = "Bacon, lettuce and tomato" - self.assertEqual(__, string[1]) + self.assertEqual('a', string[1]) def test_single_characters_can_be_represented_by_integers(self): - self.assertEqual(__, ord('a')) - self.assertEqual(__, ord('b') == (ord('a') + 1)) + self.assertEqual(97, ord('a')) + self.assertEqual(True, ord('b') == (ord('a') + 1)) def test_strings_can_be_split(self): string = "Sausage Egg Cheese" words = string.split() - self.assertEqual([__, __, __], words) + self.assertEqual(['Sausage', 'Egg', 'Cheese'], words) def test_strings_can_be_split_with_different_patterns(self): import re # import python regular expression library @@ -51,7 +51,7 @@ def test_strings_can_be_split_with_different_patterns(self): words = pattern.split(string) - self.assertEqual([__, __, __, __], words) + self.assertEqual(['the', 'rain', 'in', 'spain'], words) # `pattern` is a Python regular expression pattern which matches # ',' or ';' @@ -59,18 +59,18 @@ def test_strings_can_be_split_with_different_patterns(self): def test_raw_strings_do_not_interpret_escape_characters(self): string = r'\n' self.assertNotEqual('\n', string) - self.assertEqual(__, string) - self.assertEqual(__, len(string)) + self.assertEqual(r'\n', string) + self.assertEqual(2, len(string)) # Useful in regular expressions, file paths, URLs, etc. def test_strings_can_be_joined(self): words = ["Now", "is", "the", "time"] - self.assertEqual(__, ' '.join(words)) + self.assertEqual('Now is the time', ' '.join(words)) def test_strings_can_change_case(self): - self.assertEqual(__, 'guido'.capitalize()) - self.assertEqual(__, 'guido'.upper()) - self.assertEqual(__, 'TimBot'.lower()) - self.assertEqual(__, 'guido van rossum'.title()) - self.assertEqual(__, 'ToTaLlY aWeSoMe'.swapcase()) + self.assertEqual('Guido', 'guido'.capitalize()) + self.assertEqual("GUIDO", 'guido'.upper()) + self.assertEqual('timbot', 'TimBot'.lower()) + self.assertEqual('Guido Van Rossum', 'guido van rossum'.title()) + self.assertEqual('tOtAlLy AwEsOmE', 'ToTaLlY aWeSoMe'.swapcase()) diff --git a/python2/koans/about_strings.py b/python2/koans/about_strings.py index abfcf5981..1e7301639 100644 --- a/python2/koans/about_strings.py +++ b/python2/koans/about_strings.py @@ -8,88 +8,88 @@ class AboutStrings(Koan): def test_double_quoted_strings_are_strings(self): string = "Hello, world." - self.assertEqual(__, isinstance(string, basestring)) + self.assertEqual(True, isinstance(string, basestring)) def test_single_quoted_strings_are_also_strings(self): string = 'Goodbye, world.' - self.assertEqual(__, isinstance(string, basestring)) + self.assertEqual(True, isinstance(string, basestring)) def test_triple_quote_strings_are_also_strings(self): string = """Howdy, world!""" - self.assertEqual(__, isinstance(string, basestring)) + self.assertEqual(True, isinstance(string, basestring)) def test_triple_single_quotes_work_too(self): string = '''Bonjour tout le monde!''' - self.assertEqual(__, isinstance(string, basestring)) + self.assertEqual(True, isinstance(string, basestring)) def test_raw_strings_are_also_strings(self): string = r"Konnichi wa, world!" - self.assertEqual(__, isinstance(string, basestring)) + self.assertEqual(True, isinstance(string, basestring)) def test_use_single_quotes_to_create_string_with_double_quotes(self): string = 'He said, "Go Away."' - self.assertEqual(__, string) + self.assertEqual(True, isinstance(string, basestring)) def test_use_double_quotes_to_create_strings_with_single_quotes(self): string = "Don't" - self.assertEqual(__, string) + self.assertEqual('Don\'t', string) def test_use_backslash_for_escaping_quotes_in_strings(self): a = "He said, \"Don't\"" b = 'He said, "Don\'t"' - self.assertEqual(__, (a == b)) + self.assertEqual(True, (a == b)) def test_use_backslash_at_the_end_of_a_line_to_continue_onto_the_next_line(self): string = "It was the best of times,\n\ It was the worst of times." - self.assertEqual(__, len(string)) + self.assertEqual(52, len(string)) def test_triple_quoted_strings_can_span_lines(self): string = """ Howdy, world! """ - self.assertEqual(__, len(string)) + self.assertEqual(15, len(string)) def test_triple_quoted_strings_need_less_escaping(self): a = "Hello \"world\"." b = """Hello "world".""" - self.assertEqual(__, (a == b)) + self.assertEqual(True, (a == b)) def test_escaping_quotes_at_the_end_of_triple_quoted_string(self): string = """Hello "world\"""" - self.assertEqual(__, string) + self.assertEqual('Hello "world"', string) def test_plus_concatenates_strings(self): string = "Hello, " + "world" - self.assertEqual(__, string) + self.assertEqual("Hello, world", string) def test_adjacent_strings_are_concatenated_automatically(self): string = "Hello" ", " "world" - self.assertEqual(__, string) + self.assertEqual('Hello, world', string) def test_plus_will_not_modify_original_strings(self): hi = "Hello, " there = "world" string = hi + there - self.assertEqual(__, hi) - self.assertEqual(__, there) + self.assertEqual('Hello, ', hi) + self.assertEqual('world', there) def test_plus_equals_will_append_to_end_of_string(self): hi = "Hello, " there = "world" hi += there - self.assertEqual(__, hi) + self.assertEqual('Hello, world', hi) def test_plus_equals_also_leaves_original_string_unmodified(self): original = "Hello, " hi = original there = "world" hi += there - self.assertEqual(__, original) + self.assertEqual('Hello, ', original) def test_most_strings_interpret_escape_characters(self): string = "\n" self.assertEqual('\n', string) self.assertEqual("""\n""", string) - self.assertEqual(__, len(string)) + self.assertEqual(1, len(string)) diff --git a/python2/koans/about_triangle_project2.py b/python2/koans/about_triangle_project2.py index 6b6184657..09c783f20 100644 --- a/python2/koans/about_triangle_project2.py +++ b/python2/koans/about_triangle_project2.py @@ -12,8 +12,11 @@ class AboutTriangleProject2(Koan): # Let's handle that part now. def test_illegal_triangles_throw_exceptions(self): # Calls triangle(0, 0, 0) - self.assertRaises(TriangleError, triangle, 0, 0, 0) + try: + self.assertRaises(TriangleError, triangle, 0, 0, 0) - self.assertRaises(TriangleError, triangle, 3, 4, -5) - self.assertRaises(TriangleError, triangle, 1, 1, 3) - self.assertRaises(TriangleError, triangle, 2, 4, 2) + self.assertRaises(TriangleError, triangle, 3, 4, -5) + self.assertRaises(TriangleError, triangle, 1, 1, 3) + self.assertRaises(TriangleError, triangle, 2, 4, 2) + except TriangleError as ex: + print TriangleError[0] diff --git a/python2/koans/about_true_and_false.py b/python2/koans/about_true_and_false.py index 51a6b537f..b46dd82d4 100644 --- a/python2/koans/about_true_and_false.py +++ b/python2/koans/about_true_and_false.py @@ -12,31 +12,30 @@ def truth_value(self, condition): return 'false stuff' def test_true_is_treated_as_true(self): - self.assertEqual(__, self.truth_value(True)) + self.assertEqual('true stuff', self.truth_value(True)) def test_false_is_treated_as_false(self): - self.assertEqual(__, self.truth_value(False)) + self.assertEqual('false stuff', self.truth_value(False)) def test_none_is_treated_as_false(self): - self.assertEqual(__, self.truth_value(None)) + self.assertEqual('false stuff', self.truth_value(None)) def test_zero_is_treated_as_false(self): - self.assertEqual(__, self.truth_value(0)) + self.assertEqual('false stuff', self.truth_value(0)) def test_empty_collections_are_treated_as_false(self): - self.assertEqual(__, self.truth_value([])) - self.assertEqual(__, self.truth_value(())) - self.assertEqual(__, self.truth_value({})) - self.assertEqual(__, self.truth_value(set())) + self.assertEqual('false stuff', self.truth_value([])) + self.assertEqual('false stuff', self.truth_value(())) + self.assertEqual('false stuff', self.truth_value({})) + self.assertEqual('false stuff', self.truth_value(set())) def test_blank_strings_are_treated_as_false(self): - self.assertEqual(__, self.truth_value("")) + self.assertEqual('false stuff', self.truth_value("")) def test_everything_else_is_treated_as_true(self): - self.assertEqual(__, self.truth_value(1)) - self.assertEqual(__, self.truth_value(1,)) + self.assertEqual('true stuff', self.truth_value(1)) + self.assertEqual('true stuff', self.truth_value(1,)) self.assertEqual( - __, + 'true stuff', self.truth_value("Python is named after Monty Python")) - self.assertEqual(__, self.truth_value(' ')) - self.assertEqual(__, self.truth_value('0')) + self.assertEqual('true stuff', self.truth_value(' ')) diff --git a/python2/koans/about_tuples.py b/python2/koans/about_tuples.py index 84ba5d552..5727eed6b 100644 --- a/python2/koans/about_tuples.py +++ b/python2/koans/about_tuples.py @@ -7,14 +7,14 @@ class AboutTuples(Koan): def test_creating_a_tuple(self): count_of_three = (1, 2, 5) - self.assertEqual(__, count_of_three[2]) + self.assertEqual(5, count_of_three[2]) def test_tuples_are_immutable_so_item_assignment_is_not_possible(self): count_of_three = (1, 2, 5) try: count_of_three[2] = "three" except TypeError as ex: - self.assertMatch(__, ex[0]) + self.assertMatch("'tuple' object does not support item assignment", ex[0]) def test_tuples_are_immutable_so_appending_is_not_possible(self): count_of_three = (1, 2, 5) @@ -25,7 +25,7 @@ def test_tuples_are_immutable_so_appending_is_not_possible(self): # Note, assertMatch() uses regular expression pattern matching, # so you don't have to copy the whole message. - self.assertMatch(__, ex[0]) + self.assertMatch("'tuple' object has no attribute 'append'", ex[0]) # Tuples are less flexible than lists, but faster. @@ -36,25 +36,25 @@ def test_tuples_can_only_be_changed_through_replacement(self): list_count.append("boom") count_of_three = tuple(list_count) - self.assertEqual(__, count_of_three) + self.assertEqual((1, 2, 5, 'boom'), count_of_three) def test_tuples_of_one_look_peculiar(self): - self.assertEqual(__, (1).__class__) - self.assertEqual(__, (1,).__class__) - self.assertEqual(__, ("Hello comma!", )) + self.assertEqual(int, (1).__class__) + self.assertEqual(tuple, (1,).__class__) + self.assertEqual(('Hello comma!',), ("Hello comma!", )) def test_tuple_constructor_can_be_surprising(self): - self.assertEqual(__, tuple("Surprise!")) + self.assertEqual(('S', 'u', 'r', 'p', 'r', 'i', 's', 'e', '!'), tuple("Surprise!")) def test_creating_empty_tuples(self): - self.assertEqual(__, ()) - self.assertEqual(__, tuple()) # Sometimes less confusing + self.assertEqual((), ()) + self.assertEqual((), tuple()) # Sometimes less confusing def test_tuples_can_be_embedded(self): lat = (37, 14, 6, 'N') lon = (115, 48, 40, 'W') place = ('Area 51', lat, lon) - self.assertEqual(__, place) + self.assertEqual(('Area 51', (37, 14, 6, 'N'), (115, 48, 40, 'W')), place) def test_tuples_are_good_for_representing_records(self): locations = [ @@ -66,5 +66,5 @@ def test_tuples_are_good_for_representing_records(self): ("Cthulhu", (26, 40, 1, 'N'), (70, 45, 7, 'W')) ) - self.assertEqual(__, locations[2][0]) - self.assertEqual(__, locations[0][1][2]) + self.assertEqual('Cthulhu', locations[2][0]) + self.assertEqual(15.56, locations[0][1][2]) diff --git a/python2/koans/about_with_statements.py b/python2/koans/about_with_statements.py index 15cfbaf69..e83539e57 100644 --- a/python2/koans/about_with_statements.py +++ b/python2/koans/about_with_statements.py @@ -26,7 +26,7 @@ def count_lines(self, file_name): self.fail() def test_counting_lines(self): - self.assertEqual(__, self.count_lines("example_file.txt")) + self.assertEqual(4, self.count_lines("example_file.txt")) # ------------------------------------------------------------------ @@ -45,7 +45,7 @@ def find_line(self, file_name): self.fail() def test_finding_lines(self): - self.assertEqual(__, self.find_line("example_file.txt")) + self.assertEqual('test\n', self.find_line("example_file.txt")) ## ------------------------------------------------------------------ ## THINK ABOUT IT: @@ -92,16 +92,20 @@ def count_lines2(self, file_name): return count def test_counting_lines2(self): - self.assertEqual(__, self.count_lines2("example_file.txt")) + self.assertEqual(4, self.count_lines2("example_file.txt")) # ------------------------------------------------------------------ def find_line2(self, file_name): - # Rewrite find_line using the Context Manager. - pass + with self.FileContextManager(file_name) as f: + for line in f.readlines(): + match = re.search('e', line) + if match: + return line + def test_finding_lines2(self): - self.assertEqual(__, self.find_line2("example_file.txt")) + self.assertEqual('test\n', self.find_line2("example_file.txt")) self.assertNotEqual(None, self.find_line2("example_file.txt")) # ------------------------------------------------------------------ @@ -114,4 +118,4 @@ def count_lines3(self, file_name): return count def test_open_already_has_its_own_built_in_context_manager(self): - self.assertEqual(__, self.count_lines3("example_file.txt")) + self.assertEqual(4, self.count_lines3("example_file.txt")) diff --git a/python2/koans/triangle.py b/python2/koans/triangle.py index 8f3faeed3..ef433101d 100644 --- a/python2/koans/triangle.py +++ b/python2/koans/triangle.py @@ -18,8 +18,17 @@ # about_triangle_project_2.py # def triangle(a, b, c): - # DELETE 'PASS' AND WRITE THIS CODE - pass + if min([a,b,c]) <= 0: + raise TriangleError + x, y, z = sorted([a,b,c]) + if (x + y) <= z: + raise TriangleError + elif a == b == c: + return 'equilateral' + elif a == b or a == c or b == c: + return 'isosceles' + else: + return 'scalene' # Error class used in part 2. No need to change this code. diff --git a/python2/libs/colorama/__init__.py b/python2/libs/colorama/__init__.py index 2d127fa8e..331174e57 100644 --- a/python2/libs/colorama/__init__.py +++ b/python2/libs/colorama/__init__.py @@ -1,7 +1,6 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. -from .initialise import init, deinit, reinit +from .initialise import init from .ansi import Fore, Back, Style from .ansitowin32 import AnsiToWin32 -VERSION = '0.2.7' +VERSION = '0.1.18' diff --git a/python2/libs/colorama/ansi.py b/python2/libs/colorama/ansi.py index 5dfe374ce..7b818e19e 100644 --- a/python2/libs/colorama/ansi.py +++ b/python2/libs/colorama/ansi.py @@ -1,4 +1,3 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. ''' This module generates ANSI character codes to printing colors to terminals. See: http://en.wikipedia.org/wiki/ANSI_escape_code diff --git a/python2/libs/colorama/ansitowin32.py b/python2/libs/colorama/ansitowin32.py index ea0a6c15f..5c39a480e 100644 --- a/python2/libs/colorama/ansitowin32.py +++ b/python2/libs/colorama/ansitowin32.py @@ -1,4 +1,4 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. + import re import sys @@ -123,7 +123,7 @@ def write(self, text): def reset_all(self): if self.convert: self.call_win32('m', (0,)) - elif is_a_tty(self.wrapped): + else: self.wrapped.write(Style.RESET_ALL) @@ -173,17 +173,4 @@ def call_win32(self, command, params): args = func_args[1:] kwargs = dict(on_stderr=self.on_stderr) func(*args, **kwargs) - elif command in ('H', 'f'): # set cursor position - func = winterm.set_cursor_position - func(params, on_stderr=self.on_stderr) - elif command in ('J'): - func = winterm.erase_data - func(params, on_stderr=self.on_stderr) - elif command == 'A': - if params == () or params == None: - num_rows = 1 - else: - num_rows = params[0] - func = winterm.cursor_up - func(num_rows, on_stderr=self.on_stderr) diff --git a/python2/libs/colorama/initialise.py b/python2/libs/colorama/initialise.py index cba3676dd..eca2bea40 100644 --- a/python2/libs/colorama/initialise.py +++ b/python2/libs/colorama/initialise.py @@ -1,4 +1,3 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. import atexit import sys @@ -8,9 +7,6 @@ orig_stdout = sys.stdout orig_stderr = sys.stderr -wrapped_stdout = sys.stdout -wrapped_stderr = sys.stderr - atexit_done = False @@ -20,14 +16,11 @@ def reset_all(): def init(autoreset=False, convert=None, strip=None, wrap=True): - if not wrap and any([autoreset, convert, strip]): + if wrap==False and (autoreset==True or convert==True or strip==True): raise ValueError('wrap=False conflicts with any other arg=True') - global wrapped_stdout, wrapped_stderr - sys.stdout = wrapped_stdout = \ - wrap_stream(orig_stdout, convert, strip, autoreset, wrap) - sys.stderr = wrapped_stderr = \ - wrap_stream(orig_stderr, convert, strip, autoreset, wrap) + sys.stdout = wrap_stream(orig_stdout, convert, strip, autoreset, wrap) + sys.stderr = wrap_stream(orig_stderr, convert, strip, autoreset, wrap) global atexit_done if not atexit_done: @@ -35,16 +28,6 @@ def init(autoreset=False, convert=None, strip=None, wrap=True): atexit_done = True -def deinit(): - sys.stdout = orig_stdout - sys.stderr = orig_stderr - - -def reinit(): - sys.stdout = wrapped_stdout - sys.stderr = wrapped_stdout - - def wrap_stream(stream, convert, strip, autoreset, wrap): if wrap: wrapper = AnsiToWin32(stream, @@ -53,4 +36,3 @@ def wrap_stream(stream, convert, strip, autoreset, wrap): stream = wrapper.stream return stream - diff --git a/python2/libs/colorama/win32.py b/python2/libs/colorama/win32.py index f4024f95e..5f49e6cba 100644 --- a/python2/libs/colorama/win32.py +++ b/python2/libs/colorama/win32.py @@ -1,4 +1,3 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. # from winbase.h STDOUT = -11 @@ -6,129 +5,91 @@ try: from ctypes import windll - from ctypes import wintypes except ImportError: windll = None SetConsoleTextAttribute = lambda *_: None else: from ctypes import ( - byref, Structure, c_char, c_short, c_uint32, c_ushort, POINTER + byref, Structure, c_char, c_short, c_uint32, c_ushort ) - class CONSOLE_SCREEN_BUFFER_INFO(Structure): - """struct in wincon.h.""" - _fields_ = [ - ("dwSize", wintypes._COORD), - ("dwCursorPosition", wintypes._COORD), - ("wAttributes", wintypes.WORD), - ("srWindow", wintypes.SMALL_RECT), - ("dwMaximumWindowSize", wintypes._COORD), - ] - def __str__(self): - return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % ( - self.dwSize.Y, self.dwSize.X - , self.dwCursorPosition.Y, self.dwCursorPosition.X - , self.wAttributes - , self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right - , self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X - ) - - _GetStdHandle = windll.kernel32.GetStdHandle - _GetStdHandle.argtypes = [ - wintypes.DWORD, - ] - _GetStdHandle.restype = wintypes.HANDLE - - _GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo - _GetConsoleScreenBufferInfo.argtypes = [ - wintypes.HANDLE, - POINTER(CONSOLE_SCREEN_BUFFER_INFO), - ] - _GetConsoleScreenBufferInfo.restype = wintypes.BOOL - - _SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute - _SetConsoleTextAttribute.argtypes = [ - wintypes.HANDLE, - wintypes.WORD, - ] - _SetConsoleTextAttribute.restype = wintypes.BOOL + handles = { + STDOUT: windll.kernel32.GetStdHandle(STDOUT), + STDERR: windll.kernel32.GetStdHandle(STDERR), + } - _SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition - _SetConsoleCursorPosition.argtypes = [ - wintypes.HANDLE, - wintypes._COORD, - ] - _SetConsoleCursorPosition.restype = wintypes.BOOL + SHORT = c_short + WORD = c_ushort + DWORD = c_uint32 + TCHAR = c_char - _FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA - _FillConsoleOutputCharacterA.argtypes = [ - wintypes.HANDLE, - c_char, - wintypes.DWORD, - wintypes._COORD, - POINTER(wintypes.DWORD), - ] - _FillConsoleOutputCharacterA.restype = wintypes.BOOL + class COORD(Structure): + """struct in wincon.h""" + _fields_ = [ + ('X', SHORT), + ('Y', SHORT), + ] - _FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute - _FillConsoleOutputAttribute.argtypes = [ - wintypes.HANDLE, - wintypes.WORD, - wintypes.DWORD, - wintypes._COORD, - POINTER(wintypes.DWORD), - ] - _FillConsoleOutputAttribute.restype = wintypes.BOOL + class SMALL_RECT(Structure): + """struct in wincon.h.""" + _fields_ = [ + ("Left", SHORT), + ("Top", SHORT), + ("Right", SHORT), + ("Bottom", SHORT), + ] - handles = { - STDOUT: _GetStdHandle(STDOUT), - STDERR: _GetStdHandle(STDERR), - } + class CONSOLE_SCREEN_BUFFER_INFO(Structure): + """struct in wincon.h.""" + _fields_ = [ + ("dwSize", COORD), + ("dwCursorPosition", COORD), + ("wAttributes", WORD), + ("srWindow", SMALL_RECT), + ("dwMaximumWindowSize", COORD), + ] - def GetConsoleScreenBufferInfo(stream_id=STDOUT): + def GetConsoleScreenBufferInfo(stream_id): handle = handles[stream_id] csbi = CONSOLE_SCREEN_BUFFER_INFO() - success = _GetConsoleScreenBufferInfo( + success = windll.kernel32.GetConsoleScreenBufferInfo( handle, byref(csbi)) + # This fails when imported via setup.py when installing using 'pip' + # presumably the fix is that running setup.py should not trigger all + # this activity. + # assert success return csbi def SetConsoleTextAttribute(stream_id, attrs): handle = handles[stream_id] - return _SetConsoleTextAttribute(handle, attrs) + success = windll.kernel32.SetConsoleTextAttribute(handle, attrs) + assert success def SetConsoleCursorPosition(stream_id, position): - position = wintypes._COORD(*position) - # If the position is out of range, do nothing. - if position.Y <= 0 or position.X <= 0: - return - # Adjust for Windows' SetConsoleCursorPosition: - # 1. being 0-based, while ANSI is 1-based. - # 2. expecting (x,y), while ANSI uses (y,x). - adjusted_position = wintypes._COORD(position.Y - 1, position.X - 1) - # Adjust for viewport's scroll position - sr = GetConsoleScreenBufferInfo(STDOUT).srWindow - adjusted_position.Y += sr.Top - adjusted_position.X += sr.Left - # Resume normal processing handle = handles[stream_id] - return _SetConsoleCursorPosition(handle, adjusted_position) + position = COORD(*position) + success = windll.kernel32.SetConsoleCursorPosition(handle, position) + assert success def FillConsoleOutputCharacter(stream_id, char, length, start): handle = handles[stream_id] - char = c_char(char) - length = wintypes.DWORD(length) - num_written = wintypes.DWORD(0) - # Note that this is hard-coded for ANSI (vs wide) bytes. - success = _FillConsoleOutputCharacterA( + char = TCHAR(char) + length = DWORD(length) + start = COORD(*start) + num_written = DWORD(0) + # AttributeError: function 'FillConsoleOutputCharacter' not found + # could it just be that my types are wrong? + success = windll.kernel32.FillConsoleOutputCharacter( handle, char, length, start, byref(num_written)) + assert success return num_written.value - def FillConsoleOutputAttribute(stream_id, attr, length, start): - ''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )''' - handle = handles[stream_id] - attribute = wintypes.WORD(attr) - length = wintypes.DWORD(length) - num_written = wintypes.DWORD(0) - # Note that this is hard-coded for ANSI (vs wide) bytes. - return _FillConsoleOutputAttribute( - handle, attribute, length, start, byref(num_written)) + +if __name__=='__main__': + x = GetConsoleScreenBufferInfo(STDOUT) + print(x.dwSize) + print(x.dwCursorPosition) + print(x.wAttributes) + print(x.srWindow) + print(x.dwMaximumWindowSize) + diff --git a/python2/libs/colorama/winterm.py b/python2/libs/colorama/winterm.py index 270881154..63f4469cc 100644 --- a/python2/libs/colorama/winterm.py +++ b/python2/libs/colorama/winterm.py @@ -1,4 +1,4 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. + from . import win32 @@ -22,7 +22,8 @@ class WinStyle(object): class WinTerm(object): def __init__(self): - self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes + self._default = \ + win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes self.set_attrs(self._default) self._default_fore = self._fore self._default_back = self._back @@ -66,55 +67,3 @@ def set_console(self, attrs=None, on_stderr=False): handle = win32.STDERR win32.SetConsoleTextAttribute(handle, attrs) - def get_position(self, handle): - position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition - # Because Windows coordinates are 0-based, - # and win32.SetConsoleCursorPosition expects 1-based. - position.X += 1 - position.Y += 1 - return position - - def set_cursor_position(self, position=None, on_stderr=False): - if position is None: - #I'm not currently tracking the position, so there is no default. - #position = self.get_position() - return - handle = win32.STDOUT - if on_stderr: - handle = win32.STDERR - win32.SetConsoleCursorPosition(handle, position) - - def cursor_up(self, num_rows=0, on_stderr=False): - if num_rows == 0: - return - handle = win32.STDOUT - if on_stderr: - handle = win32.STDERR - position = self.get_position(handle) - adjusted_position = (position.Y - num_rows, position.X) - self.set_cursor_position(adjusted_position, on_stderr) - - def erase_data(self, mode=0, on_stderr=False): - # 0 (or None) should clear from the cursor to the end of the screen. - # 1 should clear from the cursor to the beginning of the screen. - # 2 should clear the entire screen. (And maybe move cursor to (1,1)?) - # - # At the moment, I only support mode 2. From looking at the API, it - # should be possible to calculate a different number of bytes to clear, - # and to do so relative to the cursor position. - if mode[0] not in (2,): - return - handle = win32.STDOUT - if on_stderr: - handle = win32.STDERR - # here's where we'll home the cursor - coord_screen = win32.COORD(0,0) - csbi = win32.GetConsoleScreenBufferInfo(handle) - # get the number of character cells in the current buffer - dw_con_size = csbi.dwSize.X * csbi.dwSize.Y - # fill the entire screen with blanks - win32.FillConsoleOutputCharacter(handle, ' ', dw_con_size, coord_screen) - # now set the buffer's attributes accordingly - win32.FillConsoleOutputAttribute(handle, self.get_attrs(), dw_con_size, coord_screen ); - # put the cursor at (0, 0) - win32.SetConsoleCursorPosition(handle, (coord_screen.X, coord_screen.Y)) diff --git a/python2/runner/path_to_enlightenment.py b/python2/runner/path_to_enlightenment.py index 21758bcec..a81faa4d4 100644 --- a/python2/runner/path_to_enlightenment.py +++ b/python2/runner/path_to_enlightenment.py @@ -88,6 +88,5 @@ def koans(): suite.addTests(loader.loadTestsFromTestCase(AboutProxyObjectProject)) suite.addTests(loader.loadTestsFromTestCase(TelevisionTest)) suite.addTests(loader.loadTestsFromTestCase(AboutExtraCredit)) - suite.addTests(loader.loadTestsFromTestCase(AboutRegex)) return suite diff --git a/python3/contemplate_koans.py b/python3/contemplate_koans.py index b7d35d4b3..81c1502bc 100644 --- a/python3/contemplate_koans.py +++ b/python3/contemplate_koans.py @@ -10,25 +10,26 @@ # So thanks guys! # +import unittest import sys if __name__ == '__main__': if sys.version_info < (3, 0): print("\nThis is the Python 3 version of Python Koans, but you are " + - "running it with Python 2!\n\n" - "Did you accidentally use the wrong python script? \nTry:\n\n" + - " python3 contemplate_koans.py\n") + "running it with Python 2!\n\n" + "Did you accidentally use the wrong python script? \nTry:\n\n" + + " python3 contemplate_koans.py\n") else: if sys.version_info < (3, 3): print("\n" + - "********************************************************\n" + - "WARNING:\n" + - "This version of Python Koans was designed for " + - "Python 3.3 or greater.\n" + - "Your version of Python is older, so you may run into " + - "problems!\n\n" + - "But lets see how far we get...\n" + - "********************************************************\n") + "********************************************************\n" + + "WARNING:\n" + + "This version of Python Koans was designed for " + + "Python 3.3 or greater.\n" + + "Your version of Python is older, so you may run into " + + "problems!\n\n" + + "But lets see how far we get...\n" + + "********************************************************\n") from runner.mountain import Mountain diff --git a/python3/koans/about_classes.py b/python3/koans/about_classes.py index f3ed7eeb1..c2f6867a5 100644 --- a/python3/koans/about_classes.py +++ b/python3/koans/about_classes.py @@ -115,7 +115,7 @@ def test_args_must_match_init(self): # THINK ABOUT IT: # Why is this so? - def test_different_objects_have_different_instance_variables(self): + def test_different_objects_have_difference_instance_variables(self): fido = self.Dog5("Fido") rover = self.Dog5("Rover") diff --git a/python3/koans/about_true_and_false.py b/python3/koans/about_true_and_false.py index 4aa021a4c..c6585567f 100644 --- a/python3/koans/about_true_and_false.py +++ b/python3/koans/about_true_and_false.py @@ -36,4 +36,3 @@ def test_everything_else_is_treated_as_true(self): self.assertEqual(__, self.truth_value(1,)) self.assertEqual(__, self.truth_value("Python is named after Monty Python")) self.assertEqual(__, self.truth_value(' ')) - self.assertEqual(__, self.truth_value('0')) diff --git a/python3/koans/about_tuples.py b/python3/koans/about_tuples.py index 76c193395..9833c40c6 100644 --- a/python3/koans/about_tuples.py +++ b/python3/koans/about_tuples.py @@ -6,7 +6,7 @@ class AboutTuples(Koan): def test_creating_a_tuple(self): count_of_three = (1, 2, 5) - self.assertEqual(__, count_of_three[2]) + self.assertEqual(5, __) def test_tuples_are_immutable_so_item_assignment_is_not_possible(self): count_of_three = (1, 2, 5) diff --git a/python3/libs/colorama/__init__.py b/python3/libs/colorama/__init__.py index 2d127fa8e..331174e57 100644 --- a/python3/libs/colorama/__init__.py +++ b/python3/libs/colorama/__init__.py @@ -1,7 +1,6 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. -from .initialise import init, deinit, reinit +from .initialise import init from .ansi import Fore, Back, Style from .ansitowin32 import AnsiToWin32 -VERSION = '0.2.7' +VERSION = '0.1.18' diff --git a/python3/libs/colorama/ansi.py b/python3/libs/colorama/ansi.py index 5dfe374ce..7b818e19e 100644 --- a/python3/libs/colorama/ansi.py +++ b/python3/libs/colorama/ansi.py @@ -1,4 +1,3 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. ''' This module generates ANSI character codes to printing colors to terminals. See: http://en.wikipedia.org/wiki/ANSI_escape_code diff --git a/python3/libs/colorama/ansitowin32.py b/python3/libs/colorama/ansitowin32.py index ea0a6c15f..5c39a480e 100644 --- a/python3/libs/colorama/ansitowin32.py +++ b/python3/libs/colorama/ansitowin32.py @@ -1,4 +1,4 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. + import re import sys @@ -123,7 +123,7 @@ def write(self, text): def reset_all(self): if self.convert: self.call_win32('m', (0,)) - elif is_a_tty(self.wrapped): + else: self.wrapped.write(Style.RESET_ALL) @@ -173,17 +173,4 @@ def call_win32(self, command, params): args = func_args[1:] kwargs = dict(on_stderr=self.on_stderr) func(*args, **kwargs) - elif command in ('H', 'f'): # set cursor position - func = winterm.set_cursor_position - func(params, on_stderr=self.on_stderr) - elif command in ('J'): - func = winterm.erase_data - func(params, on_stderr=self.on_stderr) - elif command == 'A': - if params == () or params == None: - num_rows = 1 - else: - num_rows = params[0] - func = winterm.cursor_up - func(num_rows, on_stderr=self.on_stderr) diff --git a/python3/libs/colorama/initialise.py b/python3/libs/colorama/initialise.py index cba3676dd..eca2bea40 100644 --- a/python3/libs/colorama/initialise.py +++ b/python3/libs/colorama/initialise.py @@ -1,4 +1,3 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. import atexit import sys @@ -8,9 +7,6 @@ orig_stdout = sys.stdout orig_stderr = sys.stderr -wrapped_stdout = sys.stdout -wrapped_stderr = sys.stderr - atexit_done = False @@ -20,14 +16,11 @@ def reset_all(): def init(autoreset=False, convert=None, strip=None, wrap=True): - if not wrap and any([autoreset, convert, strip]): + if wrap==False and (autoreset==True or convert==True or strip==True): raise ValueError('wrap=False conflicts with any other arg=True') - global wrapped_stdout, wrapped_stderr - sys.stdout = wrapped_stdout = \ - wrap_stream(orig_stdout, convert, strip, autoreset, wrap) - sys.stderr = wrapped_stderr = \ - wrap_stream(orig_stderr, convert, strip, autoreset, wrap) + sys.stdout = wrap_stream(orig_stdout, convert, strip, autoreset, wrap) + sys.stderr = wrap_stream(orig_stderr, convert, strip, autoreset, wrap) global atexit_done if not atexit_done: @@ -35,16 +28,6 @@ def init(autoreset=False, convert=None, strip=None, wrap=True): atexit_done = True -def deinit(): - sys.stdout = orig_stdout - sys.stderr = orig_stderr - - -def reinit(): - sys.stdout = wrapped_stdout - sys.stderr = wrapped_stdout - - def wrap_stream(stream, convert, strip, autoreset, wrap): if wrap: wrapper = AnsiToWin32(stream, @@ -53,4 +36,3 @@ def wrap_stream(stream, convert, strip, autoreset, wrap): stream = wrapper.stream return stream - diff --git a/python3/libs/colorama/win32.py b/python3/libs/colorama/win32.py index f4024f95e..5f49e6cba 100644 --- a/python3/libs/colorama/win32.py +++ b/python3/libs/colorama/win32.py @@ -1,4 +1,3 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. # from winbase.h STDOUT = -11 @@ -6,129 +5,91 @@ try: from ctypes import windll - from ctypes import wintypes except ImportError: windll = None SetConsoleTextAttribute = lambda *_: None else: from ctypes import ( - byref, Structure, c_char, c_short, c_uint32, c_ushort, POINTER + byref, Structure, c_char, c_short, c_uint32, c_ushort ) - class CONSOLE_SCREEN_BUFFER_INFO(Structure): - """struct in wincon.h.""" - _fields_ = [ - ("dwSize", wintypes._COORD), - ("dwCursorPosition", wintypes._COORD), - ("wAttributes", wintypes.WORD), - ("srWindow", wintypes.SMALL_RECT), - ("dwMaximumWindowSize", wintypes._COORD), - ] - def __str__(self): - return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % ( - self.dwSize.Y, self.dwSize.X - , self.dwCursorPosition.Y, self.dwCursorPosition.X - , self.wAttributes - , self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right - , self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X - ) - - _GetStdHandle = windll.kernel32.GetStdHandle - _GetStdHandle.argtypes = [ - wintypes.DWORD, - ] - _GetStdHandle.restype = wintypes.HANDLE - - _GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo - _GetConsoleScreenBufferInfo.argtypes = [ - wintypes.HANDLE, - POINTER(CONSOLE_SCREEN_BUFFER_INFO), - ] - _GetConsoleScreenBufferInfo.restype = wintypes.BOOL - - _SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute - _SetConsoleTextAttribute.argtypes = [ - wintypes.HANDLE, - wintypes.WORD, - ] - _SetConsoleTextAttribute.restype = wintypes.BOOL + handles = { + STDOUT: windll.kernel32.GetStdHandle(STDOUT), + STDERR: windll.kernel32.GetStdHandle(STDERR), + } - _SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition - _SetConsoleCursorPosition.argtypes = [ - wintypes.HANDLE, - wintypes._COORD, - ] - _SetConsoleCursorPosition.restype = wintypes.BOOL + SHORT = c_short + WORD = c_ushort + DWORD = c_uint32 + TCHAR = c_char - _FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA - _FillConsoleOutputCharacterA.argtypes = [ - wintypes.HANDLE, - c_char, - wintypes.DWORD, - wintypes._COORD, - POINTER(wintypes.DWORD), - ] - _FillConsoleOutputCharacterA.restype = wintypes.BOOL + class COORD(Structure): + """struct in wincon.h""" + _fields_ = [ + ('X', SHORT), + ('Y', SHORT), + ] - _FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute - _FillConsoleOutputAttribute.argtypes = [ - wintypes.HANDLE, - wintypes.WORD, - wintypes.DWORD, - wintypes._COORD, - POINTER(wintypes.DWORD), - ] - _FillConsoleOutputAttribute.restype = wintypes.BOOL + class SMALL_RECT(Structure): + """struct in wincon.h.""" + _fields_ = [ + ("Left", SHORT), + ("Top", SHORT), + ("Right", SHORT), + ("Bottom", SHORT), + ] - handles = { - STDOUT: _GetStdHandle(STDOUT), - STDERR: _GetStdHandle(STDERR), - } + class CONSOLE_SCREEN_BUFFER_INFO(Structure): + """struct in wincon.h.""" + _fields_ = [ + ("dwSize", COORD), + ("dwCursorPosition", COORD), + ("wAttributes", WORD), + ("srWindow", SMALL_RECT), + ("dwMaximumWindowSize", COORD), + ] - def GetConsoleScreenBufferInfo(stream_id=STDOUT): + def GetConsoleScreenBufferInfo(stream_id): handle = handles[stream_id] csbi = CONSOLE_SCREEN_BUFFER_INFO() - success = _GetConsoleScreenBufferInfo( + success = windll.kernel32.GetConsoleScreenBufferInfo( handle, byref(csbi)) + # This fails when imported via setup.py when installing using 'pip' + # presumably the fix is that running setup.py should not trigger all + # this activity. + # assert success return csbi def SetConsoleTextAttribute(stream_id, attrs): handle = handles[stream_id] - return _SetConsoleTextAttribute(handle, attrs) + success = windll.kernel32.SetConsoleTextAttribute(handle, attrs) + assert success def SetConsoleCursorPosition(stream_id, position): - position = wintypes._COORD(*position) - # If the position is out of range, do nothing. - if position.Y <= 0 or position.X <= 0: - return - # Adjust for Windows' SetConsoleCursorPosition: - # 1. being 0-based, while ANSI is 1-based. - # 2. expecting (x,y), while ANSI uses (y,x). - adjusted_position = wintypes._COORD(position.Y - 1, position.X - 1) - # Adjust for viewport's scroll position - sr = GetConsoleScreenBufferInfo(STDOUT).srWindow - adjusted_position.Y += sr.Top - adjusted_position.X += sr.Left - # Resume normal processing handle = handles[stream_id] - return _SetConsoleCursorPosition(handle, adjusted_position) + position = COORD(*position) + success = windll.kernel32.SetConsoleCursorPosition(handle, position) + assert success def FillConsoleOutputCharacter(stream_id, char, length, start): handle = handles[stream_id] - char = c_char(char) - length = wintypes.DWORD(length) - num_written = wintypes.DWORD(0) - # Note that this is hard-coded for ANSI (vs wide) bytes. - success = _FillConsoleOutputCharacterA( + char = TCHAR(char) + length = DWORD(length) + start = COORD(*start) + num_written = DWORD(0) + # AttributeError: function 'FillConsoleOutputCharacter' not found + # could it just be that my types are wrong? + success = windll.kernel32.FillConsoleOutputCharacter( handle, char, length, start, byref(num_written)) + assert success return num_written.value - def FillConsoleOutputAttribute(stream_id, attr, length, start): - ''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )''' - handle = handles[stream_id] - attribute = wintypes.WORD(attr) - length = wintypes.DWORD(length) - num_written = wintypes.DWORD(0) - # Note that this is hard-coded for ANSI (vs wide) bytes. - return _FillConsoleOutputAttribute( - handle, attribute, length, start, byref(num_written)) + +if __name__=='__main__': + x = GetConsoleScreenBufferInfo(STDOUT) + print(x.dwSize) + print(x.dwCursorPosition) + print(x.wAttributes) + print(x.srWindow) + print(x.dwMaximumWindowSize) + diff --git a/python3/libs/colorama/winterm.py b/python3/libs/colorama/winterm.py index 270881154..63f4469cc 100644 --- a/python3/libs/colorama/winterm.py +++ b/python3/libs/colorama/winterm.py @@ -1,4 +1,4 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. + from . import win32 @@ -22,7 +22,8 @@ class WinStyle(object): class WinTerm(object): def __init__(self): - self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes + self._default = \ + win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes self.set_attrs(self._default) self._default_fore = self._fore self._default_back = self._back @@ -66,55 +67,3 @@ def set_console(self, attrs=None, on_stderr=False): handle = win32.STDERR win32.SetConsoleTextAttribute(handle, attrs) - def get_position(self, handle): - position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition - # Because Windows coordinates are 0-based, - # and win32.SetConsoleCursorPosition expects 1-based. - position.X += 1 - position.Y += 1 - return position - - def set_cursor_position(self, position=None, on_stderr=False): - if position is None: - #I'm not currently tracking the position, so there is no default. - #position = self.get_position() - return - handle = win32.STDOUT - if on_stderr: - handle = win32.STDERR - win32.SetConsoleCursorPosition(handle, position) - - def cursor_up(self, num_rows=0, on_stderr=False): - if num_rows == 0: - return - handle = win32.STDOUT - if on_stderr: - handle = win32.STDERR - position = self.get_position(handle) - adjusted_position = (position.Y - num_rows, position.X) - self.set_cursor_position(adjusted_position, on_stderr) - - def erase_data(self, mode=0, on_stderr=False): - # 0 (or None) should clear from the cursor to the end of the screen. - # 1 should clear from the cursor to the beginning of the screen. - # 2 should clear the entire screen. (And maybe move cursor to (1,1)?) - # - # At the moment, I only support mode 2. From looking at the API, it - # should be possible to calculate a different number of bytes to clear, - # and to do so relative to the cursor position. - if mode[0] not in (2,): - return - handle = win32.STDOUT - if on_stderr: - handle = win32.STDERR - # here's where we'll home the cursor - coord_screen = win32.COORD(0,0) - csbi = win32.GetConsoleScreenBufferInfo(handle) - # get the number of character cells in the current buffer - dw_con_size = csbi.dwSize.X * csbi.dwSize.Y - # fill the entire screen with blanks - win32.FillConsoleOutputCharacter(handle, ' ', dw_con_size, coord_screen) - # now set the buffer's attributes accordingly - win32.FillConsoleOutputAttribute(handle, self.get_attrs(), dw_con_size, coord_screen ); - # put the cursor at (0, 0) - win32.SetConsoleCursorPosition(handle, (coord_screen.X, coord_screen.Y)) diff --git a/python3/runner/path_to_enlightenment.py b/python3/runner/path_to_enlightenment.py index e8a23fa32..f1bcb4261 100644 --- a/python3/runner/path_to_enlightenment.py +++ b/python3/runner/path_to_enlightenment.py @@ -86,6 +86,5 @@ def koans(): suite.addTests(loader.loadTestsFromTestCase(AboutProxyObjectProject)) suite.addTests(loader.loadTestsFromTestCase(TelevisionTest)) suite.addTests(loader.loadTestsFromTestCase(AboutExtraCredit)) - suite.addTests(loader.loadTestsFromTestCase(AboutRegex)) return suite