Exemplo n.º 1
0
def test_request_matcher():
    # Given
    server = MagicMock()
    request = HttpRequestBuilder().with_path("/test").and_method("GET").build()
    server.get_actual_requests.return_value = [request, request]

    # When

    # Then
    assert_that(server, had_request().with_path("/test").and_method("GET"))
    assert_that(server, had_request().with_times(2).and_path("/test").and_method("GET"))
    assert_that(server, not_(had_request().with_path("/somewhereelse").and_method("GET")))
    assert_that(
        had_request().with_path("/sausages").and_method("PUT"),
        has_string("call with method: 'PUT' path: '/sausages'"),
    )
    assert_that(
        had_request().with_times(4).and_query(has_entries(a="b")).and_body("chips"),
        has_string(
            "<4> call(s) with query parameters: a dictionary containing {'a': 'b'} body: 'chips'"
        ),
    )
    assert_that(
        had_request().with_path("/sausages").and_method("PUT").and_times(99),
        mismatches_with(
            server,
            all_of(
                contains_string(
                    "found <0> matching requests: <[]>. All requests: <[mbtest.imposters.imposters.HttpRequest"
                ),
                contains_string("path='/test'"),
                contains_string("method='GET'"),
            ),
        ),
    )
Exemplo n.º 2
0
def test_request_matcher():
    # Given
    server = MagicMock()
    request = {"path": "/test", "method": "GET"}
    server.get_actual_requests.return_value = {"someport": [request, request]}

    # When

    # Then
    assert_that(server, had_request(path="/test", method="GET"))
    assert_that(server, had_request(path="/test", method="GET", times=2))
    assert_that(server, not_(had_request(path="/somewhereelse", method="GET")))
    assert_that(
        had_request(path="/sausages", method="PUT"),
        has_string("call with method: 'PUT' path: '/sausages'"),
    )
    assert_that(
        had_request(path="/sausages", times=4), has_string("<4> call(s) with path: '/sausages'")
    )
    assert_that(
        had_request(path="/sausages", method="PUT"),
        mismatches_with(
            server,
            all_of(
                contains_string("found <0> matching requests: <[]>. All requests: <[{"),
                contains_string("'path': '/test'"),
                contains_string("'method': 'GET'"),
            ),
        ),
    )
Exemplo n.º 3
0
def test_has_row():
    # Given
    soup = BeautifulSoup(HTML, "html.parser")
    table = soup.table
    should_match = has_row(
        index_matches=2,
        row_matches=has_class("bazz"),
        cells_match=contains_exactly(tag_has_string("fizz"),
                                     tag_has_string("buzz")),
    )
    should_not_match_1 = has_row(
        index_matches=2,
        row_matches=has_class("bazz"),
        cells_match=contains_exactly(tag_has_string("egg"),
                                     tag_has_string("chips")),
    )
    should_not_match_2 = has_row(
        index_matches=3,
        row_matches=has_class("bazz"),
        cells_match=contains_exactly(tag_has_string("fizz"),
                                     tag_has_string("buzz")),
    )
    should_not_match_3 = has_row(
        index_matches=2,
        row_matches=has_class("eden"),
        cells_match=contains_exactly(tag_has_string("fizz"),
                                     tag_has_string("buzz")),
    )

    # Then
    assert_that(table, should_match)
    assert_that(table, not_(should_not_match_1))
    assert_that(table, not_(should_not_match_2))
    assert_that(table, not_(should_not_match_3))
    assert_that(
        should_match,
        has_string(
            "table with row "
            "cells matching a sequence containing [tag with string matching 'fizz', tag with string matching 'buzz'] "
            "row matching tag with class matching 'bazz' "
            "index matching <2>"),
    )
    assert_that(
        has_row(row_matches=has_class("banana")),
        has_string(
            "table with row row matching tag with class matching 'banana'"),
    )
    assert_that(
        should_not_match_1,
        mismatches_with(
            table,
            all_of(
                starts_with(f"was {table}"),
                contains_string("found rows:"),
                contains_string("<tr><td>baz</td><td>qux</td></tr>"),
            ),
        ),
    )
Exemplo n.º 4
0
def test_call_has_positional_arg():
    # Given
    m = mock.MagicMock()

    # When
    m("first", "second", "third")
    call = m.mock_calls[0]

    # Then
    assert_that(call, call_has_arg(1, "second"))
    assert_that(call, call_has_arg(2, "third"))
    assert_that(call, not_(call_has_arg(4, "nope")))
    assert_that(call, call_has_arg(1, contains_string("eco")))
    assert_that(
        call_has_arg(1, contains_string("eco")),
        has_string(
            "mock.call with argument index <1> matching a string containing 'eco'"
        ),
    )
    assert_that(
        call_has_arg(1, "fifth"),
        mismatches_with(
            call, "got mock.call with argument index <1> with value 'second'"),
    )
    assert_that(
        call_has_arg(4, "nope"),
        mismatches_with(call, "got mock.call with without argument index <4>"),
    )
Exemplo n.º 5
0
def test_has_id_tag():
    # Given
    should_match = has_id_tag("fish", has_class("banana"))
    should_not_match_1 = has_id_tag("fish", has_class("foo"))
    should_not_match_2 = has_id_tag("grrgug", anything())

    assert_that(HTML, should_match)
    assert_that(HTML, not_(should_not_match_1))
    assert_that(HTML, not_(should_not_match_2))
    assert_that(
        should_match,
        has_string(
            matches_regexp(
                r"HTML with tag id=['<]fish['>] matching tag with class matching 'banana'"
            )),
    )
    assert_that(
        should_not_match_1,
        mismatches_with(
            HTML,
            matches_regexp(
                r"""got HTML with tag id=['<]fish['>] values """
                r"""\['<div class="banana grapes" id="fish"><p>Some text.</p></div>'\]"""
            ),
        ),
    )
    assert_that(
        should_not_match_2,
        mismatches_with(
            HTML,
            matches_regexp(
                r"got HTML with tag id=['<]grrgug['>] values \[\]")),
    )
Exemplo n.º 6
0
def test_nested_identical_properties():
    # Given
    class SomeClass(object):
        def __init__(self, a, b, c):
            self.a = a
            self.b = b
            self._c = c

        @property
        def c(self):
            return self._c

        def some_method(self):
            pass

    a = SomeClass(1, SomeClass(2, 3, 4), 4)
    b = SomeClass(1, SomeClass(2, 3, 4), 4)
    c = SomeClass(1, SomeClass(2, 4, 5), 6)

    # Then
    assert_that(a, has_identical_properties_to(b))
    assert_that(a, not_(has_identical_properties_to(c)))
    assert_that(
        has_identical_properties_to(a),
        has_string(f"object with identical properties to object {a}"),
    )
    assert_that(has_identical_properties_to(a), mismatches_with(c, f"was {c}"))
Exemplo n.º 7
0
def test_url_with_path_segments():
    should_match = is_url().with_path_segments(
        contains_exactly("path1", "path2", "path3"))
    should_not_match = is_url().with_path_segments(empty())

    assert_that(URL, should_match)
    assert_that(URL, not_(should_not_match))

    assert_that(
        should_match,
        has_string(
            "URL with path segments: a sequence containing ['path1', 'path2', 'path3']"
        ),
    )
    assert_that(
        should_not_match,
        mismatches_with(
            URL,
            "was URL with path segments: was <['path1', 'path2', 'path3']>"),
    )
    assert_that(
        should_match,
        matches_with(
            URL,
            "was URL with path segments: was <['path1', 'path2', 'path3']>"),
    )
Exemplo n.º 8
0
def test_call_has_keyword_arg():
    # Given
    m = mock.MagicMock()

    # When
    m(f="first", s="second", t="third")
    call = m.mock_calls[0]

    # Then
    assert_that(call, call_has_arg("s", "second"))
    assert_that(call, not_(call_has_arg("s", "nope")))
    assert_that(call, not_(call_has_arg("w", "nope")))
    assert_that(call, call_has_arg("s", contains_string("eco")))
    assert_that(
        call_has_arg("s", contains_string("eco")),
        has_string(
            "mock.call with keyword argument 's' matching a string containing 'eco'"
        ),
    )
    assert_that(
        call_has_arg("s", "fifth"),
        mismatches_with(
            call,
            "got mock.call with keyword argument 's' with value 'second'"),
    )
    assert_that(
        call_has_arg("n", "nope"),
        mismatches_with(call,
                        "got mock.call with without keyword argument 'n'"),
    )
Exemplo n.º 9
0
def test_email_builder():
    # Given
    builder = (EmailMessageBuilder().with_body_text("foo bar baz").and_to(
        "*****@*****.**",
        "banana").and_cc("*****@*****.**", "apple").and_bcc(
            "*****@*****.**", "orange").and_from(
                "*****@*****.**",
                "Simon Brunning (he/him)").and_subject("I like chips"))

    # When
    email_message = builder.build()

    # Then
    assert_that(email_message, instance_of(MIMEText))
    assert_that(
        email_message,
        all_of(
            has_string(contains_string("bar")),
            has_entries({
                "To": "banana <*****@*****.**>",
                "CC": "apple <*****@*****.**>",
                "BCC": "orange <*****@*****.**>",
                "From": '"Simon Brunning (he/him)" <*****@*****.**>',
                "subject": "I like chips",
            }),
        ),
    )
Exemplo n.º 10
0
def test_identical_properties():
    # Given
    class SomeClass(ReprFromDict):
        def __init__(self, a, b):
            self.a = a
            self.b = b

    class OtherClass(ReprFromDict):
        def __init__(self, a, b):
            self.a = a
            self._b = b

        @property
        def b(self):
            return self._b

    class YetAnotherClass(ReprFromDict):
        def __init__(self, a, b):
            self.a = a
            self.b = b

    a = SomeClass(1, 2)
    b = OtherClass(1, 2)
    c = YetAnotherClass(1, 3)

    # Then
    assert_that(a, has_identical_properties_to(b))
    assert_that(a, not_(has_identical_properties_to(c)))
    assert_that(
        has_identical_properties_to(a),
        has_string(f"object with identical properties to object <{a}>"),
    )
    assert_that(has_identical_properties_to(a),
                mismatches_with(c, f"was <{c}>"))
def test_column_field_can_be_marked_as_internal(engine):
    Base = declarative_base()

    class AuthorRecord(Base):
        __tablename__ = "author"

        c_id = Column(Integer, primary_key=True)
        c_name = Column(Unicode, nullable=False)

    class Author(SqlAlchemyObjectType):
        __model__ = AuthorRecord

        id = column_field(AuthorRecord.c_id, internal=True)
        name = column_field(AuthorRecord.c_name)

    class Root(RootType):
        authors = many(lambda: select(Author))

    Base.metadata.create_all(engine)

    result = executor(Root)("""{
        authors {
            id
        }
    }""",
                            context=QueryContext(session=Session(engine)))
    assert_that(
        result,
        is_invalid_result(errors=contains_inanyorder(
            has_string(starts_with('Cannot query field "id"')), )),
    )
Exemplo n.º 12
0
def test_url_with_query():
    should_match = is_url().with_query(
        has_entries(key1="value1", key2="value2"))
    should_not_match = is_url().with_query(
        has_entries(key1="value1", key2="nope"))

    assert_that(URL, should_match)
    assert_that(URL, not_(should_not_match))

    assert_that(
        should_match,
        has_string(
            "URL with query: a dictionary containing {'key1': 'value1', 'key2': 'value2'}"
        ),
    )
    assert_that(
        should_not_match,
        mismatches_with(URL,
                        "was URL with query: value for 'key2' was 'value2'"))
    assert_that(
        should_match,
        matches_with(
            URL,
            "was URL with query: was <{'key1': 'value1', 'key2': 'value2'}>"),
    )
Exemplo n.º 13
0
def test_has_rows(db):
    assert_that(
        db,
        has_table_with_rows(
            "sausages",
            contains_inanyorder(
                has_properties(kind="cumberland"),
                has_properties(kind="lincolnshire"),
                has_properties(kind="vegetarian"),
            ),
        ),
    )
    assert_that(
        db,
        not_(
            has_table_with_rows("sausages",
                                has_item(has_properties(kind="vegan")))))
    assert_that(
        db,
        not_(
            has_table_with_rows(
                "bacon",
                contains_exactly(has_properties(kind="smoked"),
                                 has_properties(kind="unsmoked")),
            )),
    )
    assert_that(
        has_table_with_rows(
            "sausages",
            contains_exactly(has_properties(kind="cumberland"),
                             has_properties(kind="lincolnshire")),
        ),
        has_string(
            matches_regexp(
                r"DB connection with table 'sausages' with rows matching a sequence containing \["
                r"\(?an object with a property 'kind' matching 'cumberland'\)?, "
                r"\(?an object with a property 'kind' matching 'lincolnshire'\)?"
                r"\]")),
    )
    assert_that(
        has_table_with_rows("sausages",
                            has_item(has_properties(kind="vegan"))),
        mismatches_with(
            db,
            all_of(contains_string("was <["),
                   contains_string("RowTuple(kind='vegetarian', rating=0)")),
        ),
    )
    assert_that(
        has_table_with_rows(
            "bacon",
            contains_exactly(has_properties(kind="smoked"),
                             has_properties(kind="unsmoked")),
        ),
        mismatches_with(
            db,
            "SQL statement 'SELECT * FROM bacon;' gives 'OperationalError' <no such table: bacon>",
        ),
    )
Exemplo n.º 14
0
def has_error(message='', trace=''):
    return has_property('{}test-cases',
                        has_property('test-case',
                                     has_property('failure',
                                                  has_properties({
                                                                  'message': message,
                                                                  'stack-trace': has_string(trace)
                                                                  }))))
Exemplo n.º 15
0
def assert_deprecated(message, matcher):
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")

        matcher(anything()).matches("", StringDescription())

        assert_that(
            w, has_item(has_properties(category=DeprecationWarning, message=has_string(message)))
        )
Exemplo n.º 16
0
def test_response_matcher_builder():
    # Given
    stub_response = MOCK_RESPONSE
    matcher = (is_response().with_status_code(200).and_body(
        "sausages").and_content(b"content").and_json(has_entries(
            a="b")).and_headers(has_entries(key="value")).and_cookies(
                has_entries(name="value")).and_elapsed(
                    between(timedelta(seconds=1),
                            timedelta(minutes=1))).and_history(
                                contains_exactly(
                                    is_response().with_url(
                                        is_url().with_path("/path1")),
                                    is_response().with_url(
                                        is_url().with_path("/path2")),
                                )).and_url(is_url().with_path(
                                    "/path0")).and_encoding("utf-8"))
    mismatcher = is_response().with_body("kale").and_status_code(404)

    # When

    # Then
    assert_that(stub_response, matcher)
    assert_that(stub_response, not_(mismatcher))
    assert_that(
        matcher,
        has_string(
            "response with "
            "status_code: <200> "
            "body: 'sausages' "
            "content: <b'content'> "
            "json: a dictionary containing {'a': 'b'} "
            "headers: a dictionary containing {'key': 'value'} "
            "cookies: a dictionary containing {'name': 'value'} "
            "elapsed: (a value greater than or equal to <0:00:01> and a value less than or equal to <0:01:00>) "
            "history: a sequence containing "
            "[response with url: URL with path: '/path1', response with url: URL with path: '/path2'] "
            "url: URL with path: '/path0' "
            "encoding: 'utf-8'"),
    )
    assert_that(
        mismatcher,
        mismatches_with(
            stub_response,
            contains_string(
                "was response with status code: was <200> body: was 'sausages'"
            ),
        ),
    )
    assert_that(
        matcher,
        matches_with(
            stub_response,
            contains_string(
                "was response with status code: was <200> body: was 'sausages'"
            ),
        ),
    )
Exemplo n.º 17
0
def autoscaler_fails(context):
    # If the signal doesn't return a ClustermanSignalError it's a problem with the autoscaler
    expected_error = 'signal evaluation failed'
    context.batch.autoscaler.signal.evaluate.side_effect = ValueError(expected_error)
    try:
        context.batch.run()
    except ValueError as e:
        # Make sure that we're not masking an error somewhere
        assert_that(e, has_string(expected_error))
Exemplo n.º 18
0
    def test_syntax_errors_are_reported(self):
        query = " "

        result = self.execute(query)
        assert_that(
            result,
            is_invalid_result(errors=contains(
                all_of(instance_of(GraphQLError),
                       has_string(starts_with("Syntax Error"))), ), ))
Exemplo n.º 19
0
def test_contains_bytestring():
    should_match = contains_bytestring(b"foo")
    should_not_match = contains_bytestring(b"bar")

    assert_that(b"a foo b", should_match)
    assert_that(b"a foo b", not_(should_not_match))

    assert_that(should_match, has_string("bytestring containing <b'foo'>"))
    assert_that(should_not_match, mismatches_with(b" a foo b", "was <b' a foo b'>"))
Exemplo n.º 20
0
def test_internal_fields_cannot_be_queried_directly():
    AuthorRecord = attr.make_class("AuthorRecord", ["id", "name"])
    BookRecord = attr.make_class("BookRecord", ["author_id", "title"])

    class Author(StaticDataObjectType):
        __records__ = [
            AuthorRecord("PGW", "PG Wodehouse"),
            AuthorRecord("JH", "Joseph Heller"),
        ]

        id = field(type=String)
        name = field(type=String)

    class Book(StaticDataObjectType):
        __records__ = [
            BookRecord("PGW", "Leave it to Psmith"),
            BookRecord("PGW", "The Code of the Woosters"),
        ]

        author_id = field(type=String, internal=True)
        author = single(lambda: StaticDataObjectType.select(
            Author,
            join={Book.author_id: Author.id},
        ))
        title = field(type=String)

    class Root(RootType):
        books = many(lambda: StaticDataObjectType.select(Book))

    execute = executor(Root)
    assert_that(
        execute("{ books { title authorId } }"),
        is_invalid_result(errors=contains_inanyorder(
            has_string(starts_with('Cannot query field "authorId"')), )),
    )
    # Check that internal fields can still be used for joining
    assert_that(
        execute("{ books { title author { name } } }"),
        is_successful_result(
            data={
                "books": [
                    {
                        "title": "Leave it to Psmith",
                        "author": {
                            "name": "PG Wodehouse"
                        }
                    },
                    {
                        "title": "The Code of the Woosters",
                        "author": {
                            "name": "PG Wodehouse"
                        }
                    },
                ],
            }),
    )
Exemplo n.º 21
0
    def test_single_relationship_raises_error_if_there_are_multiple_matching_results(
            self):
        class Root(RootType):
            author = single(lambda: self._join_to_authors(count=2))

        result = executor(Root)("{ author { name } }")
        assert_that(
            result,
            is_invalid_result(errors=contains_inanyorder(
                has_string("Expected 1 value but got 2"), )))
Exemplo n.º 22
0
def test_is_weekday():
    assert_that(datetime.date(1968, 7, 19), is_weekday())
    assert_that(datetime.date(1968, 7, 21), not_(is_weekday()))

    assert_that(is_weekday(), has_string("A weekday"))
    assert_that(
        is_weekday(),
        mismatches_with(datetime.date(1968, 7, 21),
                        "was <1968-07-21> with weekday <6>, a Sunday"),
    )
Exemplo n.º 23
0
def test_HasWeekday():
    assert_that(datetime.date(1968, 7, 21), HasWeekday(6))
    assert_that(datetime.date(1968, 7, 21), not_(HasWeekday(2)))

    assert_that(HasWeekday(2), has_string("Date with weekday matching <2>"))
    assert_that(
        HasWeekday(2),
        mismatches_with(datetime.date(1968, 7, 21),
                        "was <1968-07-21> with weekday <6>, a Sunday"),
    )
Exemplo n.º 24
0
def test_between():
    # Given
    r = 2

    # When

    # Then
    assert_that(r, between(1, 3))
    assert_that(r, not_(between(4, 6)))
    assert_that(
        between(1, 3),
        has_string(
            "(a value greater than or equal to <1> and a value less than or equal to <3>)"
        ),
    )
    assert_that(
        between(1, 3, lower_inclusive=False, upper_inclusive=False),
        has_string("(a value greater than <1> and a value less than <3>)"),
    )
    assert_that(between(4, 6), mismatches_with(3, contains_string("was <3>")))
Exemplo n.º 25
0
def assert_deprecated(message, matcher):
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")

        matcher(anything()).matches("", StringDescription())

        assert_that(w,
                    has_item(
                        has_properties(
                            category=DeprecationWarning,
                            message=has_string(message))))
Exemplo n.º 26
0
def has_error(message='', trace=''):
    return has_property(
        '{}test-cases',
        has_property(
            'test-case',
            has_property(
                'failure',
                has_properties({
                    'message': message,
                    'stack-trace': has_string(trace)
                }))))
Exemplo n.º 27
0
    def test_query_is_validated_on_execution(self):
        query = """{
            x
        }"""

        result = self.execute(query)
        assert_that(
            result,
            is_invalid_result(errors=contains(
                all_of(instance_of(GraphQLError),
                       has_string('Cannot query field "x" on type "Root".')),
            ), ))
Exemplo n.º 28
0
def test_url_with_password():
    should_match = is_url().with_password("password")
    should_not_match = is_url().with_password("nope")

    assert_that(URL, should_match)
    assert_that(URL, not_(should_not_match))

    assert_that(should_match, has_string("URL with password: '******'"))
    assert_that(should_not_match,
                mismatches_with(URL, "was URL with password: was 'password'"))
    assert_that(should_match,
                matches_with(URL, "was URL with password: was 'password'"))
Exemplo n.º 29
0
def test_url_with_host():
    should_match = is_url().with_host("brunni.ng")
    should_not_match = is_url().with_host("example.com")

    assert_that(URL, should_match)
    assert_that(URL, not_(should_not_match))

    assert_that(should_match, has_string("URL with host: 'brunni.ng'"))
    assert_that(should_not_match,
                mismatches_with(URL, "was URL with host: was 'brunni.ng'"))
    assert_that(should_not_match,
                mismatches_with(URL, "was URL with host: was 'brunni.ng'"))
Exemplo n.º 30
0
def test_has_table(db):
    assert_that(db, has_table("sausages"))
    assert_that(db, not_(has_table("bacon")))
    assert_that(has_table("sausages"),
                has_string("DB connection has table named 'sausages'"))
    assert_that(
        has_table("bacon"),
        mismatches_with(
            db,
            "SQL statement 'SELECT * FROM bacon;' gives 'OperationalError' <no such table: bacon>",
        ),
    )
Exemplo n.º 31
0
def test_url_with_port():
    should_match = is_url().with_port(1234)
    should_not_match = is_url().with_port(5678)

    assert_that(URL, should_match)
    assert_that(URL, not_(should_not_match))

    assert_that(should_match, has_string("URL with port: <1234>"))
    assert_that(should_not_match,
                mismatches_with(URL, "was URL with port: was <1234>"))
    assert_that(should_match, matches_with(URL,
                                           "was URL with port: was <1234>"))
Exemplo n.º 32
0
def test_has_repr():
    # Given
    r = [1, "2"]

    # When

    # Then
    assert_that(r, has_repr(contains_string("[1, '2']")))
    assert_that(r, has_repr(contains_string("[1")))
    assert_that(has_repr("a"),
                has_string("an object with repr() matching 'a'"))
    assert_that(has_repr("a"), mismatches_with("b", "was 'b'"))
Exemplo n.º 33
0
def ExtraConfData_test():
  wrap = RequestWrap( PrepareJson() )
  assert_that( wrap[ 'extra_conf_data' ], empty() )

  wrap = RequestWrap( PrepareJson( extra_conf_data = { 'key': [ 'value' ] } ) )
  extra_conf_data = wrap[ 'extra_conf_data' ]
  assert_that( extra_conf_data, has_entry( 'key', contains( 'value' ) ) )
  assert_that(
    extra_conf_data,
    has_string( matches_regexp( "^<HashableDict {u?'key': \[u?'value'\]}>$" ) )
  )

  # Check that extra_conf_data can be used as a dictionary's key.
  assert_that( { extra_conf_data: 'extra conf data' },
               has_entry( extra_conf_data, 'extra conf data' ) )

  # Check that extra_conf_data's values are immutable.
  extra_conf_data[ 'key' ].append( 'another_value' )
  assert_that( extra_conf_data, has_entry( 'key', contains( 'value' ) ) )
Exemplo n.º 34
0
def has_error(message='', trace='', status=Status.FAILED):
    return has_property('{}test-cases',
                        has_property('test-case',
                                     all_of(has_property('attrib', has_entry('status', status)),
                                            has_property('failure',
                                                         has_properties({'message': message,
                                                                         'stack-trace': has_string(trace)
                                                                         })))))