def should_call_only_with_arguments_that_the_handler_understands(): call_args = {"evil_extra": None} call_args.update(_.handler_kwargs) call_result = _.command.call(**call_args) expect(call_result).to.be.equal(_.called)
def test_should_fail_if_inputs_do_not_have_the_same_type(self): testf = lambda: timestamp.compare(self.TESTS[0][0], datetime.datetime.utcnow()) expect(testf).to(raise_error(ValueError)) testf = lambda: timestamp.compare(self.TESTS[0], datetime.datetime.utcnow()) expect(testf).to(raise_error(ValueError))
def it_should_pass_if_actual_raises_expected_exception_with_message(): message = 'Foo error' def callback(): raise AttributeError(message) expect(callback).to.raise_error(AttributeError, message)
def test_should_fail_if_actual_has_header_without_value_in_kwargs(self): with failure(self.response, "to have header 'content-length' with value '25'"): expect(response=self.response).to.have.headers( content_type=IRRELEVANT_HEADER_VALUE1, content_length='25')
def test_request_extraction_with_aggregation(self): req = _make_test_request(self.SERVICE_NAME, self.FAKE_OPERATION_ID) req = req.allocateQuotaRequest req.allocateOperation.quotaMetrics = [ sc_messages.MetricValueSet( metricName=u'a_float', metricValues=[ metric_value.create( labels={ u'key1': u'value1', u'key2': u'value2'}, int64Value=12, ), ] ) ] resp = sc_messages.AllocateQuotaResponse( operationId=self.FAKE_OPERATION_ID) item = quota_request.CachedItem(req, resp, self.SERVICE_NAME, None) expect(item._op_aggregator).to(be_none) item.aggregate(req) item.aggregate(req) extracted = item.extract_request() op = extracted.allocateQuotaRequest.allocateOperation expect(op.quotaMetrics[0].metricValues[0].int64Value).to(equal(24))
def test_should_fail_if_actual_has_expected_header_and_value(self): with failure( self.response, "not to have header {!r} with value {!r}".format(IRRELEVANT_HEADER_KEY1, IRRELEVANT_HEADER_VALUE1), ): expect(response=self.response).not_to.have.header(IRRELEVANT_HEADER_KEY1, IRRELEVANT_HEADER_VALUE1)
def test_should_not_send_the_request_if_cached(self, dummy_thread_class): t = self._mock_transport self._subject.start() dummy_request = _make_dummy_report_request(self.PROJECT_ID, self.SERVICE_NAME) self._subject.report(dummy_request) expect(t.services.report.called).to(be_false)
def it_should_return_the_correct_list_of_available_paths_equal_to_4_size(self): expected_paths = [ [self.vertexA, self.vertexB, self.vertexC, self.vertexD] ] expect(self.paths_equal_4_size).to(have_len(1)) for path in expected_paths: expect(self.paths_equal_4_size).to(contain(path))
def test_should_clear_requests_on_stop(self, dummy_thread_class): # stop the subject, the transport did not see a request self._subject.start() self._subject.report( _make_dummy_report_request(self.PROJECT_ID, self.SERVICE_NAME)) self._subject.stop() expect(self._mock_transport.services.report.called).to(be_true)
def test_should_ignore_bad_transport_when_not_cached(self, dummy_thread_class): self._subject.start() self._subject.report( _make_dummy_report_request(self.PROJECT_ID, self.SERVICE_NAME)) self._mock_transport.services.report.side_effect = lambda: old_div(1,0) self._subject.stop() expect(self._mock_transport.services.report.called).to(be_true)
def test_when_model_validate_raises_validation_error_then_raises_validation_error(self): class InvalidUser(User): def validate(self): raise errors.ValidationError() expect(lambda: self.validator(InvalidUser())).to.raise_error( errors.ValidationError)
def should_copy_the_songs_to_the_destination_directory(): execution = _.env.run(*_.cmd + ['--dest', 'pulled', 'pull']) copied_songs = [path for path in execution.files_created if 'pulled' in path and path.endswith('.mp3')] expect(copied_songs).to.have.length(2)
def test_should_convert_correctly_with_nanos(self): for t in self.NANO_TESTS: dt, nanos = timestamp.from_rfc3339(t[0], with_nanos=True) expect(dt).to(equal(t[1][0])) epsilon = abs(nanos - t[1][1]) # expect(epsilon).to(equal(0)) expect(epsilon).to(be_below_or_equal(self.TOLERANCE))
def it_should_fail_if_actual_has_key_in_kwargs_but_not_in_args(): with failure(_.dct, "not to have key 'bar' with value 0 but was 0"): expect(_.dct).not_to.have.keys('foo', bar=0) def it_should_fail_if_actual_has_key_in_dict_with_value(): with failure(_.dct, "not to have key 'bar' with value 0 but was 0"): expect(_.dct).not_to.have.keys({'bar': 0, 'foo': 1})
def test_should_merge_bucket_counts_correctly(self): for d1, d2, _ in self.merge_triples: d1_start = list(d1.bucketCounts) d2_start = list(d2.bucketCounts) want = [x + y for (x,y) in zip(d1_start, d2_start)] distribution.merge(d1, d2) expect(d2.bucketCounts).to(equal(want))
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_when_callable_raises_type_error_then_should_not_be_catched(self): def callback(): raise TypeError('foo') User.name.default = callback expect(lambda: User().name).to.raise_error(TypeError, 'foo')
def test_valid_json_object_as_file(self): _file = StringIO() _file.write(self.user_meta.to_json()) _file.seek(0) actual = serialize.deserialize(_file) expect(actual).to.equal([self.user_meta])
def test_when_default_is_callable_then_use_its_returned_value_as_field_default(self): default = 'anonymous' User.name.default = lambda: default user = User() expect(user.name).to.be(default)
def test_should_return_none_initially_as_req_is_not_cached(self): req = _make_test_request(self.SERVICE_NAME, self.FAKE_OPERATION_ID) fake_response = sc_messages.AllocateQuotaResponse( operationId=self.FAKE_OPERATION_ID) agg = self.agg actual = agg.allocate_quota(req) expect(actual).to(equal(fake_response))
def test_set_blocking_returns_previous_state(): with tempfile.TemporaryFile() as f: io.set_blocking(f, True) expect(io.set_blocking(f, False)).to.be.true io.set_blocking(f, False) expect(io.set_blocking(f, True)).to.be.false
def test_should_fail_if_actual_has_expected_header_without_value(self): with failure( self.response, "to have header {!r} with value {!r} but was".format(IRRELEVANT_HEADER_KEY1, IRRELEVANT_HEADER_VALUE3), ): expect(response=self.response).to.have.header(IRRELEVANT_HEADER_KEY1, IRRELEVANT_HEADER_VALUE3)
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 test_should_send_report_request_if_check_fails(self): wrappee = _DummyWsgiApp() control_client = mock.MagicMock(spec=client.Client) given = { u'wsgi.url_scheme': u'http', u'PATH_INFO': u'/any/method', 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 = messages.CheckResponse( operationId = u'fake_operation_id', checkErrors = [ messages.CheckError( code=messages.CheckError.CodeValueValuesEnum.PROJECT_DELETED) ] ) wrapped = wsgi.add_all(wrappee, self.PROJECT_ID, control_client, loader=service.Loaders.SIMPLE) control_client.check.return_value = dummy_response wrapped(given, _dummy_start_response) expect(control_client.check.called).to(be_true) expect(control_client.report.called).to(be_true)
def test_should_load_service_ok(self): loaded = service.Loaders.SIMPLE.load() registry = service.MethodRegistry(loaded) info = registry.lookup(u'GET', u'/anything') expect(info).not_to(be_none) info = registry.lookup(u'POST', u'/anything') expect(info).not_to(be_none)
def test_should_add_matching_hashes_for_matching_labels(self): a_dict = {'test': 'dict'} mv1 = metric_value.create(labels=a_dict) mv2 = metric_value.create(labels=a_dict) want = self.make_hash(mv1) got = self.make_hash(mv2) expect(got).to(equal(want))
def it_should_pass_if_actual_raises_and_message_matches_pattern(): pattern = r'\w+ error' def callback(): raise AttributeError(_.message) expect(callback).to.raise_error(AttributeError, pattern)
def assert_messages_and_user(context, numero, usuario): count = int(numero) #context.thread['msgs'].should.have.length_of(count) expect(context.thread['msgs']).to.have.length(count) msg = context.thread['msgs'][0] #msg['user'].should.equal(usuario) expect(msg['user']).to.equal(usuario)
def it_should_contain_extra_messages_if_assertion_fails(): try: _.obj.be(False, 'more', 'extra') except AssertionError: pass expect(_.obj._message).to.equal(['be', 'more', 'extra'])
def test_when_override_mixin_field_then_validates_subclass_field(self): class User(UserMixin, models.Model): name = fields.String(required=True) user = User() expect(lambda: user.validate()).to.raise_error( errors.ValidationError, 'required')
def test_rejects_list(self): name = self.add_module(values={"menu": ["spam", "eggs", "sausage"]}) expect(partial(config_for_module, name)).to(complain(TypeError))
def test_fileno_delegates_to_stream(self): demuxer = io.Demuxer(sys.stdout) expect(demuxer.fileno()).to.equal(sys.stdout.fileno())
def check_disables_redirect(self, method): client = HttpClient() client.enable_cookies() getattr(client, method)("http://something") expect(self.send_spy["allow_redirects"]).to(be(False))
def test_write_delegates_to_stream(self): s = StringIO() demuxer = io.Demuxer(s) demuxer.write(u'test') expect(s.getvalue()).to.equal('test')
def test_reading_partial_chunk(self): demuxer = io.Demuxer(self.create_fixture()) expect(demuxer.read(2)).to.equal('fo')
def test_read_from_socket(self): a, b = socket.socketpair() a.send('test') stream = io.Stream(b) expect(stream.read(32)).to.equal('test')
def test_flush_returns_length_written(self): a = StringIO(u'fo') b = StringIO() pump = io.Pump(a, b) expect(pump.flush(3)).to.equal(2)
def test_find_if_default_none_and_func_not_none(self): e = List([1, 2, 3, 4, 5]) act = e.find(lambda x: x % 2 == 0) expect(act).to(equal(2))
### from expects import expect, equal AN_EMPTY_STRING = '' NUMBER_WITH_NONE = '"","5"' TWO_NUMBERS = '"1","2"' with description('Given numbers as string'): with description('returns the sum of the numbers separated by comma'): with it('given an empty string returns 0 in string format'): result = string_calculator(AN_EMPTY_STRING) expected_result = '0' expect(result).to(equal(expected_result)) with description('given none and a number separated by commma'): with it('None equals to 0 and give the sum'): result = string_calculator(NUMBER_WITH_NONE) expected_result = '5' expect(result).to(equal(expected_result)) with description('given two int numbers separated by comma'): with it('it return the sum of both numbers'): result = string_calculator(TWO_NUMBERS) expected_result = '3' expect(result).to(equal(expected_result))
def test_find_if_default_applied_func_results_no_match(self): e = List([1, 2, 3, 4, 5]) act = e.find(default=100, callback=lambda x: x == 0) expect(act).to(equal(100))
def test_find_if_func_is_different_raises_error(self): e = List([1, 2, 3, 4, 5]) expect(lambda: e.find(default=0, callback='...')).to( raise_error(TypeError))
def test_find_if_default_and_func_not_none(self): e = List([1, 2, 3, 4, 5]) act = e.find(default=100, callback=lambda x: x == 0) expect(act).to(equal(100))
from sdcclient.secure import PolicyEventsClientV1 from specs import be_successful_api_call with description("Policy Events v1", "integration") as self: with before.each: self.client = PolicyEventsClientV1(sdc_url=os.getenv( "SDC_SECURE_URL", "https://secure.sysdig.com"), token=os.getenv("SDC_SECURE_TOKEN")) with context("when we try to retrieve policy events from the last 7 days"): with it("returns the list of all events happened"): week_in_seconds = 7 * 24 * 60 * 60 ok, res = self.client.get_policy_events_duration(week_in_seconds) expect((ok, res)).to(be_successful_api_call) expect(res).to(have_keys("ctx", "data")) expect(res["data"]).to( contain( have_keys("id", "timestamp", "customerId", "source", "name", "description", "cursor"))) with it("returns the list of all events from a range"): to_sec = int( (datetime.datetime.utcnow() - datetime.datetime.utcfromtimestamp(0)).total_seconds()) from_sec = to_sec - (7 * 24 * 60 * 60) ok, res = self.client.get_policy_events_range(from_sec, to_sec) expect((ok, res)).to(be_successful_api_call)
""" Suite for Breeds list endpoint calls """ import json from expects import expect, equal from questions_three.scaffolds.check_script import check, check_suite from questions_three.http_client import HttpClient with check_suite('/breeds/*/list* - lists endpoint calls'): response = HttpClient().get('https://dog.ceo/api/breeds/list/all') with check('response status is 200'): expect(response.status_code).to(equal(200)) body = json.loads(response.text) with check('response body status is a success'): expect(body["status"]).to(equal('success')) with check('response body message to have 94 breeds'): expect(len(body["message"])).to(equal(94)) with check_suite('/breeds/list/all/random/* - lists 10 random breeds including sub breeds'): response = HttpClient().get('https://dog.ceo/api/breeds/list/all/random/10') with check('response status is 200'): expect(response.status_code).to(equal(200)) body = json.loads(response.text) with check('response body status is a success'):
def test_read_from_file(self): with tempfile.TemporaryFile() as f: stream = io.Stream(f) f.write('test') f.seek(0) expect(stream.read(32)).to.equal('test')
"name": "Basic copy", "crowdanki_uuid": "6a69bc9d-de6d-42b3-9ba3-9f6e9cc09179", } ] @dataclass class Models: """Mock Anki's models, without initialising Anki's backend.""" models: dict Models.all = lambda self: self.models Models.save = MagicMock() with description("disambiguate_note_model_uuids"): with it("should disambiguate duplicated note model uuids"): collection = MagicMock() notifier = MagicMock() collection.models = Models(deepcopy(MODELS_WITH_DUPLICATES)) disambiguate_note_model_uuids(collection, notifier) expect(collection.models.all()).not_to(equal(MODELS_WITH_DUPLICATES)) expect(collection.models.all()[0]).to(equal(MODELS_WITH_DUPLICATES[0])) with it("should keep note models without duplicates unchanged uuids"): collection = MagicMock() notifier = MagicMock() collection.models = Models(deepcopy(MODELS_WITHOUT_DUPLICATES)) disambiguate_note_model_uuids(collection, notifier) expect(collection.models.all()).to(equal(MODELS_WITHOUT_DUPLICATES))
def test_write_to_socket(self): a, b = socket.socketpair() stream = io.Stream(a) stream.write('test') expect(b.recv(32)).to.equal('test')
from mamba import before, describe, it from expects import contain, equal, expect, have_length from src.datasource.covid19 import Covid19 with describe("Covid19") as self: with before.each: self.covid19 = Covid19() with describe("#countries") as self: with it("returns all country names"): expect(self.covid19.countries()).to(contain('Italy', 'Germany')) with describe("#metrics") as self: with it("returns three metrics for every country"): expect(self.covid19.metrics()).to( contain( 'Italy:confirmed', 'Italy:deaths', 'Italy:recovered', 'Germany:confirmed', 'Germany:deaths', 'Germany:recovered', )) with describe("#timeseries") as self: with it("returns 58 datapoints for group 'confirmed'"): expect(
def test_fileno_delegates_to_file_descriptor(self): stream = io.Stream(sys.stdout) expect(stream.fileno()).to.equal(sys.stdout.fileno())
from specs import be_successful_api_call with description("Events v1", "integration") as self: with before.all: self.client = EventsClientV1(sdc_url=os.getenv( "SDC_MONITOR_URL", "https://app.sysdigcloud.com"), token=os.getenv("SDC_MONITOR_TOKEN")) self.event_name = "event_v1_test_ci" with it("is able to create a custom event"): call = self.client.post_event( name=self.event_name, description= "This event was created in a CI pipeline for the Python SDK library" ) expect(call).to(be_successful_api_call) with it("is able to list the events happened without any filter"): time.sleep(3) # Wait for the event to appear in the feed ok, res = self.client.get_events() expect((ok, res)).to(be_successful_api_call) expect(res).to(have_key("events")) with it("is able to list the events created by the tests"): time.sleep(3) # Wait for the event to appear in the feed ok, res = self.client.get_events(last_s=60) expect((ok, res)).to(be_successful_api_call) expect(res).to( have_key("events", contain(have_keys(name=self.event_name)))) with it("is able to remove the event from the feed"):
def test_fileno_delegates_to_from_stream(self): pump = io.Pump(sys.stdout, sys.stderr) expect(pump.fileno()).to.equal(sys.stdout.fileno())
from mamba import description, context, it from expects import expect, equal import regex_project_type import constants with description('Regex Project Generator'): with context('regex for python'): with it('returns it'): python_project = regex_project_type.RegexProjectGenerator(['python']) expect(python_project.regex()).to(equal([constants.PYTHON_REGEX])) with context('having several project types'): with it('returns a list'): several_projects = regex_project_type.RegexProjectGenerator(['python','go']) expect(several_projects.regex()).to(equal([constants.PYTHON_REGEX, constants.GO_REGEX]))
def test_reading_overlapping_chunks(self): demuxer = io.Demuxer(self.create_fixture()) expect(demuxer.read(2)).to.equal('fo') expect(demuxer.read(2)).to.equal('o') expect(demuxer.read(2)).to.equal('d')
def test_write_returns_length_written(self): with tempfile.TemporaryFile() as f: stream = io.Stream(f) expect(stream.write('test')).to.equal(4)
def test_reading_multiple_chunks(self): demuxer = io.Demuxer(self.create_fixture()) expect(demuxer.read(32)).to.equal('foo') expect(demuxer.read(32)).to.equal('d')
def test_write_to_file(self): with tempfile.TemporaryFile() as f: stream = io.Stream(f) stream.write('test') f.seek(0) expect(f.read(32)).to.equal('test')
def test_write_returns_none_when_no_data(self): stream = io.Stream(StringIO()) expect(stream.write('')).to.be.none
def test_read_returns_empty_string_at_eof(self): with tempfile.TemporaryFile() as f: stream = io.Stream(f) expect(stream.read(32)).to.equal('')
def test_rejects_dict(self): name = self.add_module(values={"outer": {"inner": 42}}) expect(partial(config_for_module, name)).to(complain(TypeError))
def test_none(self): key = "worries" name = self.add_module(values={key: None}) actual = config_for_module(name)[key] expect(actual).to(be_a(type(None)))