예제 #1
0
  def FromData(cls, mode, http_data):
    """Creates an HttpBodyAssertion for an HTTP request or response.

    Args:
      mode: string, 'expect_request' or 'expect_response' depending on if it is
          a request or response.
      http_data: dict, api_call.expect_request or api_call.expect_response.

    Returns:
      HttpBodyAssertion
    """
    payload_json_assertion = None
    payload_text_assertion = None
    body_present = True
    body_data = http_data.get('body')
    if 'body' not in http_data or (not body_data and body_data is not None):
      # The body section is missing entirely or it is present and is an empty
      # dictionary. In these cases, the assertions are not present and will be
      # updated always.
      body_present = False
      payload_json_assertion = assertions.JsonAssertion().Matches(
          '', assertions.MISSING_VALUE)
      payload_text_assertion = assertions.EqualsAssertion(
          assertions.MISSING_VALUE)
      http_data['body'] = {'text': None, 'json': {}}
    elif body_data is None:
      # The body section is present and explicitly None. This implies assertions
      # that the body is actual None. If it is not, the assertions will fail.
      body_present = False
      payload_json_assertion = assertions.JsonAssertion().Matches('', None)
      payload_text_assertion = assertions.EqualsAssertion(None)
    else:
      # The body is present, load the assertions that were provided.
      if 'text' in body_data:
        payload_text_assertion = assertions.Assertion.ForComplex(
            body_data['text'])
      if 'json' in body_data:
        payload_json_assertion = assertions.JsonAssertion()
        json_data = body_data['json']
        if not json_data or json_data == assertions.MISSING_VALUE:
          # If explicitly None, this asserts that the request is empty.
          # If explicitly the empty dictionary, the assertion checks nothing.
          payload_json_assertion.Matches('', json_data)
        else:
          for field, struct in six.iteritems(json_data):
            payload_json_assertion.Matches(field, struct)

    return cls(mode, body_present, payload_json_assertion,
               payload_text_assertion)
예제 #2
0
    def _ForCommon(cls, mode, http_data, uri_assertion, method_assertion,
                   extract_references):
        """Builder for the attributes applicable to both requests and responses."""
        header_assertion = assertions.DictAssertion()
        for header, value in six.iteritems(http_data.get('headers', {})):
            header_assertion.AddAssertion(
                header, assertions.Assertion.ForComplex(value))

        payload_json_assertion = None
        payload_text_assertion = None
        body_present = True
        body_data = http_data.get('body')
        if 'body' not in http_data or (not body_data
                                       and body_data is not None):
            # The body section is missing entirely or it is present and is an empty
            # dictionary. In these cases, the assertions are not present and will be
            # updated always.
            body_present = False
            payload_json_assertion = assertions.JsonAssertion().Matches(
                '', assertions.MISSING_VALUE)
            payload_text_assertion = assertions.EqualsAssertion(
                assertions.MISSING_VALUE)
            http_data['body'] = {'text': None, 'json': {}}
        elif body_data is None:
            # The body section is present and explicitly None. This implies assertions
            # that the body is actual None. If it is not, the assertions will fail.
            body_present = False
            payload_json_assertion = assertions.JsonAssertion().Matches(
                '', None)
            payload_text_assertion = assertions.EqualsAssertion(None)
        else:
            # The body is present, load the assertions that were provided.
            if 'text' in body_data:
                payload_text_assertion = assertions.Assertion.ForComplex(
                    body_data['text'])
            if 'json' in body_data:
                payload_json_assertion = assertions.JsonAssertion()
                json_data = body_data['json']
                if not json_data or json_data == assertions.MISSING_VALUE:
                    # If explicitly None, this asserts that the request is empty.
                    # If explicitly the empty dictionary, the assertion checks nothing.
                    payload_json_assertion.Matches('', json_data)
                else:
                    for field, struct in six.iteritems(json_data):
                        payload_json_assertion.Matches(field, struct)

        return cls(mode, uri_assertion, method_assertion, header_assertion,
                   payload_json_assertion, payload_text_assertion,
                   body_present, extract_references)
예제 #3
0
  def ForMissing(cls):
    """Creates a RequestAssertion for a missing api_call."""
    uri_assertion = assertions.EqualsAssertion(assertions.MISSING_VALUE)
    method_assertion = assertions.EqualsAssertion(assertions.MISSING_VALUE)
    headers_assertion = assertions.DictAssertion()

    payload_json_assertion = (assertions.JsonAssertion()
                              .Matches('', assertions.MISSING_VALUE))
    payload_text_assertion = assertions.EqualsAssertion(
        assertions.MISSING_VALUE)
    body_assertion = HttpBodyAssertion('expect_request', False,
                                       payload_json_assertion,
                                       payload_text_assertion)
    return cls(uri_assertion, method_assertion, headers_assertion,
               body_assertion)
예제 #4
0
  def testJsonUpdate(self):
    actual = {
        'foo': 'bar',
        'a': {'b': 'c', 'd': 'e'},
        'h': {
            'i': {'j': 'k', 'l': 'm'},
        },
        'scalar_list': ['s', 't', 'u'],
        'dict_list': [
            {'s': 't', 'u': 'v'},
            {'w': 'x', 'y': 'z'},
        ],
        'diff_len_lists': [{'a': 'b'}, 'b', 'c'],
    }
    assertion_data = {
        'foo': 'X',
        'a': {'b': 'X'},
        'h': {'i': {'j': 'X'}},
        'scalar_list': ['s', 'X', 'u'],
        'dict_list': [{'s': 'X', 'u': 'v'}, {'w': 'x', 'y': 'X'},],
        'diff_len_lists': ['X'],
    }
    assertion = assertions.JsonAssertion()
    for field, struct in assertion_data.items():
      assertion.Matches(field, struct)

    context = updates.Context(
        {'data': assertion_data}, 'data', updates.Mode.RESULT)
    failures = assertion.Check(context, actual)
    self.assertEqual(7, len(failures))

    for f in failures:
      f.Update([updates.Mode.RESULT])
    self.assertEqual('bar', assertion_data['foo'])
    self.assertEqual('c', assertion_data['a']['b'])
    self.assertEqual('k', assertion_data['h']['i']['j'])
    self.assertEqual('t', assertion_data['scalar_list'][1])
    self.assertEqual('t', assertion_data['dict_list'][0]['s'])
    self.assertEqual('z', assertion_data['dict_list'][1]['y'])
    self.assertEqual([{'a': 'b'}, 'b', 'c'], assertion_data['diff_len_lists'])
예제 #5
0
    def ForMissing(cls, location):
        backing_data = {
            'api_call':
            OrderedDict([('expect_request',
                          OrderedDict([('uri', ''), ('method', ''),
                                       ('headers', {}),
                                       ('body', {
                                           'text': None,
                                           'json': {}
                                       })])),
                         ('return_response',
                          OrderedDict([('headers', {
                              'status': '200'
                          }), ('body', None)]))])
        }
        update_context = updates.Context(backing_data,
                                         'api_call',
                                         cls.EventType().UpdateMode(),
                                         was_missing=True,
                                         location=location)
        response = backing_data['api_call']['return_response']

        return cls(
            update_context, None, None, False,
            HTTPAssertion(
                'expect_request',
                assertions.EqualsAssertion(assertions.MISSING_VALUE),
                assertions.EqualsAssertion(assertions.MISSING_VALUE),
                assertions.DictAssertion(),
                assertions.JsonAssertion().Matches('',
                                                   assertions.MISSING_VALUE),
                assertions.EqualsAssertion(assertions.MISSING_VALUE), False,
                {}), None,
            HTTPResponsePayload(headers=response['headers'],
                                payload=response['body'],
                                omit_fields=None))
예제 #6
0
class AssertionTests(test_case.TestCase, parameterized.TestCase):
  @parameterized.parameters([
      (assertions.EqualsAssertion(''), '', True),
      (assertions.EqualsAssertion(''), 'asdf', False),
      (assertions.EqualsAssertion('asdf'), 'asdf', True),
      (assertions.EqualsAssertion('asdf'), 'qwer', False),

      (assertions.MatchesAssertion('asdf'), 'asdf', True),
      (assertions.MatchesAssertion('a.*'), 'asdf', True),
      (assertions.MatchesAssertion('b.*'), 'asdf', False),
      (assertions.MatchesAssertion(''), 'asdf', False),
      (assertions.MatchesAssertion('.*'), 'asdf', True),
      (assertions.MatchesAssertion('.*'), b'asdf', True),

      (assertions.IsNoneAssertion(True), None, True),
      (assertions.IsNoneAssertion(True), 'asdf', False),
      (assertions.IsNoneAssertion(True), True, False),
      (assertions.IsNoneAssertion(True), False, False),
      (assertions.IsNoneAssertion(True), 1, False),
      (assertions.IsNoneAssertion(False), None, False),
      (assertions.IsNoneAssertion(False), 'asdf', True),
      (assertions.IsNoneAssertion(False), True, True),
      (assertions.IsNoneAssertion(False), False, True),
      (assertions.IsNoneAssertion(False), 1, True),

      (assertions.InAssertion({1, 2, 3}), 1, True),
      (assertions.InAssertion({1, 2, 3}), 4, False),
      (assertions.InAssertion({1, 2, 3}), 'a', False),
      (assertions.InAssertion({1, 2, 3}), None, False),
      (assertions.InAssertion({'a', 'b', 'c'}), 'a', True),
      (assertions.InAssertion({'a', 'b', 'c'}), 'd', False),
      (assertions.InAssertion({'a', 'b', 'c'}), 1, False),
      (assertions.InAssertion({'a', 'b', 'c'}), None, False),

      (assertions.DictAssertion(), {}, True),
      (assertions.DictAssertion().Equals('a', 'b'), {}, False),
      (assertions.DictAssertion().Equals('a', 'b'), {'a': 'b'}, True),
      (assertions.DictAssertion().Equals('a', 'b'), {'a': 'c'}, False),

      (assertions.DictAssertion().Matches('a', 'b'), {}, False),
      (assertions.DictAssertion().Matches('a', 'b'), {'a': 'b'}, True),
      (assertions.DictAssertion().Matches('a', 'b'), {'a': 'c'}, False),
      (assertions.DictAssertion().Matches('a', '.*'), {'a': 'c'}, True),
      (assertions.DictAssertion().Matches(
          'a', 'as.*df'), {'a': 'asqwerdf'}, True),

      (assertions.DictAssertion().IsNone('a'), {}, True),
      (assertions.DictAssertion().IsNone('a'), {'a': 'b'}, False),

      (assertions.DictAssertion().In('a', ['1', '2', '3']), {}, False),
      (assertions.DictAssertion().In('a', ['1', '2', '3']), {'a': 'b'}, False),
      (assertions.DictAssertion().In('a', ['1', '2', '3']), {'a': '1'}, True),
  ])
  def testAssertion(self, assertion, actual, matches):
    if matches:
      with assertions.FailureCollector([]) as f:
        f.AddAll(assertion.Check(updates.Context.Empty(), actual))
    else:
      with self.assertRaises(assertions.Error):
        with assertions.FailureCollector([]) as f:
          f.AddAll(assertion.Check(updates.Context.Empty(), actual))

  @parameterized.parameters([
      (assertions.JsonAssertion().Matches('', {}), True),
      (assertions.JsonAssertion().Matches('', {'a': {}}), True),
      (assertions.JsonAssertion().Matches('', {'a': {'b': 'c'}}), True),
      (assertions.JsonAssertion().Matches('', {'a': {'b': 'c', 'f': 1}}), True),
      (assertions.JsonAssertion().Matches('', {'a': {'b': 'd'}}), False),
      (assertions.JsonAssertion().Matches('a.f', 1), True),
      (assertions.JsonAssertion().Matches('a.f', 2), False),
      (assertions.JsonAssertion().Matches('a.g', True), True),
      (assertions.JsonAssertion().Matches('a.g', False), False),
      (assertions.JsonAssertion().Matches('h.o.p', 'q'), True),
      (assertions.JsonAssertion().Matches('h.o.p', 'z'), False),
      (assertions.JsonAssertion().Matches('h.o', {'p': 'q'}), True),
      (assertions.JsonAssertion().Matches('list', {}), False),
      (assertions.JsonAssertion().Matches('list', []), False),
      (assertions.JsonAssertion().Matches('list', [1, 2]), False),
      (assertions.JsonAssertion().Matches('list', [{}, {}]), True),
      (assertions.JsonAssertion().Matches('list',
                                          [{'s': 't'}, {'y': 'z'}]), True),
      (assertions.JsonAssertion().Matches('list',
                                          [{'s': 't'}, {'y': 'x'}]), False),
      (assertions.JsonAssertion().Matches('list',
                                          [{'s': 't'}, {'z': 'asdf'}]), False),
      (assertions.JsonAssertion().Matches('list',
                                          [{'s': 't'}, {'y': 'z'},
                                           {'asdf', 'asdf'}]), False),
      (assertions.JsonAssertion().Matches('a.f', 1).Matches('a.b', 'c'), True),
      (assertions.JsonAssertion().Matches('a.f', 1).IsAbsent('a.x'), True),
      (assertions.JsonAssertion().Matches('a.f', 1).IsAbsent('a.d'), False),
      (assertions.JsonAssertion().Matches('n_l.l.a', [1, 3, 5]), True),
      (assertions.JsonAssertion().Matches('n_l.l.b', [2, 3]), False),
      (assertions.JsonAssertion().Matches('n_l.l.c', [0, 0]), False),
      (assertions.JsonAssertion().Matches('n_l.l', [{'a': 1, 'b': 2},
                                                    {'a': 3, 'b': 4},
                                                    {'a': 5, 'b': 6}]), True),
  ])
  def testCheckJsonContent(self, assertion, matches):
    actual = {
        'a': {'b': 'c', 'd': 'e', 'f': 1, 'g': True},
        'h': {
            'i': {'j': 'k', 'l': 'm'},
            'o': {'p': 'q', 'r': 'r'},
        },
        'list': [
            {'s': 't', 'u': 'v'},
            {'w': 'x', 'y': 'z'},
        ],
        'n_l': {'l': [
            {'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}
        ]}
    }
    if matches:
      with assertions.FailureCollector([]) as f:
        f.AddAll(assertion.Check(updates.Context.Empty(), actual))
    else:
      with self.assertRaises(assertions.Error):
        with assertions.FailureCollector([]) as f:
          f.AddAll(assertion.Check(updates.Context.Empty(), actual))

  def testJsonUpdate(self):
    actual = {
        'foo': 'bar',
        'a': {'b': 'c', 'd': 'e'},
        'h': {
            'i': {'j': 'k', 'l': 'm'},
        },
        'scalar_list': ['s', 't', 'u'],
        'dict_list': [
            {'s': 't', 'u': 'v'},
            {'w': 'x', 'y': 'z'},
        ],
        'diff_len_lists': [{'a': 'b'}, 'b', 'c'],
    }
    assertion_data = {
        'foo': 'X',
        'a': {'b': 'X'},
        'h': {'i': {'j': 'X'}},
        'scalar_list': ['s', 'X', 'u'],
        'dict_list': [{'s': 'X', 'u': 'v'}, {'w': 'x', 'y': 'X'},],
        'diff_len_lists': ['X'],
    }
    assertion = assertions.JsonAssertion()
    for field, struct in assertion_data.items():
      assertion.Matches(field, struct)

    context = updates.Context(
        {'data': assertion_data}, 'data', updates.Mode.RESULT)
    failures = assertion.Check(context, actual)
    self.assertEqual(7, len(failures))

    for f in failures:
      f.Update([updates.Mode.RESULT])
    self.assertEqual('bar', assertion_data['foo'])
    self.assertEqual('c', assertion_data['a']['b'])
    self.assertEqual('k', assertion_data['h']['i']['j'])
    self.assertEqual('t', assertion_data['scalar_list'][1])
    self.assertEqual('t', assertion_data['dict_list'][0]['s'])
    self.assertEqual('z', assertion_data['dict_list'][1]['y'])
    self.assertEqual([{'a': 'b'}, 'b', 'c'], assertion_data['diff_len_lists'])