Wraps a resolver with a mapping of overrides. This can be used to make local DNS changes (e.g. for testing) without modifying system-wide settings. The mapping can be in three formats:: { # Hostname to host or ip "example.com": "127.0.1.1",
| 537 | |
| 538 | |
| 539 | class OverrideResolver(Resolver): |
| 540 | """Wraps a resolver with a mapping of overrides. |
| 541 | |
| 542 | This can be used to make local DNS changes (e.g. for testing) |
| 543 | without modifying system-wide settings. |
| 544 | |
| 545 | The mapping can be in three formats:: |
| 546 | |
| 547 | { |
| 548 | # Hostname to host or ip |
| 549 | "example.com": "127.0.1.1", |
| 550 | |
| 551 | # Host+port to host+port |
| 552 | ("login.example.com", 443): ("localhost", 1443), |
| 553 | |
| 554 | # Host+port+address family to host+port |
| 555 | ("login.example.com", 443, socket.AF_INET6): ("::1", 1443), |
| 556 | } |
| 557 | |
| 558 | .. versionchanged:: 5.0 |
| 559 | Added support for host-port-family triplets. |
| 560 | """ |
| 561 | |
| 562 | def initialize(self, resolver: Resolver, mapping: dict) -> None: |
| 563 | self.resolver = resolver |
| 564 | self.mapping = mapping |
| 565 | |
| 566 | def close(self) -> None: |
| 567 | self.resolver.close() |
| 568 | |
| 569 | def resolve( |
| 570 | self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC |
| 571 | ) -> Awaitable[List[Tuple[int, Any]]]: |
| 572 | if (host, port, family) in self.mapping: |
| 573 | host, port = self.mapping[(host, port, family)] |
| 574 | elif (host, port) in self.mapping: |
| 575 | host, port = self.mapping[(host, port)] |
| 576 | elif host in self.mapping: |
| 577 | host = self.mapping[host] |
| 578 | return self.resolver.resolve(host, port, family) |
| 579 | |
| 580 | |
| 581 | # These are the keyword arguments to ssl.wrap_socket that must be translated |
no outgoing calls