def test_signals_resend_on_1st_call_after_flush_interval_with_errors(self): req = _make_test_request(self.SERVICE_NAME) failure_code = messages.CheckError.CodeValueValuesEnum.NOT_FOUND fake_response = messages.CheckResponse( operationId=self.FAKE_OPERATION_ID, checkErrors=[ messages.CheckError(code=failure_code) ]) agg = self.agg expect(agg.check(req)).to(be_none) agg.add_response(req, fake_response) expect(agg.check(req)).to(equal(fake_response)) # Now flush interval is reached, but not the response expiry self.timer.tick() # now past the flush_interval expect(agg.check(req)).to(be_none) # first response is null # until expiry, the response will continue to be returned expect(agg.check(req)).to(equal(fake_response)) expect(agg.check(req)).to(equal(fake_response)) # expire self.timer.tick() self.timer.tick() # now expired expect(agg.check(req)).to(be_none) expect(agg.check(req)).to(be_none) # 2nd check is None as well
def test_should_not_enter_scheduler_for_cached_checks(self, sched, thread_class): thread_class.return_value.start.side_effect = lambda: old_div(1,0) self._subject.start() # confirm scheduler is created and initialized expect(sched.scheduler.called).to(be_true) scheduler = sched.scheduler.return_value expect(scheduler.enter.called).to(be_true) scheduler.reset_mock() # call check once, to a cache response dummy_request = _make_dummy_check_request(self.PROJECT_ID, self.SERVICE_NAME) dummy_response = messages.CheckResponse( operationId=dummy_request.checkRequest.operation.operationId) t = self._mock_transport t.services.check.return_value = dummy_response expect(self._subject.check(dummy_request)).to(equal(dummy_response)) t.reset_mock() # call check again - response is cached... expect(self._subject.check(dummy_request)).to(equal(dummy_response)) expect(self._mock_transport.services.check.called).to(be_false) # ... the scheduler is not run expect(scheduler.run.called).to(be_false)
def test_should_update_temp_response_with_actual(self): req = _make_test_request(self.SERVICE_NAME, self.FAKE_OPERATION_ID) temp_response = sc_messages.AllocateQuotaResponse( operationId=self.FAKE_OPERATION_ID) real_response = sc_messages.AllocateQuotaResponse( operationId=self.FAKE_OPERATION_ID, quotaMetrics=[sc_messages.MetricValueSet( metricName=u'a_float', metricValues=[ metric_value.create( labels={ u'key1': u'value1', u'key2': u'value2'}, doubleValue=1.1, ), ] )] ) agg = self.agg agg.allocate_quota(req) signature = quota_request.sign(req.allocateQuotaRequest) with agg._cache as cache: item = cache[signature] expect(item.response).to(equal(temp_response)) expect(item.is_in_flight).to(be_true) agg.add_response(req, real_response) item = cache[signature] expect(item.response).to(equal(real_response)) expect(item.is_in_flight).to(be_false)
def test_should_send_requests_with_configured_header_api_key(self): wrappee = _DummyWsgiApp() control_client = mock.MagicMock(spec=client.Client) given = { u'wsgi.url_scheme': u'http', u'PATH_INFO': u'/uvw/method1/with_query_param', u'REMOTE_ADDR': u'192.168.0.3', u'HTTP_HOST': u'localhost', u'HTTP_APIKEYHEADER': u'my-header-value', u'HTTP_REFERER': u'example.myreferer.com', u'REQUEST_METHOD': u'GET'} dummy_response = messages.CheckResponse(operationId=u'fake_operation_id') wrapped = wsgi.add_all(wrappee, self.PROJECT_ID, control_client, loader=service.Loaders.ENVIRONMENT) control_client.check.return_value = dummy_response wrapped(given, _dummy_start_response) expect(control_client.check.called).to(be_true) check_request = control_client.check.call_args_list[0].checkRequest check_req = control_client.check.call_args[0][0] expect(check_req.checkRequest.operation.consumerId).to( equal(u'api_key:my-header-value')) expect(control_client.report.called).to(be_true) report_req = control_client.report.call_args[0][0] expect(report_req.reportRequest.operations[0].consumerId).to( equal(u'api_key:my-header-value'))
def test_should_send_requests_with_default_query_param_api_key(self): for default_key in (u'key', u'api_key'): wrappee = _DummyWsgiApp() control_client = mock.MagicMock(spec=client.Client) given = { u'wsgi.url_scheme': u'http', u'QUERY_STRING': u'%s=my-default-api-key-value' % (default_key,), u'PATH_INFO': u'/uvw/method_needs_api_key/with_query_param', u'REMOTE_ADDR': u'192.168.0.3', u'HTTP_HOST': u'localhost', u'HTTP_REFERER': u'example.myreferer.com', u'REQUEST_METHOD': u'GET'} dummy_response = sc_messages.CheckResponse( operationId=u'fake_operation_id') wrapped = wsgi.add_all(wrappee, self.PROJECT_ID, control_client, loader=service.Loaders.ENVIRONMENT) control_client.check.return_value = dummy_response wrapped(given, _dummy_start_response) expect(control_client.check.called).to(be_true) check_request = control_client.check.call_args_list[0].checkRequest check_req = control_client.check.call_args[0][0] expect(check_req.checkRequest.operation.consumerId).to( equal(u'api_key:my-default-api-key-value')) expect(control_client.report.called).to(be_true) report_req = control_client.report.call_args[0][0] expect(report_req.reportRequest.operations[0].consumerId).to( equal(u'api_key:my-default-api-key-value')) expect(control_client.allocate_quota.called).to(be_false)
def test_should_return_ttl_cache_if_flush_interval_is_positive(self): delta = datetime.timedelta(seconds=1) should_be_ttl = [ lambda timer: caches.create( caches.CheckOptions(num_entries=1, flush_interval=delta), timer=timer ), lambda timer: caches.create( caches.ReportOptions(num_entries=1, flush_interval=delta), timer=timer ), ] for testf in should_be_ttl: timer = _DateTimeTimer() sync_cache = testf(timer) expect(sync_cache).to(be_a(caches.LockedObject)) with sync_cache as cache: expect(cache).to(be_a(caches.DequeOutTTLCache)) expect(cache.timer()).to(equal(0)) cache[1] = 1 expect(set(cache)).to(equal({1})) expect(cache.get(1)).to(equal(1)) timer.tick() expect(cache.get(1)).to(equal(1)) timer.tick() expect(cache.get(1)).to(be_none) # Is still TTL without the custom timer sync_cache = testf(None) expect(sync_cache).to(be_a(caches.LockedObject)) with sync_cache as cache: expect(cache).to(be_a(caches.DequeOutTTLCache))
def _expect_stats_eq_direct_calc_from_samples(d, samples): # pylint: disable=fixme # TODO: update this the sum of rho-squared want_mean = sum(samples) / len(samples) expect(d.mean).to(equal(want_mean)) expect(d.maximum).to(equal(max(samples))) expect(d.minimum).to(equal(min(samples)))
def test_flush_pipes_data_between_streams(self): a = StringIO(u'food') b = StringIO() pump = io.Pump(a, b) pump.flush(3) expect(a.read(1)).to(equal('d')) expect(b.getvalue()).to(equal('foo'))
def it_should_handle_the_collison_and_insert_the_url_twice(self): uow = inject.instance('UnitOfWorkManager') with uow.start() as tx: s_url1 = tx.short_urls.get('SID-123') s_url2 = tx.short_urls.get('SID-321') expect(s_url1.url).to(equal(self.url)) expect(s_url2.url).to(equal(self.url))
def test_should_merge_stats_correctly(self): # TODO(add a check of the variance) for d1, d2, _ in self.merge_triples: distribution.merge(d1, d2) expect(d2.count).to(equal(2)) expect(d2.mean).to(equal((_HIGH_SAMPLE + _LOW_SAMPLE) / 2)) expect(d2.maximum).to(equal(_HIGH_SAMPLE)) expect(d2.minimum).to(equal(_LOW_SAMPLE))
def it_should_insert_a_short_url(self): uow = inject.instance('UnitOfWorkManager') with uow.start() as tx: s_url = tx.short_urls.get(self.given_sid) expect(s_url).to(be_a(ShortUrl)) expect(s_url.url).to(equal(self.url)) expect(s_url.user).to(equal(user))
def test_should_ignores_lower_expiration(self): wanted_expiration = ( self.AN_INTERVAL + datetime.timedelta(milliseconds=1)) options = caches.CheckOptions(flush_interval=self.AN_INTERVAL, expiration=self.A_LOWER_INTERVAL) expect(options.flush_interval).to(equal(self.AN_INTERVAL)) expect(options.expiration).to(equal(wanted_expiration)) expect(options.expiration).not_to(equal(self.A_LOWER_INTERVAL))
def test_should_construct_with_ok_expected_args(self): rules = self.subject_cls(logs=[u'wanted_log'], metrics=self.WANTED_METRICS, labels=self.WANTED_LABELS) expect(rules).not_to(be_none) expect(rules.logs).to(equal(set([u'wanted_log']))) expect(rules.metrics).to(equal(self.WANTED_METRICS)) expect(rules.labels).to(equal(self.WANTED_LABELS))
def test_should_create_with_defaults(self): options = caches.CheckOptions() expect(options.num_entries).to(equal( caches.CheckOptions.DEFAULT_NUM_ENTRIES)) expect(options.flush_interval).to(equal( caches.CheckOptions.DEFAULT_FLUSH_INTERVAL)) expect(options.expiration).to(equal( caches.CheckOptions.DEFAULT_EXPIRATION))
def test_should_use_the_latest_end_time_delta_merges(self): got = metric_value.merge(MetricKind.DELTA, self.early_ending, self.late_ending) expect(got.endTime).to(equal(self.late_ending.endTime)) got = metric_value.merge(MetricKind.DELTA, self.late_ending, self.early_ending) expect(got.endTime).to(equal(self.late_ending.endTime))
def test_set_blocking_changes_fd_flags(): with tempfile.TemporaryFile() as f: io.set_blocking(f, False) flags = fcntl.fcntl(f, fcntl.F_GETFL) expect(flags & os.O_NONBLOCK).to(equal(os.O_NONBLOCK)) io.set_blocking(f, True) flags = fcntl.fcntl(f, fcntl.F_GETFL) expect(flags & os.O_NONBLOCK).to(equal(0))
def test_should_detect_nothing_for_methods_with_no_registration(self): registry = self._get_registry() info = registry.lookup(u'GET', u'uvw/default_parameters') expect(info).not_to(be_none) expect(info.selector).to(equal(u'Uvw.DefaultParameters')) expect(info.url_query_param(u'name1')).to(equal(tuple())) expect(info.url_query_param(u'name2')).to(equal(tuple())) expect(info.header_param(u'name1')).to(equal(tuple())) expect(info.header_param(u'name2')).to(equal(tuple()))
def test_should_add_ok_when_nanos_have_different_signs(self): the_sum = money.add(self._SOME_YEN, self._SOME_YEN_DEBT) want_units = self._SOME_YEN_DEBT.units + self._SOME_YEN.units - 1 expect(the_sum.units).to(equal(want_units)) expect(the_sum.nanos).to(equal(money.MAX_NANOS)) the_sum = money.add(self._SOME_MORE_YEN, self._SOME_YEN_DEBT) want_units = self._SOME_YEN_DEBT.units + self._SOME_YEN.units - 1 expect(the_sum.units).to(equal(want_units)) expect(the_sum.nanos).to(equal(1 - money.MAX_NANOS))
def test_should_convert_using_as_quota_request(self): timer = _DateTimeTimer() for info, want in _INFO_TESTS: got = info.as_allocate_quota_request(timer=timer) # These additional properties have no well-defined order, so sort them. got.allocateQuotaRequest.allocateOperation.labels.additionalProperties.sort(key=KEYGETTER) want.labels.additionalProperties.sort(key=KEYGETTER) expect(got.allocateQuotaRequest.allocateOperation).to(equal(want)) expect(got.serviceName).to(equal(_TEST_SERVICE_NAME))
def test_should_add_expected_label_as_report_request(self): timer = _DateTimeTimer() rules = report_request.ReportingRules(labels=[ _EXPECTED_OK_LABEL ]) for info, want in _ADD_LABELS_TESTS: got = info.as_report_request(rules, timer=timer) expect(got.serviceName).to(equal(_TEST_SERVICE_NAME)) expect(got.reportRequest.operations[0]).to(equal(want))
def test_should_detect_registered_system_parameters(self): registry = self._get_registry() info = registry.lookup(u'GET', u'uvw/method1/abc') expect(info).not_to(be_none) expect(info.selector).to(equal(u'Uvw.Method1')) expect(info.url_query_param(u'name1')).to(equal((u'param_key1',))) expect(info.url_query_param(u'name2')).to(equal((u'param_key2',))) expect(info.header_param(u'name1')).to(equal((u'Header-Key1',))) expect(info.header_param(u'name2')).to(equal((u'Header-Key2',)))
def test_select_returns_streams_for_reading(): a, b = socket.socketpair() a.send(b'test') expect(io.select([a, b], timeout=0)).to(equal([b])) b.send(b'test') expect(io.select([a, b], timeout=0)).to(equal([a, b])) b.recv(4) expect(io.select([a, b], timeout=0)).to(equal([a])) a.recv(4) expect(io.select([a, b], timeout=0)).to(equal([]))
def test_reading_data_from_slow_stream(self): slow_stream = SlowStream([ b"\x01\x00\x00\x00\x00\x00\x00\x03f", b"oo", b"\x01\x00\x00\x00\x00\x00\x00\x01d", ]) demuxer = io.Demuxer(slow_stream) expect(demuxer.read(32)).to(equal(b'foo')) expect(demuxer.read(32)).to(equal(b'd'))
def test_reading_size_from_slow_stream(self): slow_stream = SlowStream([ "\x01\x00\x00\x00", "\x00\x00\x00\x03foo", "\x01\x00", "\x00\x00\x00\x00\x00\x01d", ]) demuxer = io.Demuxer(slow_stream) expect(demuxer.read(32)).to(equal('foo')) expect(demuxer.read(32)).to(equal('d'))
def test_should_include_project_id_in_error_text_when_needed(self): resp = sc_messages.AllocateQuotaResponse( allocateErrors = [ sc_messages.QuotaError( code=sc_messages.QuotaError.CodeValueValuesEnum.PROJECT_DELETED) ] ) code, got = quota_request.convert_response(resp, self.PROJECT_ID) want = u'Project %s has been deleted' % (self.PROJECT_ID,) expect(code).to(equal(httplib.FORBIDDEN)) expect(got).to(equal(want))
def test_should_include_project_id_in_error_text_when_needed(self): resp = messages.CheckResponse( checkErrors = [ messages.CheckError( code=messages.CheckError.CodeValueValuesEnum.PROJECT_DELETED) ] ) code, got, _ = check_request.convert_response(resp, self.PROJECT_ID) want = u'Project %s has been deleted' % (self.PROJECT_ID,) expect(code).to(equal(httplib.FORBIDDEN)) expect(got).to(equal(want))
def test_should_queue_the_request_if_not_cached(self, dummy_thread_class): # the request isn't sent immediately as long as a cache exists # instead we get a temporary response self._subject.start() dummy_request = _make_dummy_quota_request(self.PROJECT_ID, self.SERVICE_NAME) resp = self._subject.allocate_quota(dummy_request) with self._subject._quota_aggregator._out as out_deque: expect(out_deque[0]).to(equal(dummy_request)) expect(resp.operationId).to(equal( dummy_request.allocateQuotaRequest.allocateOperation.operationId))
def test_reading_size_from_slow_stream(self): slow_stream = SlowStream([ b'\x01\x00\x00\x00', b'\x00\x00\x00\x03foo', b'\x01\x00', b'\x00\x00\x00\x00\x00\x01d', ]) demuxer = io.Demuxer(slow_stream) expect(demuxer.read(32)).to(equal(b'foo')) expect(demuxer.read(32)).to(equal(b'd'))
def test_should_add_expected_label_as_report_request(self): timer = _DateTimeTimer() rules = report_request.ReportingRules(labels=[ _EXPECTED_OK_LABEL ]) for info, want in _ADD_LABELS_TESTS: got = info.as_report_request(rules, timer=timer) # These additional properties have no well-defined order, so sort them. got.reportRequest.operations[0].labels.additionalProperties.sort(key=KEYGETTER) want.labels.additionalProperties.sort(key=KEYGETTER) expect(got.serviceName).to(equal(_TEST_SERVICE_NAME)) expect(got.reportRequest.operations[0]).to(equal(want))
def test_get_d3_node_edge_representation_from_graph(self): parser = GraphParser() graph = { 'a': ['b', 'c'], 'b': ['a'] } nodes, edges = parser.d3_representation(graph) expect(nodes).to(be_a(list)) expect(set(nodes)).to(equal({'a', 'b', 'c'})) expect(edges).to(equal([('a', 'b'), ('a', 'c'), ('b', 'a')]))
bucket.has_file = Mock(return_value=has_file) bucket.get_file = Mock(return_value=file_name) return bucket with description("Entry"): with it("should hash http-link form id's"): http_id = "http://example.com" entry = Entry(FeedParserDict(id=http_id), None) expect(entry.id).not_to(contain("http")) with it("should not change it if it is does not contain http"): entry = Entry(BASIC_INPUT_ENTRY, None) expect(entry.id).to(equal(EXAMPLE_ID)) with it("should be marked as processed if the file with given id is in the bucket" ): entry = Entry(BASIC_INPUT_ENTRY, mock_bucket(True)) expect(entry.processed).to(be(True)) with it("should redirect unset fields to input_entry"): test_field = "whee" entry = Entry(FeedParserDict(id=EXAMPLE_ID, test_field=test_field), None) expect(entry.test_field).to(equal(test_field)) with it("should use file in the bucket if the file for given id exists"):
from mamba import description, context, it from expects import expect, equal, contain from fractions import Fraction from ly2abc.note import Key from spec.ly2abc_spec_helper import * with description('Key') as self: with it('takes a pitch and a mode'): expect(Key(Pitch.c, 'major')).not_to(equal(None)) with description('sharps') as self: with it('has 0 sharps for Cmajor'): expect(Key(Pitch.c, 'major').sharps()).to(equal(0)) with it('has 3 flats for Eb major'): expect(Key(Pitch.ef, 'major').sharps()).to(equal(-3)) with it('has 4 sharps for E major'): expect(Key(Pitch.e, 'major').sharps()).to(equal(4)) with it('has 3 flats for C minor'): expect(Key(Pitch.c, 'minor').sharps()).to(equal(-3)) with it('has 0 sharps for D dorian'): expect(Key(Pitch.d, 'dorian').sharps()).to(equal(0)) with it('has 2 sharps for A mixolydian'): expect(Key(Pitch.a, 'mixolydian').sharps()).to(equal(2)) with it('has 9 sharps for D# major'):
def fibonacci(index): if index < 2: return index return fibonacci(index - 1) + fibonacci(index - 2) with description('fibonacci specs'): with context('for the first two indexes'): with it('returns index'): expected_values = {0: 0, 1: 1} for index, expected_value in expected_values.items(): value = fibonacci(index) expect(value).to(equal(expected_value)) with context('for the rest of indexes'): with it('returns the sum of the previous two values'): expected_values = { 2: 1, 3: 2, 4: 3, 5: 5, 6: 8, 17: 1597, } for index, expected_value in expected_values.items(): value = fibonacci(index) expect(value).to(equal(expected_value))
def test_max_if_list_of_string(self): e = List(['apple', 'bear', 'dog', 'plum']) expect(e.max()).to(equal('plum'))
def test_version() -> None: expect(__version__).to(equal("0.1.0"))
def test_startup_succeeds(runner: CliRunner, rom: str) -> None: rom_name = os.path.basename(rom) result = runner.invoke(cli.cli, [rom, "-i"]) expect(result.exit_code).to(equal(0)) expect(result.output).to(contain(f"ROM File: {rom_name}\n"))