def test_get_properties(self): dpe = UnityDpe('dpe', cli=t_rest()) assert_that(dpe.existed, equal_to(True)) assert_that(dpe.health, instance_of(UnityHealth)) assert_that(dpe.needs_replacement, equal_to(False)) assert_that(dpe.slot_number, equal_to(0)) assert_that(dpe.name, equal_to('DPE')) assert_that(dpe.manufacturer, equal_to('')) assert_that(dpe.model, equal_to('OBERON 25 DRIVE CHASSIS')) assert_that(dpe.emc_part_number, equal_to('100-542-901-05')) assert_that(dpe.emc_serial_number, equal_to('CF2CV150500005')) assert_that(dpe.vendor_part_number, equal_to('')) assert_that(dpe.vendor_serial_number, equal_to('')) assert_that(dpe.bus_id, equal_to(0)) assert_that(dpe.current_power, equal_to(429)) assert_that(dpe.avg_power, equal_to(397)) assert_that(dpe.max_power, equal_to(429)) assert_that(dpe.current_temperature, equal_to(26)) assert_that(dpe.avg_temperature, equal_to(26)) assert_that(dpe.max_temperature, equal_to(26)) assert_that(dpe.current_speed, equal_to(12000000000)) assert_that(dpe.max_speed, equal_to(12000000000)) assert_that(dpe.parent_system, instance_of(UnitySystem)) assert_that(dpe.enclosure_type, equal_to(EnclosureTypeEnum.MIRANDA_12G_SAS_DPE)) assert_that(dpe.drive_types, only_contains(DiskTypeEnum.SAS, DiskTypeEnum.SAS_FLASH_2))
def test_error(flockmock, exitmock, truncatemock, atexitmock, logmock): # When we attempt to acquire a lock on 'PID_FILE', the acquisition # fails, Log issue and exit. dut.PID_FILE = "test.pid" if (os.path.exists(dut.PID_FILE)): # Make sure file does not exist as a precondition os.remove(dut.PID_FILE) # Arrange error return from locking mock flockmock.side_effect = IOError exitmock.side_effect = SystemExit try: dut.prevent_duplicate(dut.PID_FILE) except SystemExit: pass # Expected from exitmock # Always expect to interact with flock() flockmock.assert_called_once_with(match_equality(instance_of(file)), match_equality( fcntl.LOCK_EX | fcntl.LOCK_NB)) # Assertions to prove we took the un-happy path exitmock.assert_called_once_with(-1) logmock.return_value.error.assert_called_once_with( match_equality(instance_of(str))) # The road not taken assert_that(truncatemock.call_count, equal_to(0)) assert_that(atexitmock.call_count, equal_to(0)) assert(os.path.exists(dut.PID_FILE)) os.remove(dut.PID_FILE)
def test_success(flockmock, exitmock, truncatemock, atexitmock, logmock): # When we attempt to acquire a lock on 'PID_FILE', the acquisition # suceeds, file is created, and we arrange for it to be # removed. dut.PID_FILE = "test.pid" if (os.path.exists(dut.PID_FILE)): # Make sure file does not exist as a precondition os.remove(dut.PID_FILE) dut.prevent_duplicate(dut.PID_FILE) # Always expect to interact with flock() flockmock.assert_called_once_with(match_equality(instance_of(file)), match_equality( fcntl.LOCK_EX | fcntl.LOCK_NB)) # The road not taken assert_that(exitmock.call_count, equal_to(0)) assert_that(logmock.return_value.error.call_count, equal_to(0)) # Assertions to prove we took the happy path truncatemock.assert_called_once_with( match_equality(instance_of(int)), match_equality(0)) atexitmock.assert_called_once_with( match_equality(dut.cleanup_pidfile), match_equality(instance_of(file))) assert(os.path.exists(dut.PID_FILE)) # Clean up os.remove(dut.PID_FILE)
def DebugInfo_test( app ): request_data = BuildRequest( filetype = 'python' ) assert_that( app.post_json( '/debug_info', request_data ).json, has_entry( 'completer', has_entries( { 'name': 'Python', 'items': contains( has_entries( { 'key': 'Python interpreter', 'value': instance_of( str ) } ), has_entries( { 'key': 'Python path', 'value': instance_of( str ) } ), has_entries( { 'key': 'Python version', 'value': instance_of( str ) } ), has_entries( { 'key': 'Jedi version', 'value': instance_of( str ) } ), has_entries( { 'key': 'Parso version', 'value': instance_of( str ) } ) ) } ) ) )
def DebugInfo_test( app ): request_data = BuildRequest( filetype = 'java' ) assert_that( app.post_json( '/debug_info', request_data ).json, has_entry( 'completer', has_entries( { 'name': 'Java', 'servers': contains( has_entries( { 'name': 'jdt.ls Java Language Server', 'is_running': instance_of( bool ), 'executable': instance_of( str ), 'pid': instance_of( int ), 'logfiles': contains( instance_of( str ), instance_of( str ) ), 'extras': contains( has_entries( { 'key': 'Startup Status', 'value': instance_of( str ) } ), has_entries( { 'key': 'Java Path', 'value': instance_of( str ) } ), has_entries( { 'key': 'Launcher Config.', 'value': instance_of( str ) } ), has_entries( { 'key': 'Project Directory', 'value': instance_of( str ) } ), has_entries( { 'key': 'Workspace Path', 'value': instance_of( str ) } ) ) } ) ) } ) ) )
def test_circle_shape_square(self): with self.shape_store.flushing(): self.shape_store.create(self.circle) self.shape_store.create(self.square) self.shape_store.create(self.shape) results = self.shape_store.search() assert_that(results, has_length(3)) assert_that( results, contains( self.shape, self.square, self.circle, ), ) assert_that( results, contains( is_(instance_of(Shape)), is_(instance_of(Square)), is_(instance_of(Circle)), ), ) assert_that( self.shape_store.search(doc_types=["circle", "shape"]), contains( self.shape, self.circle, ), )
def test_find(self): """ Find returns schema. """ schema = self.registry.find(DerivedSchema.MEDIA_TYPE) assert_that(schema, is_(instance_of(PubSubMessageCodec))) assert_that(schema.schema, is_(instance_of(DerivedSchema)))
def test_initiator_modify(self): initiator = UnityHostInitiator(cli=t_rest(), _id='HostInitiator_2') assert_that(initiator.parent_host, instance_of(UnityHost)) assert_that(initiator.parent_host.id, equal_to("Host_1")) host = UnityHost(cli=t_rest(), _id='Host_19') resp = initiator.modify(host=host) assert_that(resp.is_ok(), equal_to(True)) assert_that(initiator.parent_host, instance_of(UnityHost))
def test_add_not_exist_initiator_with_force(self): host = UnityHost(cli=t_rest(), _id='Host_9') wwn = "50:00:14:40:47:B0:0C:44:50:00:14:42:D0:0C:99:99" initiator = host.add_initiator(wwn, force_create=True) assert_that(initiator, instance_of(UnityHostInitiator)) assert_that(initiator.existed, equal_to(True)) assert_that(host.fc_host_initiators, instance_of(UnityHostInitiatorList))
def test_add_initiator_iscsi(self): host = UnityHost(cli=t_rest(), _id='Host_1') iqn = "iqn.1993-08.org.debian:01:a4f95ed19999" initiator = host.add_initiator(iqn) assert_that(initiator, instance_of(UnityHostInitiator)) assert_that(initiator.existed, equal_to(True)) assert_that(host.iscsi_host_initiators, instance_of(UnityHostInitiatorList))
def test_add_initiator(self): host = UnityHost(cli=t_rest(), _id='Host_9') wwn = "50:00:14:40:47:B0:0C:44:50:00:14:42:D0:0C:44:10" initiator = host.add_initiator(wwn) assert_that(initiator, instance_of(UnityHostInitiator)) assert_that(initiator.existed, equal_to(True)) assert_that(host.fc_host_initiators, instance_of(UnityHostInitiatorList))
def test_get_lun_with_host_access(self): unity = UnitySystem('10.109.22.101', 'admin', 'Password123!') lun = unity.get_lun(_id='sv_567') assert_that(lun.host_access, instance_of(UnityBlockHostAccessList)) access = lun.host_access[0] assert_that(access.access_mask, equal_to(HostLUNAccessEnum.PRODUCTION)) assert_that(access.host, instance_of(UnityHost)) assert_that(access.host.id, equal_to('Host_1'))
def test_get_sp(self): assert_that(len(self.vnx.get_sp()), equal_to(2)) assert_that(self.vnx.spa, instance_of(VNXStorageProcessor)) assert_that(self.vnx.spa.name, equal_to('A')) assert_that(self.vnx.spa.signature, equal_to(4022290)) assert_that(self.vnx.spb, instance_of(VNXStorageProcessor)) assert_that(self.vnx.spb.name, equal_to('B')) assert_that(self.vnx.spb.signature, equal_to(4022287))
def test_parse_types(self): rows = self._parse_excel("types.xls") assert_that(rows[1][1], instance_of(int)) assert_that(rows[1][2], instance_of(float)) assert_that(rows, contains( ["string", "int", "float"], ["foobar", 10, 10.5] ))
def test_get_initiator_by_name(self): unity = t_unity() wwn = "50:00:14:40:47:B0:0C:44:50:00:14:42:D0:0C:44:10" filtered = unity.get_initiator(initiator_id=wwn) assert_that(len(filtered), equal_to(1)) assert_that(filtered, instance_of(UnityHostInitiatorList)) initiator = filtered.first_item assert_that(initiator, instance_of(UnityHostInitiator)) assert_that(initiator.existed, equal_to(True)) assert_that(initiator.initiator_id, equal_to(wwn))
def test_command_routing(): with captured_callback() as cb: # UUT keeps the reference alive for CB handling # pylint: disable=unused-variable uut = RCICommandProcessor() cb("<test/>") pubmock.sendMessage.assert_called_once_with("command.test", element=match_equality(instance_of(ET.Element)), response=match_equality(instance_of(PutOnlyQueue)))
def test_get_properties(self): server = UnityNfsServer('nfs_2', t_rest()) assert_that(server.id, equal_to('nfs_2')) assert_that(server.nfs_v4_enabled, equal_to(True)) assert_that(server.is_secure_enabled, equal_to(False)) assert_that(server.is_extended_credentials_enabled, equal_to(False)) assert_that(server.nas_server, instance_of(UnityNasServer)) assert_that(server.file_interfaces, instance_of(UnityFileInterfaceList)) assert_that(str(server.credentials_cache_ttl), equal_to('0:15:00'))
def test_factory_telnet(): lock = mock.Mock() descriptor = SwitchDescriptor(hostname='hostname', model='dell10g', username='******', password='******', port=22) switch = dell10g.factory_telnet(descriptor, lock) assert_that(switch, instance_of(SwitchTransactional)) assert_that(switch.impl, instance_of(Dell10G)) assert_that(switch.impl.shell_factory, equal_to(TelnetClient)) assert_that(switch.lock, is_(lock)) assert_that(switch.switch_descriptor, is_(descriptor))
def is_message(self, sender=SENDER, recipients=RECIPIENTS, message=MESSAGE): return has_entries( { "mailfrom": sender, "message_data": message, "recipients": recipients, "message": instance_of(email.message.Message), "peer": contains("127.0.0.1", instance_of(int)), } )
def DebugInfo_test( app ): request_data = BuildRequest( filetype = 'javascript' ) assert_that( app.post_json( '/debug_info', request_data ).json, has_entry( 'completer', has_entries( { 'name': 'JavaScript', 'servers': contains( has_entries( { 'name': 'Tern', 'is_running': instance_of( bool ), 'executable': instance_of( str ), 'pid': instance_of( int ), 'address': instance_of( str ), 'port': instance_of( int ), 'logfiles': contains( instance_of( str ), instance_of( str ) ), 'extras': contains( has_entries( { 'key': 'configuration file', 'value': instance_of( str ) } ), has_entries( { 'key': 'working directory', 'value': instance_of( str ) } ) ), } ) ), 'items': empty() } ) ) )
def test_get_switch_by_descriptor(self): my_semaphore = mock.Mock() self.semaphore_mocks['hostname'] = my_semaphore switch = self.factory.get_switch_by_descriptor(SwitchDescriptor(model='test_model', hostname='hostname')) assert_that(switch, is_(instance_of(FlowControlSwitch))) assert_that(switch.wrapped_switch, is_(instance_of(_FakeSwitch))) assert_that(switch.lock, is_(my_semaphore)) assert_that(switch.wrapped_switch.switch_descriptor, is_(SwitchDescriptor(model='test_model', hostname='hostname')))
def test_create_mount_point_success(self): lun = VNXLun(name='l1', cli=t_cli()) m2 = lun.create_mount_point(name='m2') assert_that(lun.snapshot_mount_points, instance_of(VNXLunList)) assert_that(str(lun), contains_string('"VNXLunList": [')) for smp in lun.snapshot_mount_points: assert_that(smp, instance_of(VNXLun)) pl = smp.primary_lun assert_that(pl, instance_of(VNXLun)) assert_that(pl._get_name(), equal_to('l1')) assert_that(m2.attached_snapshot, none())
def test_factory_telnet(): lock = Mock() switch = brocade_factory_telnet(SwitchDescriptor(hostname='hostname', model='brocade', username='******', password='******', port=23), lock) assert_that(switch, instance_of(FlowControlSwitch)) assert_that(switch.wrapped_switch, instance_of(Brocade)) assert_that(switch.lock, is_(lock)) assert_that(switch.switch_descriptor.hostname, equal_to("hostname")) assert_that(switch.switch_descriptor.model, equal_to("brocade")) assert_that(switch.switch_descriptor.username, equal_to("username")) assert_that(switch.switch_descriptor.password, equal_to("password")) assert_that(switch.switch_descriptor.port, equal_to(23))
def test_state_click_outside_circle(self): x = 10 y = 10 radius = 5 self.viewer.draw_circle(x, y, radius) self.fire_press_event(x + 2, y + 2) assert_that(self.interaction_context.state, instance_of(MoveCircleState)) self.fire_release_event() assert_that(self.interaction_context.state, instance_of(MoveCircleState)) self.fire_press_event(x + 6, y + 6) assert_that(self.interaction_context.state, instance_of(CreateCircleState))
def test_factory(): lock = mock.Mock() switch = juniper.qfx_copper_factory(SwitchDescriptor(hostname='hostname', model='juniper_qfx_copper', username='******', password='******', port=22), lock) assert_that(switch, instance_of(SwitchTransactional)) assert_that(switch.impl, instance_of(Juniper)) assert_that(switch.lock, is_(lock)) assert_that(switch.switch_descriptor.hostname, equal_to("hostname")) assert_that(switch.switch_descriptor.model, equal_to("juniper_qfx_copper")) assert_that(switch.switch_descriptor.username, equal_to("username")) assert_that(switch.switch_descriptor.password, equal_to("password")) assert_that(switch.switch_descriptor.port, equal_to(22))
def test_state_click_outside_marker(self): x = 10 y = 10 radius = 5 self.image.place_marker(x, y, radius) self.fire_press_event(x + 2, y + 2) assert_that(self.interaction_context.state, instance_of(MoveMarkerState)) self.fire_release_event() assert_that(self.interaction_context.state, instance_of(MoveMarkerState)) self.fire_press_event(x + 6, y + 6) assert_that(self.interaction_context.state, instance_of(CreateMarkerState))
def do_send_serial(pubmock, attrs, encoded_data, transmit_data, expected_addr=None): expected_addr = expected_addr or attrs['addr'] pubmock.reset_mock() mgr = XBeeEventManager(registry) pollermock = mgr.poller pollermock.poll.return_value = [(mgr.socket.fileno.return_value, selectmock.POLLOUT)] # Get the listener from subscribe's last call listener = get_listener(pubmock) assert listener is not None # Create command object el = Element("send_serial", attrib=attrs) el.text = encoded_data rsp = Mock() listener(element=el, response=rsp) mgr.socket.sendto.assert_called_once_with(transmit_data, (expected_addr, 0xe8, 0xc105, 0x11, 0, match_equality(instance_of(int)))) # Grab the transmit identifier so we can complete it # First call, second argument, sixth member of address tuple tx_id = mgr.socket.sendto.call_args[0][1][5] rsp.put.assert_called_once_with(ResponsePending) rsp.reset_mock() # Trigger completion with transmit status mgr.socket.recvfrom.return_value = ( # TX Status response, frame info, dst, and other indicators all success '\x8b\x00\x00\x00\x00\x00\x00', ('[00:00:00:00:00:00:00:00]!', 0x0, 0xc105, 0x8b, 0x0, tx_id)) # Tell dispatcher portion that it has data mgr.handle_read() rsp.put.assert_called_once_with( match_equality(instance_of(DeferredResponse))) # First call, only arg dr = rsp.put.call_args[0][0] print dr assert "error" not in dr.response.keys() assert dr.response.text == ""
def test_resource_creates_resource_converter(self): document = Mock() class Model(object): pass converter = Converter.resource(document, Model) assert_that(converter.parser, instance_of(DocumentParser)) assert_that(converter.mapper, instance_of(DocumentMapper)) assert_that(converter.serializer, instance_of(ResourceSerializer)) assert_that(converter.builder, instance_of(ModelBuilder)) assert_that(converter.serializer.resources, has_entry('models', 'id'))
def test_create_object_graph(): """ Construct an object graph from bound factories and entry points. """ graph = create_object_graph( name="test", ) assert_that(graph.child, is_(instance_of(Child))) assert_that(graph.child.value, is_(equal_to("default_value"))) assert_that(graph.parent, is_(instance_of(Parent))) assert_that(graph.parent.child, is_(equal_to(graph.child))) assert_that(graph.hello_world, is_(equal_to("hello world")))
def test_get_connection_to_anonymous_switch(self): my_semaphore = mock.Mock() self.semaphore_mocks['hostname'] = my_semaphore switch = self.factory.get_anonymous_switch(hostname='hostname', model='test_model', username='******', password='******', port=22) assert_that(switch, is_(instance_of(FlowControlSwitch))) assert_that(switch.wrapped_switch, is_(instance_of(_FakeSwitch))) assert_that(switch.lock, is_(my_semaphore)) assert_that(switch.wrapped_switch.switch_descriptor, is_( SwitchDescriptor(hostname='hostname', model='test_model', username='******', password='******', port=22)))
def DebugInfo_test(app): request_data = BuildRequest(filetype='javascript') assert_that( app.post_json('/debug_info', request_data).json, has_entry( 'completer', has_entries({ 'name': 'JavaScript', 'servers': contains_exactly( has_entries({ 'name': 'Tern', 'is_running': instance_of(bool), 'executable': instance_of(str), 'pid': instance_of(int), 'address': instance_of(str), 'port': instance_of(int), 'logfiles': contains_exactly(instance_of(str), instance_of(str)), 'extras': contains_exactly( has_entries({ 'key': 'configuration file', 'value': instance_of(str) }), has_entries({ 'key': 'working directory', 'value': instance_of(str) })), })), 'items': empty() })))
def DebugInfo_test(app): request_data = BuildRequest(filetype='go') assert_that( app.post_json('/debug_info', request_data).json, has_entry( 'completer', has_entries({ 'name': 'Go', 'servers': contains( has_entries({ 'name': 'gopls', 'is_running': instance_of(bool), 'executable': contains(instance_of(str), instance_of(str), instance_of(str), instance_of(str)), 'address': None, 'port': None, 'pid': instance_of(int), 'logfiles': contains(instance_of(str)), 'extras': contains( has_entries({ 'key': 'Server State', 'value': instance_of(str), }), has_entries({ 'key': 'Project Directory', 'value': PathToTestFile(), }), has_entries({ 'key': 'Settings', 'value': '{}' }), ) })), })))
def test_client_returns_new_record_on_record_creation(person_record: Record, client: Client): person_record.id = None assert_that(person_record.exists(), is_not(True)) record_data = person_record.data record_data['id'] = 45 with requests_mock.Mocker() as mocker: mocker.post('/'.join( [client.server_url, 'data/{}'.format(person_record.obj)]), json={ 'status': 'OK', 'data': record_data }) record = client.records.create(person_record) assert_that(record, is_(instance_of(Record))) assert_that(record.exists()) assert_that(record.id, equal_to(45))
def test_flat_map_nofuture(executor): """Executor raises TypeError if map function does not produce a Future.""" flat_map_executor = FlatMapExecutor( executor, lambda x: executor.submit(mult10, x) if x == 2 else mult10(x) ) inputs = [1, 2, 3] futures = [flat_map_executor.submit(lambda v: v, x) for x in inputs] # The second future should have returned the mapped value assert_that(futures[1].result(), equal_to(20)) # The others should have failed since returned value is not a Future assert_that(futures[0].exception(), instance_of(TypeError)) assert_that(calling(futures[2].result), raises(TypeError))
def test_client_updates_record_with_partial_data(client: Client): record = Record(obj='person', age=20, name='Ivan', is_active=True, street="Street") record = client.records.create(record) assert_that(record, instance_of(Record)) # perform partial update record = client.records.partial_update('person', record.get_pk(), {'name': 'Petr'}) assert_that(record.name, equal_to('Petr')) # check that new data got stored in Custodian record = client.records.get('person', record.get_pk()) assert_that(record.name, equal_to('Petr'))
def test_attribute_access(): """ Configuration can be accessed by attribute and key. """ config = Configuration( key="value", nested=dict( nested_key="nested_value", other_key=range(10), ) ) assert_that(config, has_entry("key", "value")) assert_that(config, has_property("key", "value")) assert_that(config["nested"], is_(instance_of(Configuration))) assert_that(config["nested"], has_entry("nested_key", "nested_value")) assert_that(config.nested, has_property("nested_key", "nested_value"))
def test_given_api_exception_when_handle_api_exception_then_return_formatted_response( self): @handle_api_exception def decorated(): raise APIException(s.status_code, s.message, s.error_id, s.details) result = decorated() assert_that( result, contains( has_entries({ 'message': s.message, 'error_id': s.error_id, 'details': s.details, 'timestamp': instance_of(float) }), s.status_code))
def post(self, body='', content_type='application/json', args={}): view = TestResourceView() request = HttpRequest() request.META['CONTENT_TYPE'] = content_type request._body = body response = view.post(None, request, **args) assert_that(response, instance_of(HttpResponse)) try: json_response = json.loads(response.content) except ValueError: json_response = None return response.status_code, json_response
def test_me(self): response = self.deform_session_auth_client.use_project('some-project') assert_that(response, instance_of(ProjectClient)) assert_that( response.base_uri, equal_to(get_base_uri( project='some-project', host=self.deform_session_auth_client.host, port=self.deform_session_auth_client.port, secure=self.deform_session_auth_client.secure, api_base_path=self.deform_session_auth_client.api_base_path )) ) assert_that( response.auth_header, equal_to(self.deform_session_auth_client.auth_header) )
def get(self, args={}, query={}): view = TestResourceView() request = HttpRequest() for (k, v) in query.items(): request.GET[k] = v response = view.get(request, **args) assert_that(response, instance_of(HttpResponse)) try: json_response = json.loads(response.content) except ValueError: json_response = None return response.status_code, json_response
def test_get_properties(self): capacities = t_unity().get_system_capacity() assert_that(len(capacities), equal_to(1)) capacity = capacities[0] assert_that(capacity.id, equal_to('0')) assert_that(capacity.size_free, equal_to(9496172691456)) assert_that(capacity.size_total, equal_to(9641664708608)) assert_that(capacity.size_used, equal_to(145492017152)) assert_that(capacity.compression_size_saved, equal_to(0)) assert_that(capacity.compression_percent, equal_to(0)) assert_that(capacity.compression_ratio, equal_to(1)) assert_that(capacity.data_reduction_size_saved, equal_to(0)) assert_that(capacity.data_reduction_percent, equal_to(0)) assert_that(capacity.data_reduction_ratio, equal_to(1)) assert_that(capacity.size_subscribed, equal_to(1018980990976)) assert_that(capacity.tiers[0], instance_of(UnitySystemTierCapacity))
def test_create_pool(self): unity = t_unity() disk_group = unity.get_disk_group(_id='dg_15') raid_group_0 = RaidGroupParameter( disk_group=disk_group, disk_num=3, raid_type=RaidTypeEnum.RAID5, stripe_width=RaidStripeWidthEnum.BEST_FIT) raid_groups = [raid_group_0] pool = unity.create_pool( name='test_pool', description='Unity test pool.', raid_groups=raid_groups, alert_threshold=15, is_harvest_enabled=True, is_snap_harvest_enabled=True, pool_harvest_high_threshold=80, pool_harvest_low_threshold=40, snap_harvest_high_threshold=80, snap_harvest_low_threshold=40, is_fast_cache_enabled=True, is_fastvp_enabled=True, pool_type=StoragePoolTypeEnum.DYNAMIC) assert_that(pool, instance_of(UnityPool))
def test_request_given_get_method_and_an_unreachable_url_then_a_connectivity_error_should_be_raised( self): self.adapter.register_uri( 'GET', 'mock://some_url', exc=requests.exceptions.ConnectionError('some error desc')) http_executor = http.HttpExecutor(auth.AuthFactory.create( grant_client_id="client_id", grant_client_secret="client_secret"), session=self.session_mock) with pytest.raises(error.ConnectionError) as sequoia_error: http_executor.request("GET", "mock://some_url") assert_that('some error desc', is_in(sequoia_error.value.args)) assert_that(sequoia_error.value.cause, instance_of(requests.exceptions.ConnectionError))
def test_request_given_server_returns_too_many_redirects_then_error_should_be_raised( self): self.adapter.register_uri( 'GET', 'mock://some_url', exc=requests.exceptions.TooManyRedirects('some error desc')) http_executor = http.HttpExecutor(auth.AuthFactory.create( grant_client_id="client_id", grant_client_secret="client_secret"), session=self.session_mock) with pytest.raises(error.TooManyRedirects) as sequoia_error: http_executor.request("GET", "mock://some_url") assert_that('some error desc', is_in(sequoia_error.value.args)) assert_that(sequoia_error.value.cause, instance_of(requests.exceptions.TooManyRedirects))
def test_DebugInfo_FlagsWhenGlobalExtraConfAndCompilationDatabaseLoaded( self, app): with TemporaryTestDir() as tmp_dir: compile_commands = [ { 'directory': tmp_dir, 'command': 'clang++ -I. -I/absolute/path -Wall', 'file': os.path.join(tmp_dir, 'test.cc'), }, ] with TemporaryClangProject(tmp_dir, compile_commands): request_data = BuildRequest(filepath=os.path.join( tmp_dir, 'test.cc'), filetype='cpp') assert_that( app.post_json('/debug_info', request_data).json, has_entry( 'completer', has_entries({ 'name': 'C-family', 'servers': empty(), 'items': contains_exactly( has_entries({ 'key': 'compilation database path', 'value': instance_of(str) }), has_entries({ 'key': 'flags', 'value': matches_regexp( "\\['clang\\+\\+', '-x', 'c\\+\\+', .*, '-Wall', .*\\]" ) }), has_entries({ 'key': 'translation unit', 'value': os.path.join(tmp_dir, 'test.cc'), })) })))
def test_dispatch_by_convention(): """ Message dispatch can use this convention. """ graph = create_object_graph("example", testing=True) media_type = created(Foo) assert_that( graph.pubsub_message_schema_registry[media_type].schema, is_(instance_of(URIMessageSchema)), ) assert_that( graph.sqs_message_handler_registry[media_type], is_(equal_to(noop_handler)), )
def test_nested_properties(self): host = UnityHost(_id='Host_12', cli=t_rest()) assert_that( host.fc_host_initiators.initiator_id, only_contains('20:00:00:00:C9:F3:AB:0C:10:00:00:00:C9:F3:AB:0C', '20:00:00:00:C9:F3:AB:0D:10:00:00:00:C9:F3:AB:0D')) assert_that(host.iscsi_host_initiators.initiator_id, only_contains('iqn.1998-01.com.vmware:esx239209-7e7a57a4')) assert_that(host.fc_host_initiators[0].paths[0].is_logged_in, equal_to(True)) assert_that( host.fc_host_initiators[1].paths[0].fc_port.wwn, equal_to('50:06:01:60:C7:E0:01:DA:50:06:01:6C:47:E0:01:DA')) assert_that(host.fc_host_initiators[1].paths[0].initiator.type, equal_to(HostInitiatorTypeEnum.FC)) assert_that(host.host_ip_ports[0].address, equal_to('10.245.54.151')) assert_that(host.host_luns, instance_of(UnityHostLunList)) assert_that(host.host_luns[0].lun.name, equal_to('Yangpu'))
def test_properties(self): snap = UnitySnap(_id=171798691852, cli=t_rest()) assert_that(snap.existed, equal_to(True)) assert_that(snap.state, equal_to(SnapStateEnum.READY)) assert_that(snap.name, equal_to('esa_nfs1_2016-03-15_10:56:29')) assert_that(snap.is_system_snap, equal_to(False)) assert_that(snap.is_modifiable, equal_to(False)) assert_that(snap.is_read_only, equal_to(False)) assert_that(snap.is_modified, equal_to(False)) assert_that(snap.is_auto_delete, equal_to(True)) assert_that(snap.size, equal_to(5368709120)) assert_that(str(snap.creation_time), equal_to('2016-03-15 02:57:27.092000+00:00')) assert_that(snap.storage_resource, instance_of(UnityStorageResource)) assert_that(snap.creator_type, equal_to(SnapCreatorTypeEnum.USER_CUSTOM)) assert_that(snap.access_type, equal_to(FilesystemSnapAccessTypeEnum.CHECKPOINT))
def test_shouldInjectTheField(self): # pylint: disable=no-self-use assert_that(BasicTestModel, has_property('river', is_(instance_of(RiverObject)))) assert_that( BasicTestModel.river, has_property('my_field', is_(instance_of(ClassWorkflowObject)))) content_type = ContentType.objects.get_for_model(BasicTestModel) state1 = StateObjectFactory.create(label="state1") state2 = StateObjectFactory.create(label="state2") workflow = WorkflowFactory(content_type=content_type, field_name="my_field", initial_state=state1) transition_meta = TransitionMetaFactory.create( workflow=workflow, source_state=state1, destination_state=state2, ) TransitionApprovalMetaFactory.create(workflow=workflow, transition_meta=transition_meta, priority=0) test_model = BasicTestModel.objects.create() assert_that(test_model, has_property('river', is_(instance_of(RiverObject)))) assert_that( test_model.river, has_property('my_field', is_(instance_of(InstanceWorkflowObject)))) assert_that(BasicTestModel.river.my_field, has_property('initial_state', is_(instance_of(State)))) assert_that(BasicTestModel.river.my_field, has_property('final_states', is_(instance_of(QuerySet)))) assert_that(test_model.river.my_field, has_property('approve', has_property("__call__"))) assert_that(test_model.river.my_field, has_property('on_initial_state', is_(instance_of(bool)))) assert_that(test_model.river.my_field, has_property('on_final_state', is_(instance_of(bool))))
def test_order_serializer(order_with_item): """ Test OrderSerializer """ serializer = OrderSerializer(order_with_item) assert_that( serializer.data, has_entries({ "id": instance_of(int), "created": instance_of(str), "state": instance_of(str), "order_items": contains_exactly( has_entries({ "id": instance_of(int), "saved_product_id": instance_of(int), "product": instance_of(int), "saved_product": has_entries({ "id": instance_of(int), "product_id": instance_of(int), "title": instance_of(str), "width": matches_regexp(r"\d+\.\d{2}"), "height": matches_regexp(r"\d+\.\d{2}"), "length": matches_regexp(r"\d+\.\d{2}"), "weight": matches_regexp(r"\d+\.\d{2}"), "retail_price": matches_regexp(r"\d+\.\d{2}"), }), }), ), }), )
def test_switch_model_exists(self): core_mock = mock.create_autospec(switch_core.SwitchCore) core_mock.get_default_ports.return_value = mock.sentinel.port_list with mock.patch('fake_switches.switch_factory.switch_configuration' ) as switch_conf_module: switch_conf_instance = mock.Mock() switch_conf_class = mock.Mock() switch_conf_class.return_value = switch_conf_instance switch_conf_module.SwitchConfiguration = switch_conf_class factory = switch_factory.SwitchFactory(mapping={'a': core_mock}) switch = factory.get('a', 'my_hostname') assert_that(switch, is_(instance_of(switch_core.SwitchCore))) switch_conf_class.assert_called_with('127.0.0.1', name='my_hostname', ports=mock.sentinel.port_list, privileged_passwords=['root']) core_mock.assert_called_with(switch_conf_instance)
def test_DebugInfo_ServerIsNotRunning_NoSolution( self, app ): request_data = BuildRequest( filetype = 'cs' ) assert_that( app.post_json( '/debug_info', request_data ).json, has_entry( 'completer', has_entries( { 'name': 'C#', 'servers': contains_exactly( has_entries( { 'name': 'OmniSharp', 'is_running': False, 'executable': instance_of( str ), 'pid': None, 'address': None, 'port': None, 'logfiles': empty() } ) ), 'items': empty() } ) ) )
def test_create_minimal_parameters(): response = confd.agents.post(number='1234') response.assert_created('agents') assert_that( response.item, has_entries( id=instance_of(int), number='1234', firstname=None, lastname=None, password=None, preprocess_subroutine=None, description=None, ), ) confd.agents(response.item['id']).delete().assert_deleted()
def test_client_returns_iterable_of_records_on_bulk_query( person_record: Record, client: Client): query = client.records.query('person').filter(address__city_id__eq=45) with requests_mock.Mocker() as mocker: mocker.get( '/'.join([client.server_url, 'data/person']), json={ 'status': 'OK', 'data': [ # nothing terrible in is that records are duplicated person_record.data, person_record.data ] }) assert_that(len(query), equal_to(2)) for record in query: assert_that(record, instance_of(Record))
def DebugInfo_ServerIsRunning_test(app): filepath = PathToTestFile('testy', 'Program.cs') contents = ReadFile(filepath) event_data = BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') app.post_json('/event_notification', event_data) WaitUntilCompleterServerReady(app, 'cs') request_data = BuildRequest(filepath=filepath, filetype='cs') assert_that( app.post_json('/debug_info', request_data).json, has_entry( 'completer', has_entries({ 'name': 'C#', 'servers': contains_exactly( has_entries({ 'name': 'OmniSharp', 'is_running': True, 'executable': instance_of(str), 'pid': instance_of(int), 'address': instance_of(str), 'port': instance_of(int), 'logfiles': contains_exactly(instance_of(str), instance_of(str)), 'extras': contains_exactly( has_entries({ 'key': 'solution', 'value': instance_of(str) })) })), 'items': empty() })))
def test_properties(self): nfs = UnityNfsShare('NFSShare_1', cli=t_rest()) assert_that(nfs.id, equal_to('NFSShare_1')) assert_that(nfs.type, equal_to(NFSTypeEnum.NFS_SHARE)) assert_that(nfs.role, equal_to(NFSShareRoleEnum.PRODUCTION)) assert_that(nfs.default_access, equal_to(NFSShareDefaultAccessEnum.ROOT)) assert_that(nfs.min_security, equal_to(NFSShareSecurityEnum.SYS)) assert_that(nfs.name, equal_to('esa_nfs1')) assert_that(nfs.path, equal_to(r'/')) assert_that(nfs.export_paths, only_contains(r'10.244.220.120:/esa_nfs1')) assert_that(nfs.description, equal_to('bcd')) assert_that(str(nfs.creation_time), equal_to('2016-03-02 02:39:22.856000+00:00')) assert_that(str(nfs.modification_time), equal_to('2016-03-02 02:39:22.856000+00:00')) assert_that(nfs.filesystem.get_id(), equal_to('fs_1')) assert_that(nfs.filesystem, instance_of(UnityFileSystem))
def test_job_list_request(self): payload = { 'nextPageToken': 'next', 'jobs': [{ 'status': 'pending', 'specification': {}, 'dateCreated': '2017-05-23T08:34:43Z', 'sources': [], 'result': None, 'id': 'g_1', 'dateUpdated': '2017-05-23T08:34:43Z', 'type': 'urn:job:something.fresh', 'groupId': '71f0d3fde7f348ea89aa1173299146f8', 'issuer': 'urn:app:app-id-1' }] } response = RestResult(0, 'OK', payload) httpretty.register_uri(httpretty.GET, 'https://fish.barrel/_api/jobs', body=json.dumps(response.serialize())) job_list = self.job_service.job_list_request().set_type( 'urn:job:fish').set_page_size(3).set_order_by( OrderBy.date_updated).set_next_page_token('nnn').set_path( '/mmm').set_issuer('urn:me').set_order_direction( OrderDirection.descending).set_status( JobStatus.pending).execute() assert_that(job_list.jobs[0], instance_of(Job)) assert_that(job_list.jobs[0].id, is_('g_1')) assert_that( httpretty.last_request().querystring, is_({ 'nextPageToken': ['nnn'], 'orderBy': ['dateUpdated'], 'pageSize': ['3'], 'status': ['pending'], 'path': ['/mmm'], 'type': ['urn:job:fish'], 'orderDirection': ['des'], 'issuer': ['urn:me'] }))
def test_convert_resource_custom_type(self): graph = MagicMock() class BazURIHandler(URIHandler): @property def resource_type(self): return Baz handler = BazURIHandler(graph) resource = handler.convert_resource(dict(foo="bar", ), ) assert_that( resource, is_(instance_of(Baz)), ) assert_that( resource.foo, is_(equal_to("bar")), )
def test_full_run(self, api_request_factory): image_path = pathlib.Path( __file__).absolute().parent / 'test_image.jpg' image = Image.open(image_path) buffered = BytesIO() image.save(buffered, format='JPEG') encoded_image = base64.b64encode(buffered.getvalue()).decode() request = api_request_factory.post(self.url, { 'image': encoded_image, 'model_type': 'AlexNet', }) response = self.view_class.as_view()(request) assert_that(response.status_code, is_(equal_to(status.HTTP_200_OK))) # Well, we can't be sure what will be predicted here, but at least we will know that the whole process works. # And we will see the highest predictions in logs. assert_that(response.data, has_entry('image_label', is_(instance_of(str))))
def test_spotlightify_handles_other_and_transaction_links(self): self.dashboard.add_other_link('other', 'http://www.gov.uk') self.dashboard.add_other_link('other2', 'http://www.gov.uk') self.dashboard.update_transaction_link('transaction', 'http://www.gov.uk') self.dashboard.validate_and_save() transaction_link = self.dashboard.get_transaction_link() assert_that(transaction_link, instance_of(Link)) assert_that(transaction_link.link_type, equal_to('transaction')) assert_that(self.dashboard.get_other_links()[0].link_type, equal_to('other')) assert_that( self.dashboard.spotlightify(), has_entries({ 'title': 'title', 'page-type': 'dashboard', 'relatedPages': has_entries({ 'improve-dashboard-message': True, 'transaction': has_entries({ 'url': 'http://www.gov.uk', 'title': 'transaction', }), 'other': has_items( has_entries({ 'url': 'http://www.gov.uk', 'title': 'other', }), has_entries({ 'url': 'http://www.gov.uk', 'title': 'other2', }), ) }) })) assert_that(self.dashboard.spotlightify(), is_not(has_key('id'))) assert_that(self.dashboard.spotlightify(), is_not(has_key('link')))