|
| 1 | +import dns.resolver |
| 2 | +import json |
| 3 | +import os.path |
| 4 | +import pytest |
| 5 | + |
| 6 | +from email_validator.deliverability import caching_resolver |
| 7 | + |
| 8 | +# To run deliverability checks without actually making |
| 9 | +# DNS queries, we use a caching resolver where the cache |
| 10 | +# is pre-loaded with DNS responses. |
| 11 | + |
| 12 | +# When False, all DNS queries must come from the mocked |
| 13 | +# data. When True, tests are run with live DNS queries |
| 14 | +# and the DNS responses are saved to a file. |
| 15 | +BUILD_MOCKED_DNS_RESPONSE_DATA = False |
| 16 | + |
| 17 | + |
| 18 | +# This class implements the 'get' and 'put' methods |
| 19 | +# expected for a dns.resolver.Resolver's cache. |
| 20 | +class MockedDnsResponseData: |
| 21 | + DATA_PATH = os.path.dirname(__file__) + "/mocked-dns-answers.json" |
| 22 | + |
| 23 | + @staticmethod |
| 24 | + def create_resolver(): |
| 25 | + if not hasattr(MockedDnsResponseData, 'INSTANCE'): |
| 26 | + # Create a singleton instance of this class and load the saved DNS responses. |
| 27 | + # Except when BUILD_MOCKED_DNS_RESPONSE_DATA is true, don't load the data. |
| 28 | + singleton = MockedDnsResponseData() |
| 29 | + if not BUILD_MOCKED_DNS_RESPONSE_DATA: |
| 30 | + singleton.load() |
| 31 | + MockedDnsResponseData.INSTANCE = singleton |
| 32 | + |
| 33 | + # Return a new dns.resolver.Resolver configured for caching |
| 34 | + # using the singleton instance. |
| 35 | + return caching_resolver(cache=MockedDnsResponseData.INSTANCE) |
| 36 | + |
| 37 | + def __init__(self): |
| 38 | + self.data = {} |
| 39 | + |
| 40 | + def load(self): |
| 41 | + # Loads the saved DNS response data from the JSON file and |
| 42 | + # re-structures it into dnspython classes. |
| 43 | + class Ans: # mocks the dns.resolver.Answer class |
| 44 | + |
| 45 | + def __init__(self, rrset): |
| 46 | + self.rrset = rrset |
| 47 | + |
| 48 | + def __iter__(self): |
| 49 | + return iter(self.rrset) |
| 50 | + |
| 51 | + with open(self.DATA_PATH) as f: |
| 52 | + data = json.load(f) |
| 53 | + for item in data: |
| 54 | + key = (dns.name.from_text(item["query"]["name"] + "."), |
| 55 | + dns.rdatatype.from_text(item["query"]["type"]), |
| 56 | + dns.rdataclass.from_text(item["query"]["class"])) |
| 57 | + rdatas = [ |
| 58 | + dns.rdata.from_text(rdtype=key[1], rdclass=key[2], tok=rr) |
| 59 | + for rr in item["answer"] |
| 60 | + ] |
| 61 | + if item["answer"]: |
| 62 | + self.data[key] = Ans(dns.rdataset.from_rdata_list(0, rdatas=rdatas)) |
| 63 | + else: |
| 64 | + self.data[key] = None |
| 65 | + |
| 66 | + def save(self): |
| 67 | + # Re-structure as a list with basic data types. |
| 68 | + data = [ |
| 69 | + { |
| 70 | + "query": { |
| 71 | + "name": key[0].to_text(omit_final_dot=True), |
| 72 | + "type": dns.rdatatype.to_text(key[1]), |
| 73 | + "class": dns.rdataclass.to_text(key[2]), |
| 74 | + }, |
| 75 | + "answer": [ |
| 76 | + rr.to_text() |
| 77 | + for rr in value |
| 78 | + ] |
| 79 | + } |
| 80 | + for key, value in self.data.items() |
| 81 | + ] |
| 82 | + with open(self.DATA_PATH, "w") as f: |
| 83 | + json.dump(data, f, indent=True) |
| 84 | + |
| 85 | + def get(self, key): |
| 86 | + # Special-case a domain to create a timeout. |
| 87 | + if key[0].to_text() == "timeout.com.": |
| 88 | + raise dns.exception.Timeout() |
| 89 | + |
| 90 | + # When building the DNS response database, return |
| 91 | + # a cache miss. |
| 92 | + if BUILD_MOCKED_DNS_RESPONSE_DATA: |
| 93 | + return None |
| 94 | + |
| 95 | + # Query the data for a matching record. |
| 96 | + if key in self.data: |
| 97 | + if not self.data[key]: |
| 98 | + raise dns.resolver.NoAnswer() |
| 99 | + return self.data[key] |
| 100 | + |
| 101 | + # Query the data for a response to an ANY query. |
| 102 | + ANY = dns.rdatatype.from_text("ANY") |
| 103 | + if (key[0], ANY, key[2]) in self.data and self.data[(key[0], ANY, key[2])] is None: |
| 104 | + raise dns.resolver.NoAnswer() |
| 105 | + |
| 106 | + raise ValueError("Saved DNS data did not contain query: {}".format(key)) |
| 107 | + |
| 108 | + def put(self, key, value): |
| 109 | + # Build the DNS data by saving the live query response. |
| 110 | + if not BUILD_MOCKED_DNS_RESPONSE_DATA: |
| 111 | + raise ValueError("Should not get here.") |
| 112 | + self.data[key] = value |
| 113 | + |
| 114 | + |
| 115 | +@pytest.fixture(scope="session", autouse=True) |
| 116 | +def MockedDnsResponseDataCleanup(request): |
| 117 | + def cleanup_func(): |
| 118 | + if BUILD_MOCKED_DNS_RESPONSE_DATA: |
| 119 | + MockedDnsResponseData.INSTANCE.save() |
| 120 | + request.addfinalizer(cleanup_func) |
0 commit comments