def test_delegates_to_an_instancemethod(self): value = mock.Mock() class Obj(object): def instancemethod(self): return value delegator = SimpleDelegator(Obj()) expect(delegator.instancemethod()) == value
def should_set_links_up_on_splice(self): neuron1 = BiasNeuron() neuron2 = Neuron() weight = 0.5 Network(()).splice(neuron1, neuron2, weight) neuron2.fire() expect(neuron2.activation) == sigmoid(0.5 * neuron1.activation)
def is_none_when_no_file(template): template.root = "my_root" with patch('pathlib.Path.is_file', Mock(return_value=False)): path = template.path expect(path) == None
def test_can_be_pickled(self): obj = [1, 2, 3] delegator = SimpleDelegator(obj) pickled = pickle.dumps(delegator) del delegator unpickled_delegator = pickle.loads(pickled) expect(get_delegated(unpickled_delegator)) == obj
def should_be_sigmoid_of_sum_of_incoming_values(self): incoming = StubSynapse(1.0) neuron = Neuron() neuron.add_incoming(incoming) neuron.add_incoming(incoming) neuron.fire() expect(neuron.activation) == sigmoid(2.0)
def it_expects_isinstance(self): expect(1).isinstance(int) def _fails(): expect(1).isinstance(str) assert_raises(AssertionError, _fails) assert fail_msg(_fails) == ( 'Expected an instance of str but got an instance of int')
def is_returned_when_file_exists(template): template.root = "my_root" with patch('pathlib.Path.is_file', Mock(return_value=True)): path = template.path expect(path) == Path("my_root/abc/default.png")
def it_expects_less_than_or_equal(self): expect(1) <= 1 expect(1) <= 2 def _fails(): expect(2) <= 1 assert_raises(AssertionError, _fails) assert fail_msg(_fails) == ( 'Expected something less than or equal to 1 but got 2')
def it_expects_greater_than_or_equal(self): expect(1) >= 1 expect(2) >= 1 def _fails(): expect(1) >= 2 assert_raises(AssertionError, _fails) assert fail_msg(_fails) == ( 'Expected something greater than or equal to 2 but got 1')
def it_expects_non_containment(self): expect([1]).does_not_contain(0) def _fails(): expect([1]).does_not_contain(1) assert_raises(AssertionError, _fails) assert fail_msg(_fails) == ( "Expected [1] to not contain 1 but it did")
def test_display_non_verbose(self, stdout): locs = NumberedPoints(['Home', '52.168;0.040'], config_locations={'Home': (52.015, -0.221)}) locs.format = 'locator' locs.verbose = False locs.display('extsquare') expect(stdout.getvalue()) == 'IO92va33\nJO02ae40\n'
def with_dashes(client): status, data = load(client.get( "/api/templates/iw/HelloThere_World/How-areYOU")) expect(status) == 302 expect(data).contains( '<a href="/api/templates/iw/hello_there_world/how_are_you">')
def it_expects_containment(self): expect([1]).contains(1) def _fails(): expect([2]).contains(1) assert_raises(AssertionError, _fails) assert fail_msg(_fails) == ( "Expected [2] to contain 1 but it didn't")
def test_dump_zone_file(self): zones = Zones(open("tests/data/timezones")) expect(Zones.dump_zone_file(zones)) == [ "AN\t+121100-0690000\tAmerica/Curacao", "AO\t-084800+0131400\tAfrica/Luanda", "AQ\t-775000+1663600\tAntarctica/McMurdo\tMcMurdo Station, Ross Island", ]
def when_off_ci(monkeypatch): monkeypatch.delenv('CI', raising=False) monkeypatch.delenv('CONTINUOUS_INTEGRATION', raising=False) monkeypatch.delenv('TRAVIS', raising=False) monkeypatch.delenv('APPVEYOR', raising=False) expect(services.detected()) == False
def it_expects_isinstance_for_multiple_types(self): expect('str').isinstance((str, bytes)) def _fails(): expect('str').isinstance((int, tuple)) assert_raises(AssertionError, _fails) assert fail_msg(_fails) == ( 'Expected an instance of int or tuple but got an instance of str')
def it_can_compare_bytes(self): null = bytes((0,)) expect(null) == null data = bytes(range(9, 32)) def _fails(): expect(data) == data + null assert_raises(AssertionError, _fails)
def test_file_provider(): with app_client() as client: rv = client.get('/fanstatic/jquery/jquery.js') expect(rv.status_code) == 200 rv = client.get('/fanstatic/jquery/does-not-exist.js') expect(rv.status_code) == 404
def it_returns_an_image_otherwise(mock_send_file, app): with app.test_request_context(): display("my_title", "my_path") expect(mock_send_file.mock_calls) == [ call("my_path", mimetype='image/jpeg'), ]
def test_midpoint(self): expect(Point(52.015, -0.221).midpoint(Point(52.6333, -2.5))) == \ Point(52.329631405407014, -1.3525368605590993, 'metric', 'degrees', 0) expect(Point(36.1200, -86.6700).midpoint(Point(33.9400, -118.4000))) == \ Point(36.08239491900365, -102.75217370539663, 'metric', 'degrees', 0)
def test_import_locations(self): locations = Points() locations.import_locations(['0;0', '52.015 -0.221']) expect(repr(locations)) == \ ("Points([Point(0.0, 0.0, 'metric', 'degrees', 0), " "Point(52.015, -0.221, 'metric', 'degrees', 0)], " "False, 'metric')")
def it_returns_an_error_when_no_metrics_specified(client): status, data = load(client.put("/my_owner/my_repo")) expect(status) == 400 expect(data) == { 'message': "No metrics provided." }
def test___repr__(self): expect(repr(Cell(4, 52.015, -0.221, 21, 46, 40000, 10, 0, 1, datetime.datetime(2008, 4, 15, 15, 21, 35), datetime.datetime(2008, 4, 15, 15, 28, 49)))) == \ ('Cell(4, 52.015, -0.221, 21, 46, 40000, 10, 0, 1, ' 'datetime.datetime(2008, 4, 15, 15, 21, 35), ' 'datetime.datetime(2008, 4, 15, 15, 28, 49))')
def test_get(self, outbox_class): outbox_class.return_value.get.return_value = self.mail response = self.client.get(self._reverse()) expect(response.status_code) == 200 expect(response.context['mail']) == self.mail
def test_import_locations(self): trackpoints = Trackpoints(open("tests/data/gpx_tracks")) data = list(map(str, sorted(trackpoints[0], key=lambda x: x.name))) expect(data[0]) == """Home (52°00'54"N, 000°13'15"W on 2008-07-26T00:00:00+00:00) [My place]""" expect( data[1] ) == """MSR (52°10'01"N, 000°23'24"E on 2008-07-27T00:00:00+00:00) [Microsoft Research, Cambridge]"""
def it_redirects_to_lose_alt_when_unknown_url(client): url = "http://example.com/not/a/real/image.jpg" response = client.get("/sad-biden/hello.jpg?alt=" + url) expect(response.status_code) == 302 expect(load(response, as_json=False)).contains( '<a href="/sad-biden/hello.jpg">')
def it_redirects_to_lose_alt_when_bad_url(client): url = "http:invalid" response = client.get("/sad-biden/hello.jpg?alt=" + url) expect(response.status_code) == 302 expect(load(response, as_json=False)).contains( '<a href="/sad-biden/hello.jpg">')
def test_relevant_changes(self): ok = SprinterChange(pk=1, component='Forms') not_ok = SprinterChange(pk=2, component='ORM') achievement = Achievement(component='Forms') changes = [ok, not_ok] filtered = achievement.relevant_changes(changes) expect(filtered) == [ok]
def test_can_read_from_properties(self): class C(SimpleDelegator): @property def prop(self): return 123 c = C(mock.Mock()) expect(c.prop) == 123
def it_returns_an_error_for_unknown_projects(client): status, data = load(client.get("/unknown/project")) expect(status) == 404 expect(data) == { 'message': "No such project." }
def when_alias(client): response = client.get("/api/templates/insanity-wolf") expect(response.status_code) == 302 assert '<a href="/api/templates/iw">' in load(response, as_json=False)
(x + i, y + j, z + k) for i, j, k in product((-1, 0, 1), repeat=3) if (i, j, k) != (0, 0, 0) ) for _ in range(6): inactive_neighbors = ( set(chain.from_iterable(neighbors(*c) for c in cubes)) - cubes ) next_state = { c for c in cubes if len([n for n in neighbors(*c) if n in cubes]) in (2, 3) } | { c for c in inactive_neighbors if len([n for n in neighbors(*c) if n in cubes]) == 3 } cubes = next_state return len(cubes) test = """\ .#. ..# ### """ expect(aoc(test)) == 112 print(aoc(sys.stdin.read()))
def test_non_existing_database(): expect(Events()) == Events.read("I_NEVER_EXIST")
def test_store_messages_with_events(): events = Events.read('tests/data/test') expect(events.last().message) == 'finished'
def test_read_datebase(): expect(len(Events.read('tests/data/test'))) == 3
def test_event_creation(task, start, delta, message): e = Event(task, start, delta, message) expect(e.task) == task if isinstance(start, datetime): expect(e.start) == start elif start: expect(e.start) == parse_datetime(start) else: # Special case to ignore comparison against utcnow() pass if isinstance(delta, timedelta): expect(e.delta) == delta else: expect(e.delta) == parse_delta(delta) expect(e.message) == message
def when_alias_with_text(client): response = client.get("/api/templates/insanity-wolf/hello/world") expect(response.status_code) == 302 assert '<a href="/api/templates/iw/hello/world">' in \ load(response, as_json=False)
def when_masked(client): response = client.get("/_aXcJaGVsbG8vd29ybGQJ") expect(response.status_code) == 302 assert '<a href="/api/templates/iw/hello/world">' in \ load(response, as_json=False)
def it_requires_a_name_to_return_aliases(client): status, data = load(client.get("/api/aliases/")) expect(status) == 200 expect(data) == []
def when_masked_with_1_line(client): response = client.get("/_aXcJaGVsbG8J") expect(response.status_code) == 302 assert '<a href="/api/templates/iw/hello">' in \ load(response, as_json=False)
def it_redirects_with_param(client): status, text = load(client.get("/api/aliases/?name=foo"), as_json=False) expect(status) == 302 expect(text).contains('<a href="/api/aliases/foo">')
def with_dashes(client): response = client.get("/api/templates/iw/HelloThere_World/How-areYOU") expect(response.status_code) == 302 assert '<a href="/api/templates/iw/hello_there_world/how_are_you">' in \ load(response, as_json=False)
def _fails(): expect(big_list) == sequence
def with_many_matches(client): status, data = load(client.get("/api/aliases/votestakes")) expect(status) == 200 expect(len(data)) == 5
from expecter import expect def aoc(data): and_mask = or_mask = mask = "X" mem = {} for line in data.strip().splitlines(): act, _, value = line.strip().partition(" = ") if act == "mask": mask = value and_mask = int(mask.replace("X", "1"), 2) or_mask = int(mask.replace("X", "0"), 2) elif act.startswith("mem["): pos = int(act[4:-1]) value = int(value) mem[pos] = (value & and_mask) | or_mask return sum(mem.values()) test = """\ mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X mem[8] = 11 mem[7] = 101 mem[8] = 0 """ expect(aoc(test)) == 165 print(aoc(sys.stdin.read()))
def _fails(): expect(actual) == expected
def when_plus(client): response = client.get('/4/+/5') expect(response.data).contains(b"9")
def _fails(): expect('foo\nbar') == 'foo\nbaz'
def test_match(client, pattern, links): response = client.get("/api/magic/" + pattern, follow_redirects=True) _, matches = load(response) expect([match['link'] for match in matches]) == links
def from_db(client, pattern): response = client.get('/4/x/5') expect(response.data).contains(b"20")
def test_cmp_version_to_tuple(): expect(Version()) == (0, 1, 0)
def it_says_hello(client): response = client.get('/') expect(response.data).contains(b"Praveen")
def test_cmp_version_greather_than_equal(): expect(Version((0, 2, 0))) >= Version((0, 1, 0)) expect(Version((0, 2, 0))) >= Version((0, 2, 0))
..#.#.###. ...#.#.#.# Tile 2729: ...#.#.#.# ####.#.... ..#.#..... ....#..#.# .##..##.#. .#.####... ####.#.#.. ##.####... ##..#.##.. #.##...##. Tile 3079: #.#.#####. .#..###### ..#....... ######.... ####.#..#. .#...#.##. #.#####.## ..#.###... ..#....... ..#.###... """ expect(aoc(test)) == 273 print(aoc(sys.stdin.read(), print_monsters=True))
def test_cmp_version_less_than(): expect(Version((0, 1, 0))) < Version((0, 2, 0))
def test_cmp_version_to_version(): expect(Version()) == Version()
def test_cmp_version_to_list(): expect(Version()) == [0, 1, 0]
def test_cmp_version_less_than_equal(): expect(Version((0, 1, 0))) <= Version((0, 2, 0)) expect(Version((0, 2, 0))) <= Version((0, 2, 0))
else: ruledict[name] = [ " ".join(s[1:-1]) for c in content.split(",") for s in [c.split()] ] return ruledict def aoc(rules): rules = parse(rules) canhold = lambda v: ("shiny gold" in v) or any( canhold(rules[k]) for k in v) return len([k for k in rules if canhold(rules[k])]) test = """ light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags. """ expect(aoc(test)) == 4 print(aoc(sys.stdin.read()))
def test_cmp_version_to_str(): expect(Version()) == '0.1.0'