querying.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. from lettuce import *
  2. import subprocess
  3. import re
  4. # This script provides querying functionality
  5. # The most important step is
  6. #
  7. # query for <name> [type X] [class X] [to <addr>[:port]] should have rcode <rc>
  8. #
  9. # By default, it will send queries to 127.0.0.1:47806 unless specified
  10. # otherwise. The rcode is always checked. If the result is not NO_ANSWER,
  11. # the result will be stored in last_query_result, which can then be inspected
  12. # more closely, for instance with the step
  13. #
  14. # last query should have <property> <value>
  15. #
  16. #
  17. # define a class to easily access different parts
  18. # We may consider using our full library for this, but for now
  19. # simply store several parts of the response as text values in
  20. # this structure
  21. #
  22. # The following attributes are 'parsed' from the response, all as strings,
  23. # and end up as direct attributes of the QueryResult object:
  24. # opcode, rcode, id, flags, qdcount, ancount, nscount, adcount
  25. # (flags is one string with all flags)
  26. #
  27. # this will set 'rcode' as the result code, we 'define' one additional
  28. # rcode, "NO_ANSWER", if the dig process returned an error code itself
  29. # In this case none of the other attributes will be set.
  30. #
  31. # The different sections will be lists of strings, one for each RR in the
  32. # section. The question section will start with ';', as per dig output
  33. #
  34. # See server_from_sqlite3.feature for various examples to perform queries
  35. class QueryResult(object):
  36. status_re = re.compile("opcode: ([A-Z])+, status: ([A-Z]+), id: ([0-9]+)")
  37. flags_re = re.compile("flags: ([a-z ]+); QUERY: ([0-9]+), ANSWER: " +
  38. "([0-9]+), AUTHORITY: ([0-9]+), ADDITIONAL: ([0-9]+)")
  39. def __init__(self, name, qtype, qclass, address, port):
  40. args = [ 'dig', '+tries=1', '@' + address, '-p', str(port) ]
  41. if qtype is not None:
  42. args.append('-t')
  43. args.append(str(qtype))
  44. if qclass is not None:
  45. args.append('-c')
  46. args.append(str(qclass))
  47. args.append(name)
  48. dig_process = subprocess.Popen(args, 1, None, None, subprocess.PIPE,
  49. None)
  50. result = dig_process.wait()
  51. if result != 0:
  52. self.rcode = "NO_ANSWER"
  53. else:
  54. self.rcode = None
  55. parsing = "HEADER"
  56. self.question_section = []
  57. self.answer_section = []
  58. self.authority_section = []
  59. self.additional_section = []
  60. self.line_handler = self.parse_header
  61. for out in dig_process.stdout:
  62. self.line_handler(out)
  63. def _check_next_header(self, line):
  64. """Returns true if we found a next header, and sets the internal
  65. line handler to the appropriate value.
  66. """
  67. if line == ";; ANSWER SECTION:\n":
  68. self.line_handler = self.parse_answer
  69. elif line == ";; AUTHORITY SECTION:\n":
  70. self.line_handler = self.parse_authority
  71. elif line == ";; ADDITIONAL SECTION:\n":
  72. self.line_handler = self.parse_additional
  73. elif line.startswith(";; Query time"):
  74. self.line_handler = self.parse_footer
  75. else:
  76. return False
  77. return True
  78. def parse_header(self, line):
  79. if not self._check_next_header(line):
  80. status_match = self.status_re.search(line)
  81. flags_match = self.flags_re.search(line)
  82. if status_match is not None:
  83. self.opcode = status_match.group(1)
  84. self.rcode = status_match.group(2)
  85. elif flags_match is not None:
  86. self.flags = flags_match.group(1)
  87. self.qdcount = flags_match.group(2)
  88. self.ancount = flags_match.group(3)
  89. self.nscount = flags_match.group(4)
  90. self.adcount = flags_match.group(5)
  91. def parse_question(self, line):
  92. if not self._check_next_header(line):
  93. if line != "\n":
  94. self.question_section.append(line.strip())
  95. def parse_answer(self, line):
  96. if not self._check_next_header(line):
  97. if line != "\n":
  98. self.answer_section.append(line.strip())
  99. def parse_authority(self, line):
  100. if not self._check_next_header(line):
  101. if line != "\n":
  102. self.authority_section.append(line.strip())
  103. def parse_authority(self, line):
  104. if not self._check_next_header(line):
  105. if line != "\n":
  106. self.additional_section.append(line.strip())
  107. def parse_footer(self, line):
  108. pass
  109. @step('A query for ([\w.]+) (?:type ([A-Z]+) )?(?:class ([A-Z]+) )?' +
  110. '(?:to ([^:]+)(?::([0-9]+))? )?should have rcode ([\w.]+)')
  111. def query(step, query_name, qtype, qclass, addr, port, rcode):
  112. if qtype is None:
  113. qtype = "A"
  114. if qclass is None:
  115. qclass = "IN"
  116. if addr is None:
  117. addr = "127.0.0.1"
  118. if port is None:
  119. port = 47806
  120. query_result = QueryResult(query_name, qtype, qclass, addr, port)
  121. assert query_result.rcode == rcode,\
  122. "Expected: " + rcode + ", got " + query_result.rcode
  123. world.last_query_result = query_result
  124. @step('The SOA serial for ([\w.]+) should be ([0-9]+)')
  125. def query_soa(step, query_name, serial):
  126. query_result = QueryResult(query_name, "SOA", "IN", "127.0.0.1", "47806")
  127. assert "NOERROR" == query_result.rcode,\
  128. "Got " + query_result.rcode + ", expected NOERROR"
  129. assert len(query_result.answer_section) == 1,\
  130. "Too few or too many answers in SOA response"
  131. soa_parts = query_result.answer_section[0].split()
  132. assert serial == soa_parts[6],\
  133. "Got SOA serial " + soa_parts[6] + ", expected " + serial
  134. @step('last query response should have (\S+) (.+)')
  135. def check_last_query(step, item, value):
  136. assert world.last_query_result is not None
  137. assert item in world.last_query_result.__dict__
  138. lq_val = world.last_query_result.__dict__[item]
  139. assert str(value) == str(lq_val),\
  140. "Got: " + str(lq_val) + ", expected: " + str(value)
  141. @step('([a-zA-Z]+) section of the last query response should be')
  142. def check_last_query_section(step, section):
  143. response_string = None
  144. if section.lower() == 'question':
  145. response_string = "\n".join(world.last_query_result.question_section)
  146. elif section.lower() == 'answer':
  147. response_string = "\n".join(world.last_query_result.answer_section)
  148. elif section.lower() == 'authority':
  149. response_string = "\n".join(world.last_query_result.answer_section)
  150. elif section.lower() == 'additional':
  151. response_string = "\n".join(world.last_query_result.answer_section)
  152. else:
  153. assert False, "Unknown section " + section
  154. # replace whitespace of any length by one space
  155. response_string = re.sub("[ \t]+", " ", response_string)
  156. expect = re.sub("[ \t]+", " ", step.multiline)
  157. assert response_string.strip() == expect.strip(),\
  158. "Got:\n'" + response_string + "'\nExpected:\n'" + step.multiline +"'"