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 test_should_return_a_lru_cache_if_flush_interval_is_negative(self): delta = datetime.timedelta(seconds=-1) should_be_ttl = [ lambda: caches.create( caches.CheckOptions(num_entries=1, flush_interval=delta), ), lambda: caches.create( caches.ReportOptions(num_entries=1, flush_interval=delta)), ] for testf in should_be_ttl: sync_cache = testf() expect(sync_cache).to(be_a(caches.LockedObject)) with sync_cache as cache: expect(cache).to(be_a(caches.DequeOutLRUCache))
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 it_should_return_an_sid(self): expect(self.result).to(have_key('short_url')) short_url = self.result['short_url'] expect(short_url).to(be_a(str)) expect(self.result).to(equal({ 'success': True, 'short_url': short_url, 'url': self.url }))
def test_specifies_fullscreen_option(self): Browser() spy = self.fake_webdriver.driver_spy expect(spy).not_to(equal(None)) expect(spy.call_history).to(have_length(1)) _, kwargs = spy.call_history[0] expect(kwargs.keys()).to(contain("chrome_options")) opts = kwargs["chrome_options"] expect(opts).to(be_a(webdriver.chrome.options.Options)) expect(opts.arguments).to(contain("start-fullscreen"))
def _match(self, stats): expect(stats).to(be_a(client.models.NetworkGeneratorStats)) expect(stats.ops_target).to(be_a(int)) expect(stats.ops_actual).to(be_a(int)) expect(stats.bytes_target).to(be_a(int)) expect(stats.bytes_actual).to(be_a(int)) expect(stats.io_errors).to(be_a(int)) expect(stats.latency_total).to(be_a(int)) return True, ['is valid Network Generator Stats']
def test_request_uuid_is_a_uuid(self): published_uuid = None def subscriber(request_uuid, **kwargs): nonlocal published_uuid published_uuid = request_uuid EventBroker.subscribe(event=TestEvent.http_request_sent, func=subscriber) HttpClient().get("http://spam.spam") expect(published_uuid).to(be_a(uuid.UUID))
def test_times_out_after_limit(self): limit = 42 self.context.set_env(RUN_ALL_TIMEOUT=limit) tc = self.context.create_time_controller(target=self.exercise_sut) tc.start() sleep(0.05) tc.advance(seconds=limit + 1) sleep(0.05) self.pretend_process_is_stopped() expect(tc.exception_caught).to(be_a(TimeoutError)) tc.join()
def test_configuration_factory(self): """Test API configuration factory. """ config = ConfigurationFactory.get_config('TEST') expect(config).to(be_a(object)) expect(config.get_api_name()).to_not(equal('Unknown')) expect(config.get_api_version()).to_not(equal('Unknown')) expect(config.get_settings()).to(have_key('API_VERSION')) expect(config.get_settings()).to(have_key('API_NAME'))
def test_valid_analyze_url_returned(self): with HTTMock(self.mock.by_id): survey = self.survey.by_id(survey_id=self.survey_id) expect(survey).to(be_a(dict)) expect(survey).to(have_key('analyze_url')) analyze_url = furl(survey["analyze_url"]) expect(survey["analyze_url"]).to(be_url) expect(analyze_url.path.segments[0]).to(equal("analyze"))
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')]))
def _match(self, counters): expect(counters).to(be_a(client.models.PacketAnalyzerFlowCounters)) expect(counters.frame_count).not_to(be_none) # Check optional summary statistics if counters.frame_count > 0: if counters.frame_length: expect(counters.frame_length).to( be_valid_non_zero_summary_statistic) if counters.latency: expect( counters.latency).to(be_valid_non_zero_summary_statistic) if counters.sequence: total = (counters.sequence.duplicate + counters.sequence.late + counters.sequence.reordered + counters.sequence.in_order) expect(total).to(equal(counters.frame_count)) if counters.headers: expect(counters.headers).not_to(be_empty) for header in counters.headers: expect(header).to( be_a(client.models.PacketAnalyzerFlowHeader)) if counters.frame_count > 1: if counters.interarrival: expect(counters.interarrival).to( be_valid_non_zero_summary_statistic) if counters.jitter_ipdv: expect(counters.jitter_ipdv).to( be_valid_non_zero_summary_statistic) if counters.jitter_rfc: expect(counters.jitter_rfc).to( be_valid_non_zero_summary_statistic) # 0 < timestamp_first <= timestamp_last expect(counters.timestamp_last).to( be_above(counters.timestamp_first)) duration = counters.timestamp_last - counters.timestamp_first expect(duration).to(be_above_or_equal(datetime.timedelta(0))) return True, ['is valid packet analyzer flow counter']
def test_format_documents(self, *args): mock_documents = [{ '_id': { '$oid': 'some-value' } }, { '_id': { '$oid': 'some-value' } }] formatted = DB.format_documents(mock_documents) expect(args[0].call_count).to(equal(len(mock_documents))) expect(formatted).to(be_a(list))
def _match(self, stats): expect(stats).to(be_a(client.models.MemoryGeneratorStats)) expect(stats.ops_target).to(be_a(int)) expect(stats.ops_actual).to(be_a(int)) expect(stats.bytes_target).to(be_a(int)) expect(stats.bytes_actual).to(be_a(int)) expect(stats.latency).to(be_a(int)) return True, ['is valid Memory Generator Stats']
def _match(self, duration): expect(duration).to(be_a(client.models.TrafficDuration)) has_property = False if (duration.continuous): has_property = True if (duration.frames): expect(duration.frames).to(be_above(0)) has_property = True if (duration.time): expect(duration.time.value).to(be_above(0)) expect(duration.time.units).not_to(be_empty) has_property = True expect(has_property).to(be_true) return True, ['is valid traffic duration']
def test_times_out_when_suites_remain_in_queue_after_expiry(self): limit = 42 self.context.set_env(MAX_PARALLEL_SUITES=1, RUN_ALL_TIMEOUT=limit) bogus_path = self.context.os.path.join("some", "where") self.context.fs.create_dir(bogus_path) for bogus_script in ("something.py", "or_other.py"): self.context.create_file( self.context.os.path.join(bogus_path, bogus_script)) tc = self.context.create_time_controller( target=partial(run_all, bogus_path)) tc.start() sleep(0.05) tc.advance(seconds=limit + 1) sleep(0.05) expect(tc.exception_caught).to(be_a(TimeoutError)) self.pretend_process_is_stopped() tc.join()
def test_wait_for_raises_timeout_error_if_timeout_exceeded(self): calls = 0 timeout = 5 throttle = 0.1 def func(): nonlocal calls calls += 1 return False def do_it(): wait_for(func=func, timeout=timeout, throttle=throttle) tc = TimeController(target=do_it) tc.start() tc.advance(seconds=timeout + 0.1) sleep(0.15) # Give the thread a chance to cycle expect(tc.exception_caught).to(be_a(TimeoutError))
async def test_create(self, *args): # with patch('cerberus.Validator') as validator_mock: with asynctest.patch.object(Service, 'check_exists') as check_exists_mock: mock_ctx = {'schema': {}, 'service_id': 'some-value'} mock_db = MagicMock() mock_db.insert_one = CoroutineMock() await RequestValidator.create(mock_ctx, mock_db, mock_db) mock_db.insert_one.assert_awaited_with(mock_ctx) check_exists_mock.assert_called() mock_ctx = {'schema': {'type': 'some-value'}} try: await RequestValidator.create(mock_ctx, mock_db, mock_db) expect(True).to(equal(False)) except Exception as err: expect(err.args[0]).to(be_a(object)) expect(err.args[0]).to( have_keys('message', 'context', 'status_code'))
def _match(self, digest): expect(digest).to(be_a(client.models.PacketAnalyzerFlowDigests)) # All properties are optional if digest.frame_length: expect(digest.frame_length).to( be_valid_packet_analyzer_flow_digest_result) if digest.interarrival: expect(digest.interarrival).to( be_valid_packet_analyzer_flow_digest_result) if digest.jitter_ipdv: expect(digest.jitter_ipdv).to( be_valid_packet_analyzer_flow_digest_result) if digest.jitter_rfc: expect(digest.jitter_rfc).to( be_valid_packet_analyzer_flow_digest_result) if digest.latency: expect( digest.latency).to(be_valid_packet_analyzer_flow_digest_result) if digest.sequence_run_length: expect(digest.sequence_run_length).to( be_valid_packet_analyzer_flow_digest_result) return True, ['is valid packet analyzer flow digest']
def _match(self, source): expect(source).to(be_a(client.models.TimeSource)) expect(source.id).not_to(be_empty) expect(source.stats).to(be_a(client.models.TimeSourceStats)) if source.kind == 'ntp': expect(source.config).to(be_a(client.models.TimeSourceConfig)) ntp = source.config.ntp expect(ntp).to(be_a(client.models.TimeSourceConfigNtp)) expect(ntp.hostname).not_to(be_empty) expect(source.stats.ntp).to(be_a(client.models.TimeSourceStatsNtp)) return True, ['is valid ntp source'] elif source.kind == 'system': expect(source.stats.system).to( be_a(client.models.TimeSourceStatsSystem)) return True, ['is valid system source'] else: return False, ['is invalid source']
from expects import expect, raise_error, be_a from primestg.report import Report from primestg.message import MessageS with description('Report'): with it('raise an error if isn\'t provided a file, basestring or ' 'MessageS'): def callback(): Report([]) error = 'must be file or basestring with XML or a MessageS' expect(callback).to(raise_error(TypeError, error)) with it('can parse an XML string'): report = Report('<xml><tag attr="var"/></xml>') expect(report.message).to(be_a(MessageS)) with it('can parse an XML file'): with open('spec/data/CIR4621247027_0_S02_0_20150901111051') as f: report = Report(f) expect(report.message).to(be_a(MessageS)) with it('accepts a MessageS directly'): with open('spec/data/CIR4621247027_0_S04_0_20150901110412') as f: message_s = MessageS(f) report = Report(message_s) expect(report.message).to(be_a(MessageS))
def test_get_single_survey_by_id(self): with HTTMock(self.mock.by_id): survey = self.survey.by_id(survey_id=self.survey_id) expect(survey).to(be_a(dict)) expect(survey).to(have_keys('id', 'title', 'analyze_url'))
def test_publishes_report_content(self): self.publish_results() content = self.published_kwargs["report_content"] expect(content).to(be_a(str)) expect(content).not_to(be_empty)
def check_apartments(subject): expect(subject).to(be_a(list)) expect(subject).to(have_len(2)) for rec in subject: expect(rec).to(have_keys('area', 'lat', 'lon', 'rooms'))
decorated_function = Spy().decorated_function expect(on_failure('some_integration')(decorated_function)).to( be(decorated_function)) with it('doesn\'t call the decorated function'): decorated_function = Spy().decorated_function on_failure('some_integration')(decorated_function) expect(decorated_function).to_not(have_been_called) with it('aborts the program if it references a non-existent integration' ): expect(lambda: integrations._create('bogus_name')).to( raise_error(SystemExit)) with it('has the (convenient) side effect of registering the integration name with a subject' ): decorated_function = Spy().decorated_function on_failure('some_integration')(decorated_function) expect(list(integrations.registered_integrations.keys())).to( contain_exactly(decorated_function.__name__)) for setup_function in integrations.registered_integrations: for subject in integrations.registered_integrations[ setup_function]['integrations']: expect(subject).to(be_a(rx.subjects.Subject))
def test_can_create_instance_with_no_dependencies(): container = Container() container.register(MessageWriter, StdoutMessageWriter) expect(container.resolve(MessageWriter)).to(be_a(StdoutMessageWriter))
def test_yields_an_empty_fake(self): with empty_context_manager() as actual: expect(actual).to(be_a(EmptyFake))
'some_integration': some_integration_instance } with after.each: integrations.registered_integrations = {} integration_config.loaded_integrations = {} with it('returns the decorated function as is'): decorated_function = Spy().decorated_function expect(on_failure('some_integration')(decorated_function)).to(be(decorated_function)) with it('doesn\'t call the decorated function'): decorated_function = Spy().decorated_function on_failure('some_integration')(decorated_function) expect(decorated_function).to_not(have_been_called) with it('has the (convenient) side effect of registering the integration name with a subject'): decorated_function = Spy().decorated_function on_failure('some_integration')(decorated_function) expect(list(integrations.registered_integrations.keys())).to(contain_exactly(decorated_function.__name__)) for setup_function in integrations.registered_integrations: for subject in integrations.registered_integrations[setup_function]['integrations']: expect(subject).to(be_a(rx.subjects.Subject))
def _match(self, conf): expect(conf).to(be_a(client.models.MemoryGeneratorConfig)) return True, ['is valid Memory Generator Configuration']
expect(self.method).to(have_been_called_with(self.arg1, self.arg2)) with it('should pass if called with keyword args'): self.method(**self.kwargs) expect(self.method).to(have_been_called_with(**self.kwargs)) with it('should pass if called with positional and keyword args'): self.method(self.arg1, self.arg2, **self.kwargs) expect(self.method).to(have_been_called_with(self.arg1, self.arg2, **self.kwargs)) with it('passes if called with positional arg matching matcher'): self.method(self.arg1) expect(self.method).to(have_been_called_with(be_a(type(self.arg1)))) with it('passes if called with multiple positional args matching matchers'): self.method(self.arg1, self.arg2) expect(self.method).to(have_been_called_with( be_a(type(self.arg1)), be_a(type(self.arg2)))) with it('passes if called with keyword args matching matchers'): self.method(**self.kwargs) expect(self.method).to(have_been_called_with( **{k: be_a(type(v)) for k,v in self.kwargs.items()})) with it('should fail if not called with positional arg'):
def it_should_raise_user_not_found(self): expect(self.exception).to(be_a(NotFoundException))
from expects import expect, raise_error, be_a from pysellus.interfaces import AbstractIntegration with description('the interfaces module'): with context('exposes an abstract `AbstractIntegration` class which'): with before.all: class WrongIntegration(AbstractIntegration): pass class GoodIntegration(AbstractIntegration): def on_next(self): pass self.WrongIntegration = WrongIntegration self.GoodIntegration = GoodIntegration with it('requires you to implement an `on_next` handler'): expect(lambda: self.WrongIntegration()).to(raise_error( TypeError, 'Can\'t instantiate abstract class WrongIntegration with abstract methods on_next' )) expect(lambda: self.GoodIntegration()).to_not(raise_error( TypeError, 'Can\'t instantiate abstract class GoodIntegration with abstract methods on_next' )) with it('exposes a `get_subject` method which returns an rx Subject'): expect(self.GoodIntegration().get_subject()).to(be_a(rx.subjects.Subject))
module = _load_module(WITH_FOCUS_PATH) examples = loader.Loader().load_examples_from(module) expect(examples).to(have_length(2)) expect(examples[1].has_tag('focus')).to(be_true) expect(examples[1].has_tag('integration')).to(be_true) with context('when a pending decorator loaded'): with it('mark example as pending'): module = _load_module(PENDING_DECORATOR_PATH) examples = loader.Loader().load_examples_from(module) expect(examples).to(have_length(1)) expect(examples[0].examples[0]).to(be_a(example.PendingExample)) with it('marks example group as pending'): module = _load_module(PENDING_DECORATOR_PATH) examples = loader.Loader().load_examples_from(module) expect(examples).to(have_length(1)) expect(examples[0].examples[1]).to(be_a(example_group.PendingExampleGroup)) with context('when a pending decorator loaded_as_root'): with it('mark inner examples as pending'): module = _load_module(PENDING_DECORATOR_AS_ROOT_PATH) examples = loader.Loader().load_examples_from(module)
def _match(self, stack): expect(stack).to(be_a(client.models.Stack)) expect(stack.id).not_to(be_empty) expect(stack.stats).not_to(be_none) return True, ['is valid stack']
def test_sets_fixed_time_if_none_specified(self): expect(FakeDatetime().fixed_time).to(be_a(datetime))
from expects import expect, raise_error, be_a from primestg.message import MessageS from lxml.objectify import ObjectifiedElement from lxml.etree import XMLSyntaxError with description('MessageS'): with it('raise an error if isn\'t provided an XML'): def callback(): MessageS('foo bar') expect(callback).to(raise_error(XMLSyntaxError)) with it('can parse an XML string'): message_s = MessageS('<xml><tag attr="var"/></xml>') expect(message_s.objectified).to(be_a(ObjectifiedElement)) with it('can parse an XML file'): filename = 'spec/data/CIR4621247027_0_S02_0_20150901111051' with open(filename) as data_file: message_s = MessageS(data_file) expect(message_s.objectified).to(be_a(ObjectifiedElement))
def _match(self, info): expect(info).to(be_a(client.models.MemoryInfoResult)) expect(info.free_memory).to(be_a(int)) expect(info.total_memory).to(be_a(int)) return True, ['is valid Memory Info']
# author: Stephan Becque (https://github.com/sjbecque) from expects import expect, equal, be_a, be from tetris.src.cube import Cube from tetris.src.cube_sets.cube_set import CubeSet from tetris.src.cube_sets.stones import Stones with describe(Stones) as self: with it('its factory method produces a Stones object'): expect(Stones.c([1, 1])).to(be_a(Stones)) with describe('process_completed_rows') as self: with it('removes all full rows and moves all stones above it down'): subject = Stones.c(\ [2,1],\ [1,2], [2,2],\ [1,3],\ [1,4], [2,4],\ [1,5]\ ) expect(subject.process_completed_rows(2, 5)).to( equal(Stones.c([2, 3], [1, 4], [1, 5])))
def _match(self, g7r): expect(g7r).to(be_a(client.models.MemoryGenerator)) expect(g7r.id).not_to(be_empty) expect(g7r.running).to(be_a(bool)) expect(g7r.config).to(be_a(client.models.MemoryGeneratorConfig)) return True, ['is valid Memory Generator']
def test_can_register_a_concrete_type(): container = Container() container.register(StdoutMessageWriter) expect(container.resolve(StdoutMessageWriter)).to( be_a(StdoutMessageWriter))
def test_constructor_should_set_up_a_default_deque(self): c = caches.DequeOutTTLCache(_TEST_NUM_ENTRIES, _TEST_TTL) expect(c.out_deque).to(be_a(collections.deque))
def it_should_raise_StreamNotFound(self): expect(self.exception).to(be_a(NotFoundException))