def _match(self, load): expect(load).to(be_a(client.models.TrafficLoad)) if (load.burst_size): expect(load.burst_size).to(be_above(0)) expect(load.burst_size).to(be_below(65536)) expect(load.rate).not_to(be_none) expect(load.rate.period).not_to(be_none) expect(load.rate.value).to(be_above(0)) expect(load.units).not_to(be_empty) return True, ['is valid traffic load']
def test_program_credential(): # get an existing program response = client.get('/programs', headers=AUTHENTICATED_HEADER) programs = json.loads(response.data)['programs'] expect(len(programs)).to(be_above(1)) selected_program = programs[0] response = client.get('/programs/{}/credentials'.format( selected_program['program_id']), headers=AUTHENTICATED_HEADER) program_credential = json.loads(response.data) expect(program_credential['program_id']).to( equal(selected_program['program_id'])) expect(len(program_credential['credentials'])).to(be_above(0))
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 _match(self, stats): expect(stats.summary).not_to(be_none) expect(stats.units).not_to(be_none) if stats.summary.min: expect(stats.summary.max).to(be_above_or_equal(stats.summary.min)) # Work around jitter_ipdv stat, which can be negative if stats.summary.min > 0: expect(stats.summary.total).to(be_above(0)) expect(stats.summary.max).to(be_above(0)) if stats.summary.min != stats.summary.max: expect(stats.summary.std_dev).to(be_above_or_equal(0)) return True, ['is valid non zero summary statistic']
def test_word_list(self): """Tests that the json decoder returns a list of words""" words = NetworkManager.words_from_json(self, self.sample_json) expect(len(words)).to(be_above(0)) for word in words: expect(word).to(be_a(Word))
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.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']
async def test_advance_target(self, *args): with asynctest.patch.object(Service, 'get_by_id') as get_by_id_mock: with asynctest.patch.object(Service, 'update') as update_mock: mock_id = 'some-value' mock_db = MagicMock() mock_service = { 'targets': [], } get_by_id_mock.return_value = mock_service await Service.advance_target(mock_id, mock_db) update_mock.assert_not_awaited() mock_service = { 'targets': ['some-value', 'some-value'], 'cur_target_index': 0 } get_by_id_mock.return_value = mock_service await Service.advance_target(mock_id, mock_db) update_mock.assert_called() expect(update_mock.call_args[0][0]).to(equal(mock_id)) expect(update_mock.call_args[0][1]['cur_target_index']).to( be_above(mock_service['cur_target_index'])) expect(update_mock.call_args[0][2]).to(equal(mock_db)) mock_service = { 'targets': ['some-value', 'some-value'], 'cur_target_index': 1 } get_by_id_mock.return_value = mock_service await Service.advance_target(mock_id, mock_db) update_mock.assert_called() expect(update_mock.call_args[0][0]).to(equal(mock_id)) expect(update_mock.call_args[0][1]['cur_target_index']).to( be_below(mock_service['cur_target_index'])) expect(update_mock.call_args[0][2]).to(equal(mock_db))
def _match(self, profile): expect(profile).to(be_a(client.models.TvlpProfileNetwork)) expect(profile.series).not_to(be_empty) for conf in profile.series: expect(conf).to(be_a(client.models.TvlpProfileNetworkSeries)) expect(conf.length).not_to(be_none) expect(conf.length).to(be_above(0)) expect(conf.config).to(be_a(client.models.NetworkGeneratorConfig)) return True, ['is valid Network TVLP profile']
def _match(self, profile): expect(profile).to(be_a(client.models.TvlpProfilePacket)) expect(profile.series).not_to(be_empty) for conf in profile.series: expect(conf).to(be_a(client.models.TvlpProfilePacketSeries)) expect(conf.length).not_to(be_none) expect(conf.length).to(be_above(0)) expect(conf.target_id).not_to(be_none) expect(conf.config).to(be_a(client.models.PacketGeneratorConfig)) return True, ['is valid Packet TVLP profile']
def _match(self, capture): expect(capture).to(be_a(client.models.PacketCapture)) expect(capture.id).not_to(be_empty) expect(capture.source_id).not_to(be_empty) expect(capture.active).not_to(be_none) expect(capture.config).to(be_a(client.models.PacketCaptureConfig)) expect(capture.config.mode).not_to(be_empty) expect(capture.config.buffer_wrap).not_to(be_none) expect(capture.config.buffer_size).to(be_above(0)) return True, ['is valid packet capture']
def test_get_program_by_provider(): response = client.get('/providers', headers=AUTHENTICATED_HEADER) expect(response.status_code).to(equal(200)) selected_provider = json.loads(response.data)['providers'][0] response = client.get('/providers/{}/programs'.format( selected_provider['provider_id']), headers=AUTHENTICATED_HEADER) expect(response.status_code).to(equal(200)) provider = json.loads(response.data) expect(len(provider['programs'])).to(be_above(0))
def _match(self, definition): expect(definition).to(be_a(client.models.TrafficDefinition)) expect(definition.packet).to(be_valid_traffic_packet_template) expect(definition.length).to(be_valid_traffic_length) if (definition.signature): expect(definition.signature).to( be_a(client.models.SpirentSignature)) if (definition.weight): expect(definition.weight).to(be_above(0)) return True, ['is valid traffic definition']
def test_program_crud_ops(): # get an existing program response = client.get('/programs', headers=AUTHENTICATED_HEADER) programs = json.loads(response.data)['programs'] expect(len(programs)).to(be_above(1)) selected_program = programs[0] del (selected_program['program_id']) # attempt to post the data response = client.post('/programs', headers=AUTHENTICATED_HEADER, data=json.dumps(selected_program)) # will initally fail due to validation rules expect(response.status_code).to(equal(400)) # change fields to integer selected_program['program_length_hours'] = 0 selected_program['program_length_weeks'] = 0 # will now successfully load response = client.post('/programs', headers=AUTHENTICATED_HEADER, data=json.dumps(selected_program)) expect(response.status_code).to(equal(201)) # get the program by it's id expected_program = json.loads(response.data) response = client.get('/programs/{}'.format( expected_program['program_id']), headers=AUTHENTICATED_HEADER) expect(response.status_code).to(equal(200)) actual_program = json.loads(response.data) expect(expected_program['program_id']).to( equal(actual_program['program_id'])) # update the program updated_program = copy.deepcopy(expected_program) del (updated_program['program_id']) updated_program['program_length_hours'] = 80 updated_program['program_length_weeks'] = 2 response = client.put('/programs/{}'.format( expected_program['program_id']), headers=AUTHENTICATED_HEADER, data=json.dumps(updated_program)) expect(response.status_code).to(equal(201)) updated_program = json.loads(response.data) expect(updated_program['program_length_hours']).to(equal(80)) expect(updated_program['program_length_weeks']).to(equal(2)) # delete the program response = client.delete('/programs/{}'.format( updated_program['program_id']), headers=AUTHENTICATED_HEADER) expect(response.status_code).to(equal(200))
def validate_optiona_fields(): schema = os.path.join(TEST_SCHEMA_PATH, 'schema_optional.json') validator = Validator(schema) # validate a known good document result = validator.validate(TEST_DATA) expect(len(result)).to(equal(0)) # validate a bad document result = validator.validate(BAD_TEST_DATA) expect(len(result)).to(be_above(0))
def test_retries_exception_of_child_class(self): calls = 0 def func(): nonlocal calls calls += 1 raise SonOfSpamException("intentional") try: call_with_exception_tolerance(func=func, tolerate=SpamException, timeout=0.01, throttle=0) except SonOfSpamException: pass # expected expect(calls).to(be_above(1))
def test_tolerates_last_type_in_given_sequence(self): iterations = 0 def attempt(): nonlocal iterations iterations += 1 raise EggsException() try: call_with_exception_tolerance( func=attempt, tolerate=[SpamException, EggsException], timeout=0.05, throttle=0) except EggsException: pass expect(iterations).to(be_above(1))
def test_tolerates_child_of_member_in_given_sequence(self): iterations = 0 def attempt(): nonlocal iterations iterations += 1 raise SonOfSpamException() try: call_with_exception_tolerance(func=attempt, tolerate=(SpamException, EggsException), timeout=0.05, throttle=0) except SonOfSpamException: pass expect(iterations).to(be_above(1))
def test_credential_crud_ops(): # get an existing credential response = client.get('/credentials', headers=AUTHENTICATED_HEADER) credentials = json.loads(response.data)['credentials'] expect(len(credentials)).to(be_above(1)) selected_credential = credentials[0] del (selected_credential['credential_id']) # attempt to post the data response = client.post('/credentials', headers=AUTHENTICATED_HEADER, data=json.dumps(selected_credential)) expect(response.status_code).to(equal(201)) # get the credential by it's id expected_credential = json.loads(response.data) response = client.get('/credentials/{}'.format( expected_credential['credential_id']), headers=AUTHENTICATED_HEADER) expect(response.status_code).to(equal(200)) actual_provider = json.loads(response.data) expect(expected_credential['credential_id']).to( equal(actual_provider['credential_id'])) # update the credential updated_credential = copy.deepcopy(expected_credential) del (updated_credential['credential_id']) updated_credential['credential_name'] = 'A New Credential' updated_credential['language'] = 'Sprench' response = client.put('/credentials/{}'.format( expected_credential['credential_id']), headers=AUTHENTICATED_HEADER, data=json.dumps(updated_credential)) expect(response.status_code).to(equal(201)) updated_credential = json.loads(response.data) expect(updated_credential['credential_name']).to( equal('A New Credential')) expect(updated_credential['language']).to(equal('Sprench')) # delete the credential response = client.delete('/credentials/{}'.format( updated_credential['credential_id']), headers=AUTHENTICATED_HEADER) expect(response.status_code).to(equal(200))
def test_provider_crud_ops(): # get an existing provider response = client.get('/providers', headers=AUTHENTICATED_HEADER) providers = json.loads(response.data)['providers'] expect(len(providers)).to(be_above(1)) selected_provider = providers[0] del (selected_provider['provider_id']) # attempt to post the data response = client.post('/providers', headers=AUTHENTICATED_HEADER, data=json.dumps(selected_provider)) expect(response.status_code).to(equal(201)) # get the provider by it's id expected_provider = json.loads(response.data) response = client.get('/providers/{}'.format( expected_provider['provider_id']), headers=AUTHENTICATED_HEADER) expect(response.status_code).to(equal(200)) actual_provider = json.loads(response.data) expect(expected_provider['provider_id']).to( equal(actual_provider['provider_id'])) # update the program updated_provider = copy.deepcopy(expected_provider) del (updated_provider['provider_id']) updated_provider['provider_name'] = 'A Learning Institution' updated_provider['year_incorporated'] = 1776 response = client.put('/providers/{}'.format( expected_provider['provider_id']), headers=AUTHENTICATED_HEADER, data=json.dumps(updated_provider)) expect(response.status_code).to(equal(201)) updated_provider = json.loads(response.data) expect(updated_provider['provider_name']).to( equal('A Learning Institution')) expect(updated_provider['year_incorporated']).to(equal(1776)) # delete the provider response = client.delete('/providers/{}'.format( updated_provider['provider_id']), headers=AUTHENTICATED_HEADER) expect(response.status_code).to(equal(200))
def test_participant_crud_ops(): # get an existing participant response = client.get('/participants', headers=AUTHENTICATED_HEADER) participants = json.loads(response.data)['participants'] expect(len(participants)).to(be_above(1)) selected_participant = participants[0] selected_participant['participant_id'] = 20000 # attempt to post the data response = client.post('/participants', headers=AUTHENTICATED_HEADER, data=json.dumps(selected_participant)) expect(response.status_code).to(equal(201)) # get the participant by their id expected_participant = json.loads(response.data) response = client.get('/participants/{}'.format( expected_participant['participant_id']), headers=AUTHENTICATED_HEADER) expect(response.status_code).to(equal(200)) actual_participant = json.loads(response.data) expect(expected_participant['participant_id']).to( equal(actual_participant['participant_id'])) # update the participant updated_participant = copy.deepcopy(expected_participant) del (updated_participant['participant_id']) updated_participant['exit_type'] = 'A New Exit Type' updated_participant['exit_date'] = '2019/01/10' response = client.put('/participants/{}'.format( expected_participant['participant_id']), headers=AUTHENTICATED_HEADER, data=json.dumps(updated_participant)) expect(response.status_code).to(equal(201)) updated_participant = json.loads(response.data) expect(updated_participant['exit_type']).to(equal('A New Exit Type')) expect(updated_participant['exit_date']).to(equal('2019/01/10')) # delete the participant response = client.delete('/participants/{}'.format( updated_participant['participant_id']), headers=AUTHENTICATED_HEADER) expect(response.status_code).to(equal(200))
def test_wait_for_retries(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) last_check = calls sleep(2 * throttle) expect(calls).to(be_above(last_check))
def _match(self, length): expect(length).to(be_a(client.models.TrafficLength)) has_property = False if (length.fixed): expect(length.fixed).to(be_above_or_equal(64)) has_property = True if (length.list): expect(length.list).not_to(be_empty) for l in length.list: expect(l).to(be_above_or_equal(64)) has_property = True if (length.sequence): expect(length.sequence).to( be_a(client.models.TrafficLengthSequence)) expect(length.sequence.count).to(be_above(0)) expect(length.sequence.start).to(be_above_or_equal(64)) has_property = True expect(has_property).to(be_true) return True, ['is valid traffic length']
def test_retries_up_to_specified_timeout(self): calls = 0 timeout = 5 throttle = 0.01 def func(): nonlocal calls calls += 1 raise SpamException("intentional") def do_it(): call_with_exception_tolerance(func=func, tolerate=SpamException, timeout=timeout, throttle=throttle) tc = TimeController(target=do_it) tc.start() tc.advance(seconds=timeout - 0.01) last_check = calls sleep(2 * throttle) expect(calls).to(be_above(last_check))
def test_all_apis(self, client, token_generator): # Common headers go in this dict headers = {'content-type': 'application/json', 'authorization': f'bearer {token_generator.get_token(client)}'} # Create users, and clients user_ids = post_users(USERS, client, token_generator.get_token(client)) client_ids = self._post_clients(client, user_ids, token_generator) # Create roles role_ids = [] for role in ROLES: response = client.post( '/roles', data=json.dumps(role), headers=headers) expect(response.status_code).to(equal(201)) role_ids.append(response.json['response'][0]['id']) # Assign clients to users and roles to client for i, client_id in enumerate(client_ids): request_body = { 'user_id': user_ids[i], 'roles': role_ids } response = client.patch( '/clients/{}'.format(client_id), data=json.dumps(request_body), headers=headers) expect(response.status_code).to(equal(200)) # Ensure that clients actually have roles, users, and other crucial fields for client_id in client_ids: response = client.get( '/clients/{}'.format(client_id), headers=headers) result = response.json['response'] expect(result['id']).to(equal(client_id)) expect(result['client_id_issued_at']).to(be_above(0)) expect(user_ids).to(contain(result['user_id'])) expect(len(result['roles'])).to(equal(len(role_ids))) self._cleanup(client, token_generator, user_ids=user_ids, role_ids=role_ids)
from mamba import description, it from expects import expect, have_length, be_above import os import infrastructure with description(infrastructure.AnchoreClient) as self: with it('retrieves images with stop policy results'): user = os.environ['ANCHORE_CLI_USER'] password = os.environ['ANCHORE_CLI_PASS'] url = os.environ['ANCHORE_CLI_URL'] client = infrastructure.AnchoreClient(user, password, url, True) result = client.get_images_with_policy_result('stop') expect(result).to(have_length(be_above(1)))
def test_get_all_programs(): response = client.get('/programs', headers=AUTHENTICATED_HEADER) expect(response.status_code).to(equal(200)) data = json.loads(response.data) expect(len(data['programs'])).to(be_above(1))
def test_gt_returns_false(self): expect(EmptyFake()).not_to(be_above(42))
from mamba import description, it, before from expects import expect, be_above, have_key from patchscheme.scheme import Scheme import patchscheme.strategies as st from datetime import datetime class PatchPerson(Scheme): created_at = st.Suppress() updated_at = st.Force(datetime.now) with description(PatchPerson) as self: with before.each: self.stored = dict( created_at=datetime(2019, 9, 27, 0, 0), updated_at=datetime(2019, 9, 27, 0, 0) ) self.payload = {} self.payload.update(self.stored) with it('should patch using Force and Suppress'): now = datetime.now() patch = PatchPerson(self.stored, self.payload).map() expect(patch).not_to(have_key('created_at')) expect(patch).to(have_key('updated_at')) expect(patch['updated_at']).to(be_above(now))
from mamba import description, it, context, before from expects import expect, have_length, be_above, have_key, equal, be_none import securecscc with description(securecscc.SysdigSecureClient) as self: with before.all: self.client = securecscc.SysdigSecureClient(securecscc.Credentials()) with context('when retrieving events happened on last minute'): with before.all: self.events = self.client.events_happened_on_last_minute() with it('returns more than 0 events'): expect(self.events).to(have_length(be_above(0))) with it('event contains an id'): expect(self.events[0]).to(have_key('id')) with it('event contains the timestamp'): expect(self.events[0]).to(have_key('timestamp')) with it('retrieves a policy from its id'): policy_id = 3120 policy_name = 'Disallowed SSH Connection' policy = self.client.find_policy_by_id(policy_id) expect(policy).to(equal(policy_name))
def test_gt(self): hicard = Card(CardFace.King, CardSuit.Hearts) locard = Card(CardFace.Two, CardSuit.Hearts) expect(hicard).to(be_above(locard))