1# Copyright 2009 Google Inc. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Mocks for tests."""
16
17__author__ = 'tstromberg@google.com (Thomas Stromberg)'
18
19import time
20import nameserver
21
22# external dependencies (from third_party)
23import dns.message
24import dns.rdataclass
25import dns.query
26
27GOOD_IP = '127.0.0.1'
28SLOW_IP = '9.9.9.9'
29PERFECT_IP = '127.127.127.127'
30NO_RESPONSE_IP = '10.0.0.1'
31BROKEN_IP = '192.168.0.1'
32
33class MockNameServer(nameserver.NameServer):
34  """Act like Nameserver, but do not issue any actual queries!"""
35
36  def FakeAnswer(self, request, no_answer=False):
37    if not request:
38      request = self.CreateRequest('www.com', 'A', dns.rdataclass.IN)
39
40    response_text = """id 999
41opcode QUERY
42rcode NOERROR
43flags QR RD RA
44;QUESTION
45www.paypal.com. IN A
46;ANSWER
47www.paypal.com. 159 IN A 66.211.169.65
48www.paypal.com. 159 IN A 66.211.169.2
49;AUTHORITY
50paypal.com. 3459 IN NS ppns1.den.paypal.com.
51paypal.com. 3459 IN NS ppns1.phx.paypal.com.
52paypal.com. 3459 IN NS ppns2.den.paypal.com.
53paypal.com. 3459 IN NS ppns2.phx.paypal.com.
54;ADDITIONAL
55ppns1.den.paypal.com. 165480 IN A 216.113.188.121
56ppns1.phx.paypal.com. 73170 IN A 66.211.168.226
57ppns2.den.paypal.com. 73170 IN A 216.113.188.122
58ppns2.phx.paypal.com. 73170 IN A 66.211.168.227"""
59    msg = dns.message.from_text(response_text)
60    msg.question = request.question
61    if no_answer:
62      msg.answer = None
63    return msg
64
65  def Query(self, request, timeout):
66    """Return a falsified DNS response."""
67    question = str(request.question[0])
68    if self.ip == BROKEN_IP:
69      raise dns.query.BadResponse('This sucks.')
70
71    if self.ip == NO_RESPONSE_IP:
72      answer = self.FakeAnswer(request, no_answer=True)
73    elif self.ip == GOOD_IP and  'www.google.com' in question:
74      answer = self.FakeAnswer(request, no_answer=True)
75    else:
76      answer = self.FakeAnswer(request)
77
78    if self.ip == GOOD_IP:
79      time.sleep(0.001)
80    elif self.ip == SLOW_IP:
81      time.sleep(0.03)
82    return answer
83