def test_to_json_snapshot_value(self): """Test conversion of values.""" snapshot = JsonSnapshot() # Primitive types dont affect snapshot. self.assertEquals(2, JsonSnapshotHelper.ToJsonSnapshotValue(2, snapshot)) self.assertEquals( 2.0, JsonSnapshotHelper.ToJsonSnapshotValue(2.0, snapshot)) self.assertEquals( '2', JsonSnapshotHelper.ToJsonSnapshotValue('2', snapshot)) self.assertEquals( [1, 2, 3], JsonSnapshotHelper.ToJsonSnapshotValue([1, 2, 3], snapshot)) d = {'a': 'A', 'b': 2, 'c': [1, 2, 3]} self.assertEquals( d, JsonSnapshotHelper.ToJsonSnapshotValue(d, snapshot)) self.assertEquals({'_type': 'JsonSnapshot'}, snapshot.to_json_object()) # Wrapped values dont affect snapshot self.assertEquals( d, JsonSnapshotHelper.ToJsonSnapshotValue(TestWrappedValue(d), snapshot)) self.assertEquals({'_type': 'JsonSnapshot'}, snapshot.to_json_object()) # types dont affect snapshot self.assertEquals( 'type dict', JsonSnapshotHelper.ToJsonSnapshotValue(dict, snapshot)) self.assertEquals({'_type': 'JsonSnapshot'}, snapshot.to_json_object()) # methods dont affect snapshot self.assertEquals( 'Method "test_to_json_snapshot_value"', JsonSnapshotHelper.ToJsonSnapshotValue( self.test_to_json_snapshot_value, snapshot)) self.assertEquals({'_type': 'JsonSnapshot'}, snapshot.to_json_object()) # exceptions dont affect snapshot self.assertEquals( 'KeyError: \'Hello, World\'', JsonSnapshotHelper.ToJsonSnapshotValue(KeyError('Hello, World'), snapshot)) self.assertEquals({'_type': 'JsonSnapshot'}, snapshot.to_json_object()) # JsonSnapshotableEntity definition written into snapshot ll = TestLinkedList('X') ref = JsonSnapshotHelper.ToJsonSnapshotValue(ll, snapshot) self.assertEquals({'_type': 'EntityReference', '_id': 1}, ref) expect = {'_type': 'JsonSnapshot', '_subject_id': 1, '_entities': {1: {'_id': 1, 'class': 'type TestLinkedList', 'name': 'X'}} } self.assertEquals(expect, snapshot.to_json_object()) self.assertEquals(1, snapshot.find_entity_for_object(ll).id)
def test_inspect_not_found_ok(self): # Return a 404 Not found # The string we return just needs to end with " was not found", # which is what gcloud currently returns (subject to change) # and all we test for. error_response = st.CliResponseType(- 1, '', 'ERROR: (gcloud.preview.managed-instance-groups.describe)' ' The thing you requested was not found') gcloud = fake_gcloud_agent.FakeGCloudAgent( 'PROJECT', 'ZONE', default_response=error_response) contract_builder = gt.GceContractBuilder(gcloud) extra_args=['arg1', 'arg2', 'arg3'] c1 = contract_builder.new_clause_builder('TITLE') verifier = c1.inspect_resource( 'instances', 'test_name', extra_args=extra_args, no_resource_ok=True) verifier.contains_path_value('field', 'value') self.assertTrue(isinstance(verifier, jc.ValueObservationVerifierBuilder)) contract = contract_builder.build() verification_result = contract.verify() self.assertTrue(verification_result, JsonSnapshotHelper.ValueToEncodedJson(verification_result)) command = gcloud.build_gcloud_command_args( 'instances', ['describe', 'test_name'] + extra_args, project='PROJECT', zone='ZONE') self.assertEquals(command, gcloud.last_run_params)
def test_assert_expected_value_ok(self): tests = [(False, False), (1, 1), ('a', 'a'), (3.14, 3.14), ([1, 'a'], [1, 'a']), ({ 'a': 'A', 'b': 'B' }, { 'b': 'B', 'a': 'A' }), (TestLinkedList('A', TestLinkedList('B')), TestLinkedList('A', TestLinkedList('B'))), (None, None), (dict.__class__, dict.__class__)] for spec in tests: JsonSnapshotHelper.AssertExpectedValue(spec[0], spec[1]) tests = [(False, True), (1, 2), ('a', 'b'), (3.14, -3.14), ([1, 'a'], ['a', 1]), ([1, 'a'], [1, 'a', 2]), ({ 'a': 'A', 'b': 'B' }, { 'a': 'A', 'b': 'B', 'c': 'C' }), (TestLinkedList('A', TestLinkedList('B')), TestLinkedList('A', TestLinkedList('C'))), (None, False), (dict, dict.__class__)] for spec in tests: self.assertRaises(AssertionError, JsonSnapshotHelper.AssertExpectedValue, spec[0], spec[1])
def test_inspect_not_found_ok(self): context = ExecutionContext() response = Mock() response.status = 404 response.reason = 'Not Found' default_variables = {'project': 'PROJECT'} service = MyFakeGcpService([HttpError(response, 'Not Found')]) agent = TestGcpAgent.make_test_agent( service=service, default_variables=default_variables) contract_builder = gt.GcpContractBuilder(agent) c1 = contract_builder.new_clause_builder('TITLE') verifier = c1.inspect_resource( 'regions', resource_id='us-central1-f', no_resource_ok=True) verifier.contains_path_value('field', 'value') self.assertTrue(isinstance(verifier, jc.ValueObservationVerifierBuilder)) contract = contract_builder.build() verification_result = contract.verify(context) self.assertTrue(verification_result, JsonSnapshotHelper.ValueToEncodedJson(verification_result)) self.assertEquals({'project': 'PROJECT', 'region': 'us-central1-f'}, agent.service.last_get_args)
def _try_map(self, context, pred, obj, expect_ok, expect_map_result=None, dump=False, min=1): """Helper function for invoking finder and asserting the result. Args: pred: The jp.ValuePredicate to map. obj: The object to apply the predicate to. expect_ok: Whether we expect apply to succeed or not. expect_map_result: If not None, then the expected jp.MapPredicateResult from apply(). dump: If True then print the filter_result to facilitate debugging. """ map_result = jp.MapPredicate(pred, min=min)(context, obj) if dump: print 'MAP_RESULT:\n{0}\n'.format( JsonSnapshotHelper.ValueToEncodedJson(map_result)) if expect_map_result: self.assertEqual(expect_map_result, map_result) error_msg = '{expect_ok} != {ok}\n{map_result}'.format( expect_ok=expect_ok, ok=map_result.__nonzero__(), map_result=map_result) self.assertEqual(expect_ok, map_result.__nonzero__(), error_msg)
def test_inspect_indirect(self): context = ExecutionContext(test_id='TESTID', test_project='PROJECT') default_variables = { 'project': lambda x: x.get('test_project', 'UNKNOWN') } service = MyFakeGcpService(['Hello, World']) agent = TestGcpAgent.make_test_agent( service=service, default_variables=default_variables) contract_builder = gt.GcpContractBuilder(agent) c1 = contract_builder.new_clause_builder('TITLE') verifier = c1.inspect_resource('regions', resource_id=lambda x: x['test_id']) verifier.EXPECT( ov_factory.value_list_contains(jp.STR_EQ('Hello, World'))) self.assertTrue( isinstance(verifier, jc.ValueObservationVerifierBuilder)) contract = contract_builder.build() verification_result = contract.verify(context) self.assertTrue( verification_result, JsonSnapshotHelper.ValueToEncodedJson(verification_result)) self.assertEquals({ 'project': 'PROJECT', 'region': 'TESTID' }, agent.service.last_get_args)
def assertEqual(self, expect, have, msg=''): if not isinstance(expect, JsonSnapshotableEntity): super(JsonValueObservationVerifierTest, self).assertEqual(expect, have, msg) return try: JsonSnapshotHelper.AssertExpectedValue(expect, have, msg) except AssertionError: print 'EXPECTED\n{0!r}\nGOT\n{1!r}'.format(expect, have)
def assertEqual(self, expect, have, msg=''): JsonSnapshotHelper.AssertExpectedValue(expect, have, msg)
def assertEqual(self, expect, have, msg=''): if not msg: msg = 'EXPECTED\n{0!r}\nGOT\n{1!r}'.format(expect, have) JsonSnapshotHelper.AssertExpectedValue(expect, have, msg)
def assertEqual(self, expect, have, msg=''): try: JsonSnapshotHelper.AssertExpectedValue(expect, have, msg) except AssertionError: print '\nEXPECT\n{0!r}\n\nGOT\n{1!r}\n'.format(expect, have) raise