pythonmockingpytestdnspython

mock a dnspython dns query during testing


I have the following code that does a lookup of a domain's nameservers, using dnspython, and then looping over that list gets the IPv4 and IPv6 addresses for each server.

I am able to mock the results for resolver_list.

However, I am unsure how, or if it is possible, to mock the results for the query for the A and AAAA records since it is all part of the same test and I've mocked dns.resolver.query already.

    resolver_list = dns.resolver.query(domain, rdtype='NS', tcp=True)
    for ns in resolver_list:
        gtld_ns_server_list.append(ns.to_text().rstrip('.').lower())
        a_records.append(dns.resolver.query(ns.rstrip('.'), "A"))
        aaaa_records.append(dns.resolver.query(ns.rstrip('.'), "AAAA"))

My mock looks like this so far:

        ns = [
            ('ns1.external-server.com', 'NS'),
            ('ns2.external-server.com', 'NS'),
        ]
        responses = [[FakeRR(txt, rdtype=type) for txt, type in ns]]

        def fake_dns_query(*args, **kwargs):
            return responses.pop()

        mocker.patch(
            'site_management.validators.dns.resolver.query',
            fake_dns_query
        )

Any help is appreciated.


Solution

  • I think I got what I needed. I ended up adding additional lists to the responses variable that were then popped for the additional queries that were made for the A and AAAA records.

    There may be another way to do it, but I'm getting what I expect now at least.