collection of python libs developed for testing purposes

hoover.py 47KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387
  1. # coding=utf-8
  2. import collections
  3. import csv
  4. import difflib
  5. import hashlib
  6. import inspect
  7. import itertools
  8. import json
  9. import operator
  10. import time
  11. from copy import deepcopy
  12. ###############################################################################
  13. ## The Motor ##
  14. ###############################################################################
  15. def regression_test(argsrc, tests, driver_settings, cleanup_hack=None,
  16. apply_hacks=None, on_next=None):
  17. """Perform regression test with argsets from `argsrc`.
  18. For each argset pulled from source, performs one comparison
  19. per driver pair in `tests`, which is list of tuples with
  20. comparison function and pair of test driver classes: `(operator,
  21. oracle_class, result_class)`. (The classes are assumed to
  22. be sub-classes of `hoover.BaseTestDriver`.)
  23. `driver_settings` is a dictionary supposed to hold environmental
  24. values for all the drivers, the keys having form "DriverName.
  25. settingName". Each driver is then instantiated with this
  26. dict, and gets a copy of the dict with settings only intended
  27. for itself (and the "DriverName" part stripped).
  28. If comparison fails, report is generated using `hoover.jsDiff()`,
  29. and along with affected arguments stored in `hoover.Tracker`
  30. instance, which is finally used as a return value. This instance
  31. then contains method for basic stats as well as method to format
  32. the final report and a helper method to export argument sets
  33. as a CSV files.
  34. Supports hacks, which are a data transformations performed by
  35. `hoover.TinyCase` class and are intended to avoid known bugs
  36. and anomalies (`apply_hacks`) or clean up data structures of
  37. irrelevant data (`cleanup_hack`, performed only if the comparison
  38. function provided along with driver pair is not "equals").
  39. A function can be provided as `on_next` argument, that will be
  40. called after pulling each argument set, with last argument set
  41. (or `None`) as first argument and current one as second argument.
  42. """
  43. # TODO: do not parse driver_settings thousands of times (use a view class?)
  44. on_next = on_next if on_next else lambda a, b: None
  45. apply_hacks = apply_hacks if apply_hacks else []
  46. tracker = Tracker()
  47. last_argset = None
  48. all_classes = set(reduce(lambda a, b: a+b,
  49. [triple[1:] for triple in tests]))
  50. counter = StatCounter()
  51. for argset in argsrc:
  52. on_start = time.time()
  53. on_next(argset, last_argset)
  54. counter.add('on_next', time.time() - on_start)
  55. ## load the data first, only once for each driver
  56. #
  57. data = {}
  58. for aclass in all_classes:
  59. try:
  60. aclass.check_values(argset)
  61. except NotImplementedError: # let them bail out
  62. counter.count_for(aclass, 'bailouts')
  63. pass
  64. else:
  65. data[aclass], duration, overhead = get_data_and_stats(
  66. aclass, argset, driver_settings)
  67. counter.count_for(aclass, 'calls')
  68. counter.add_for(aclass, 'duration', duration)
  69. counter.add_for(aclass, 'overhead', overhead)
  70. for match_op, oclass, rclass in tests:
  71. # skip test if one of classes bailed out on the argset
  72. if oclass not in data or rclass not in data:
  73. continue
  74. diff = None
  75. case = TinyCase({
  76. 'argset': argset,
  77. 'oracle': deepcopy(data[oclass]),
  78. 'result': deepcopy(data[rclass]),
  79. 'oname': oclass.__name__,
  80. 'rname': rclass.__name__
  81. })
  82. hacks_done = sum([case.hack(h) for h in apply_hacks])
  83. counter.add_for(oclass, 'ohacks', hacks_done)
  84. counter.add_for(rclass, 'rhacks', hacks_done)
  85. counter.add('hacks', hacks_done)
  86. counter.add('hacked_cases', (1 if hacks_done else 0))
  87. if not match_op(case['oracle'], case['result']):
  88. # try to clean up so that normally ignored items
  89. # do not clutter up the report
  90. if not match_op == operator.eq:
  91. case.hack(cleanup_hack)
  92. if match_op(case['oracle'], case['result']):
  93. raise RuntimeError("cleanup ate error")
  94. diff = jsDiff(dira=case['oracle'],
  95. dirb=case['result'],
  96. namea=case['oname'],
  97. nameb=case['rname'])
  98. tracker.update(diff, argset)
  99. counter.count('cases')
  100. tracker.argsets_done += 1
  101. last_argset = argset
  102. counter.count('argsets')
  103. tracker.driver_stats = counter.all_stats()
  104. return tracker
  105. def get_data_and_stats(driverClass, argset, driver_settings):
  106. """Run test with given driver"""
  107. start = time.time()
  108. d = driverClass()
  109. d.setup(driver_settings, only_own=True)
  110. d.run(argset)
  111. return (d.data, d.duration, time.time() - d.duration - start)
  112. def get_data(driverClass, argset, driver_settings):
  113. """Run test with given driver"""
  114. d = driverClass()
  115. d.setup(driver_settings, only_own=True)
  116. d.run(argset)
  117. return d.data
  118. ###############################################################################
  119. ## The Pattern ##
  120. ###############################################################################
  121. class _BaseRuleOp():
  122. def __init__(self, items, item_ok):
  123. self._items = items
  124. self._item_ok = item_ok
  125. def _eval(self, item):
  126. try: # it's a pattern! (recurse)
  127. return RuleOp.Match(item, self._item_ok)
  128. except ValueError: # no, it's something else...
  129. return self._item_ok(item)
  130. def __nonzero__(self):
  131. try:
  132. return self._match()
  133. except TypeError:
  134. raise ValueError("items must be an iterable: %r" % self._items)
  135. class RuleOp():
  136. class ALL(_BaseRuleOp):
  137. def _match(self):
  138. return all(self._eval(item) for item in self._items)
  139. class ANY(_BaseRuleOp):
  140. def _match(self):
  141. return any(self._eval(item) for item in self._items)
  142. @staticmethod
  143. def Match(pattern, item_ok):
  144. """Evaluate set of logically structured patterns using passed function.
  145. pattern has form of `(op, [item1, item2, ...])` where op can be any of
  146. pre-defined logical operators (`ALL`/`ANY`, I doubt you will ever need
  147. more) and item_ok is a function that will be used to evaluate each one
  148. in the list. In case an itemN is actually pattern as well, it will be
  149. recursed into, passing the item_ok on and on.
  150. Note that there is no data to evaluate "against", you can use closure
  151. if you need to do that.
  152. """
  153. try:
  154. op, items = pattern
  155. except TypeError:
  156. raise ValueError("pattern is not a tuple: %r" % pattern)
  157. try:
  158. assert issubclass(op, _BaseRuleOp)
  159. except TypeError:
  160. raise ValueError("invalid operator: %r" % op)
  161. except AssertionError:
  162. raise ValueError("invalid operator class: %s" % op.__name__)
  163. return bool(op(items, item_ok))
  164. ###############################################################################
  165. ## The Path ##
  166. ###############################################################################
  167. class DictPath():
  168. """Mixin that adds "path-like" behavior to the top dict of dicts.
  169. See TinyCase for description"""
  170. DIV = "/"
  171. class Path():
  172. def __init__(self, path, div):
  173. self.DIV = div
  174. self._path = path
  175. def _validate(self):
  176. try:
  177. assert self._path.startswith(self.DIV)
  178. except (AttributeError, AssertionError):
  179. raise ValueError("invalid path: %r" % self._path)
  180. def stripped(self):
  181. return self._path.lstrip(self.DIV)
  182. @classmethod
  183. def __s2path(cls, path):
  184. return cls.Path(path, cls.DIV)
  185. @classmethod
  186. def __err_path_not_found(cls, path):
  187. raise KeyError("path not found: %s" % path)
  188. @classmethod
  189. def __getitem(cls, dct, key):
  190. if cls.DIV in key:
  191. frag, rest = key.split(cls.DIV, 1)
  192. subdct = dct[frag]
  193. result = cls.__getitem(subdct, rest)
  194. else:
  195. result = dct[key]
  196. return result
  197. @classmethod
  198. def __setitem(cls, dct, key, value):
  199. if cls.DIV not in key:
  200. dct[key] = value
  201. else:
  202. frag, rest = key.split(cls.DIV, 1)
  203. subdct = dct[frag]
  204. cls.__setitem(subdct, rest, value)
  205. @classmethod
  206. def __delitem(cls, dct, key):
  207. if cls.DIV not in key:
  208. del dct[key]
  209. else:
  210. frag, rest = key.split(cls.DIV, 1)
  211. subdct = dct[frag]
  212. return cls.__delitem(subdct, rest)
  213. ## public methods
  214. #
  215. def getpath(self, path):
  216. try:
  217. return self.__getitem(self, self.__s2path(path).stripped())
  218. except (TypeError, KeyError):
  219. self.__err_path_not_found(path)
  220. def setpath(self, path, value):
  221. try:
  222. self.__setitem(self, self.__s2path(path).stripped(), value)
  223. except (TypeError, KeyError):
  224. self.__err_path_not_found(path)
  225. def delpath(self, path):
  226. try:
  227. self.__delitem(self, self.__s2path(path).stripped())
  228. except (TypeError, KeyError):
  229. self.__err_path_not_found(path)
  230. def ispath(self, path):
  231. try:
  232. self.getpath(path)
  233. return True
  234. except KeyError:
  235. return False
  236. ###############################################################################
  237. ## The Case ##
  238. ###############################################################################
  239. class TinyCase(dict, DictPath):
  240. """Abstraction of the smallest unit of testing.
  241. This class is intended to hold relevant data after the actual test
  242. and apply transformations (hacks) as defined by rules.
  243. The data form (self) is:
  244. {
  245. 'argset': {}, # argset as fed into `BaseTestDriver.run`
  246. 'oracle': {}, # data as returned from oracle driver's `run()`
  247. 'result': {}, # data as returned from result driver's `run()`
  248. 'oname': "", # name of oracle driver's class
  249. 'rname': "" # name of result driver's class
  250. }
  251. The transformation is done using the `TinyCase.hack()` method to which
  252. a list of rules is passed. Each rule is applied, and rules are expected
  253. to be in a following form:
  254. {
  255. 'drivers': [{}], # list of structures to match against self
  256. 'argsets': [{}], # -ditto-
  257. 'action_name': <Arg> # an action name with argument
  258. }
  259. For each of patterns ('drivers', argsets') present, match against self
  260. is done using function `hoover.dataMatch`, which is basically a recursive
  261. test if the pattern is a subset of the case. If none of results is
  262. negative (i.e. both patterns missing results in match), any known actions
  263. included in the rule are called. Along with action name a list or a dict
  264. providing necessary parameters is expected: this is simply passed as only
  265. parameter to corresponding method.
  266. Actions use specific way how to address elements in the structures
  267. saved in the oracle and result keys provided by `DictPath`, which makes
  268. it easy to define rules for arbitrarily complex dictionary structures.
  269. The format resembles to Unix path, where "directories" are dict
  270. keys and "root" is the `self` of the `TinyCase` instance:
  271. /oracle/temperature
  272. /result/stats/word_count
  273. Refer to each action's docstring for descriprion of their function
  274. as well as expected format of argument. The name of action as used
  275. in the reule is the name of method without leading 'a_'.
  276. Warning: All actions will silently ignore any paths that are invalid
  277. or leading to non-existent data!
  278. (This does not apply to a path leading to `None`.)
  279. """
  280. def a_exchange(self, action):
  281. """Exchange value A for value B.
  282. Expects a dict, where key is a tuple of two values `(a, b)` and
  283. value is a list of paths. For each key, it goes through the
  284. paths and if the value equals `a` it is set to `b`.
  285. """
  286. for (oldv, newv), paths in action.iteritems():
  287. for path in paths:
  288. try:
  289. curv = self.getpath(path)
  290. except KeyError:
  291. continue
  292. else:
  293. if curv == oldv:
  294. self.setpath(path, newv)
  295. def a_format_str(self, action):
  296. """Convert value to a string using format string.
  297. Expects a dict, where key is a format string, and value is a list
  298. of paths. For each record, the paths are traversed, and value is
  299. converted to string using the format string and the `%` operator.
  300. This is especially useful for floats which you may want to trim
  301. before comparison, since direct comparison of floats is unreliable
  302. on some architectures.
  303. """
  304. for fmt, paths in action.iteritems():
  305. for path in paths:
  306. if self.ispath(path):
  307. new = fmt % self.getpath(path)
  308. self.setpath(path, new)
  309. def a_even_up(self, action):
  310. """Even up structure of both dictionaries.
  311. Expects a list of two-element tuples `('/dict/a', '/dict/b')`
  312. containing pairs of path do simple dictionaries.
  313. Then the two dicts are altered to have same structure: if a key
  314. in dict "a" is missing in dict "b", it is set to `None` in "b" and
  315. vice-versa,
  316. """
  317. for patha, pathb in action:
  318. try:
  319. a = self.getpath(patha)
  320. b = self.getpath(pathb)
  321. except KeyError:
  322. continue
  323. else:
  324. for key in set(a.keys()) | set(b.keys()):
  325. if key in a and key in b:
  326. pass # nothing to do here
  327. elif key in a and a[key] is None:
  328. b[key] = None
  329. elif key in b and b[key] is None:
  330. a[key] = None
  331. else:
  332. pass # bailout: odd key but value is *not* None
  333. def a_remove(self, action):
  334. """Remove elements from structure.
  335. Expects a simple list of paths that are simply deleted fro, the
  336. structure.
  337. """
  338. for path in action:
  339. if self.ispath(path):
  340. self.delpath(path)
  341. def a_round(self, action):
  342. """Round a (presumably) float using tha `float()` built-in.
  343. Expects dict with precision (ndigits, after the dot) as a key and
  344. list of paths as value.
  345. """
  346. for ndigits, paths in action.iteritems():
  347. for path in paths:
  348. try:
  349. f = self.getpath(path)
  350. except KeyError:
  351. pass
  352. else:
  353. self.setpath(path, round(f, ndigits))
  354. known_actions = {'remove': a_remove,
  355. 'even_up': a_even_up,
  356. 'format_str': a_format_str,
  357. 'exchange': a_exchange,
  358. 'round': a_round}
  359. def hack(self, ruleset):
  360. """Apply action from each rule, if patterns match."""
  361. def driver_matches():
  362. if 'drivers' not in rule:
  363. return True
  364. else:
  365. return any(dataMatch(p, self)
  366. for p in rule['drivers'])
  367. def argset_matches():
  368. if 'argsets' not in rule:
  369. return True
  370. else:
  371. return any(dataMatch(p, self)
  372. for p in rule['argsets'])
  373. matched = False
  374. cls = self.__class__
  375. for rule in ruleset:
  376. if driver_matches() and argset_matches():
  377. matched = True
  378. for action_name in cls.known_actions:
  379. if action_name in rule:
  380. cls.known_actions[action_name](self, rule[action_name])
  381. return matched
  382. ###############################################################################
  383. ## Drivers ##
  384. ###############################################################################
  385. class DriverError(Exception):
  386. """Error encountered when obtaining driver data"""
  387. def __init__(self, message, driver):
  388. self.message = message
  389. self.driver = driver
  390. def __str__(self):
  391. result = ("\n\n"
  392. " type: %s\n"
  393. " message: %s\n"
  394. " driver: %s\n"
  395. " args: %s\n"
  396. " settings: %s\n"
  397. % (self.message.__class__.__name__,
  398. self.message,
  399. self.driver.__class__.__name__,
  400. self.driver._args,
  401. self.driver._settings))
  402. return result
  403. class DriverDataError(Exception):
  404. """Error encountered when decoding or normalizing driver data"""
  405. def __init__(self, exception, driver):
  406. self.exception = exception
  407. self.driver = driver
  408. def __str__(self):
  409. result = ("%s: %s\n"
  410. " class: %s\n"
  411. " args: %s\n"
  412. " data: %s\n"
  413. % (self.exception.__class__.__name__, self.exception,
  414. self.driver.__class__.__name__,
  415. json.dumps(self.driver._args, sort_keys=True, indent=4),
  416. json.dumps(self.driver.data, sort_keys=True, indent=4)))
  417. return result
  418. class BaseTestDriver(object):
  419. """Base class for test drivers used by `hoover.regression_test` and others.
  420. This class is used to create a test driver, which is an abstraction
  421. and encapsulation of the system being tested. Or, the driver in fact
  422. can be just a "mock" driver that provides data for comparison with
  423. a "real" driver.
  424. The minimum you need to create a working driver is to implement a working
  425. `self._get_data` method that sets `self.data`. Any exception from this
  426. method will be re-raised as DriverError with additional information.
  427. Also, you can set self.duration (in fractional seconds, as returned by
  428. standard time module) in the _get_data method, but if you don't, it is
  429. measured for you as time the method call took. This is useful if you
  430. need to fetch the data from some other driver or a gateway, and you
  431. have better mechanism to determine how long the action would take "in
  432. real life".
  433. For example, if we are testing a Java library using a Py4J gateway,
  434. we need to do some more conversions outside our testing code just to
  435. be able to use the data in our Python test. We don't want to include
  436. this in the "duration", since we are measuring the Java library, not the
  437. Py4J GW (or our ability to perform the conversions optimally). So we
  438. do our measurement within the Java machine and pass the result to the
  439. Python driver.
  440. Optionally, you can:
  441. * Make an __init__ and after calling base __init__, set
  442. * `self._mandatory_args`, a list of keys that need to be present
  443. in `args` argument to `run()`
  444. * and `self._mandatory_settings`, a list of keys that need to be
  445. present in the `settings` argument to `__init__`
  446. * implement methods
  447. * `_decode_data` and `_normalize_data`, which are intended to decode
  448. the data from any raw format it is received, and to prepare it
  449. for comparison in test,
  450. * and `_check_data`, to allow for early detection of failure,
  451. from which any exception is re-raised as a DriverDataError with
  452. some additional info
  453. * set "bailouts", a list of functions which, when passed "args"
  454. argument, return true to indicate that driver is not able to
  455. process these values (see below for explanation). If any of
  456. these functions returns true, NotImplementedError is raised.
  457. The expected workflow when using the driver is:
  458. # 1. sub-class hoover.BaseTestDriver
  459. # 2. prepare settings and args
  460. MyDriver.check_values(args) # optional, to force bailouts ASAP
  461. d = MyDriver()
  462. d.setup(settings)
  463. d.run(args)
  464. assert d.data, "no data" # evaluate the result...
  465. assert d.duration < 1 # duration of _get_data in seconds
  466. Note on bailouts: Typical strategy for which the driver is intended is
  467. that each possible combination of `args` is exhausted, and results from
  468. multiple drivers are compared to evaluate if driver, i.e. system in
  469. question is O.K.
  470. The bailouts mechanism is useful in cases, where for a certain system,
  471. a valid combination of arguments would bring the same result as another,
  472. so there is basically no value in testing both of them.
  473. Example might be a system that does not support a binary flag and
  474. behaves as if it was "on": you can simply make the test driver
  475. accept the option but "bail out" any time it is "off", therefore
  476. skipping the time-and-resource-consuming test.
  477. """
  478. bailouts = []
  479. ##
  480. # internal methods
  481. #
  482. def __init__(self):
  483. self.data = {}
  484. self.duration = None
  485. self._args = {}
  486. self._mandatory_args = []
  487. self._mandatory_settings = []
  488. self._settings = {}
  489. self._setup_ok = False
  490. def __check_mandatory(self):
  491. """validate before run()"""
  492. for key in self._mandatory_args:
  493. assert key in self._args, "missing arg: '%s'" % key
  494. for key in self._mandatory_settings:
  495. assert key in self._settings, "missing setting: '%s'" % key
  496. def __cleanup_data(self):
  497. """remove hidden data; e.g. what was only there for _check_data"""
  498. for key in self.data.keys():
  499. if key.startswith("_"):
  500. del self.data[key]
  501. ##
  502. # virtual methods
  503. #
  504. def _check_data(self):
  505. """Early check for failure"""
  506. pass
  507. def _decode_data(self):
  508. """Decode from raw data as brought by _get_data"""
  509. pass
  510. def _normalize_data(self):
  511. """Preare data for comparison (e.g. sort, split, trim...)"""
  512. pass
  513. ##
  514. # public methods
  515. #
  516. @classmethod
  517. def check_values(cls, args=None):
  518. """check args in advance before running or setting up anything"""
  519. for fn in cls.bailouts:
  520. if fn(args):
  521. raise NotImplementedError(inspect.getsource(fn))
  522. def setup(self, settings, only_own=False):
  523. """Load settings. only_own means that only settings that belong to us
  524. are loaded ("DriverClass.settingName", the first discriminating part
  525. is removed)"""
  526. if only_own:
  527. for ckey in settings.keys():
  528. driver_class_name, setting_name = ckey.split(".", 2)
  529. if self.__class__.__name__ == driver_class_name:
  530. self._settings[setting_name] = settings[ckey]
  531. else:
  532. self._settings = settings
  533. self._setup_ok = True
  534. def run(self, args):
  535. """validate, run and store data"""
  536. self._args = args
  537. assert self._setup_ok, "run() before setup()?"
  538. self.__class__.check_values(self._args)
  539. self.__check_mandatory()
  540. start = time.time()
  541. try:
  542. self._get_data() # run the test, i.e. obtain raw data
  543. except StandardError as e:
  544. raise DriverError(e, self)
  545. self.duration = (time.time() - start if self.duration is None
  546. else self.duration)
  547. try:
  548. self._decode_data() # decode raw data
  549. self._normalize_data() # normalize decoded data
  550. self._check_data() # perform arbitrarty checking
  551. except StandardError, e:
  552. raise DriverDataError(e, self)
  553. self.__cleanup_data() # cleanup (remove data['_*'])
  554. class MockDriverTrue(BaseTestDriver):
  555. """A simple mock driver, always returning True"""
  556. def _get_data(self, args):
  557. self.data = True
  558. ###############################################################################
  559. ## Helpers ##
  560. ###############################################################################
  561. class StatCounter(object):
  562. """A simple counter with formulas support."""
  563. def __init__(self):
  564. self.generic_stats = {}
  565. self.driver_stats = {}
  566. self.formulas = {}
  567. self._born = time.time()
  568. def _register(self, dname):
  569. self.driver_stats[dname] = {
  570. 'calls': 0,
  571. 'rhacks': 0,
  572. 'ohacks': 0,
  573. 'duration': 0,
  574. 'overhead': 0
  575. }
  576. ##
  577. ## Formulas. A lot of them.
  578. ##
  579. ## cumulative duration/overhead; just round to ms
  580. #
  581. self.add_formula(dname + '_overhead',
  582. lambda g, d: int(1000 * d[dname]['overhead']))
  583. self.add_formula(dname + '_duration',
  584. lambda g, d: int(1000 * d[dname]['duration']))
  585. ## average (per driver call) overhead/duration
  586. #
  587. self.add_formula(
  588. dname + '_overhead_per_call',
  589. lambda g, d: int(1000 * d[dname]['overhead'] / d[dname]['calls'])
  590. )
  591. self.add_formula(
  592. dname + '_duration_per_call',
  593. lambda g, d: int(1000 * d[dname]['duration'] / d[dname]['calls'])
  594. )
  595. ## grand totals in times: driver time, loop overhead
  596. #
  597. def gtotal_drivertime(g, d):
  598. driver_time = (sum(s['overhead'] for s in d.values())
  599. + sum(s['duration'] for s in d.values()))
  600. return int(1000 * driver_time)
  601. def gtotal_loop_overhead(g, d):
  602. driver_time = gtotal_drivertime(g, d)
  603. onnext_time = int(1000 * g['on_next'])
  604. age = int(1000 * (time.time() - self._born))
  605. return age - driver_time - onnext_time
  606. self.add_formula('gtotal_drivertime', gtotal_drivertime)
  607. self.add_formula('gtotal_loop_overhead', gtotal_loop_overhead)
  608. self.add_formula('gtotal_loop_onnext',
  609. lambda g, d: int(1000 * g['on_next']))
  610. ## average (per driver call) overhead/duration
  611. #
  612. self.add_formula(
  613. 'cases_hacked',
  614. lambda g, d: round(100 * float(g['hacked_cases']) / g['cases'], 2)
  615. )
  616. def _computed_stats(self):
  617. computed = dict.fromkeys(self.formulas.keys())
  618. for fname, fml in self.formulas.iteritems():
  619. try:
  620. v = fml(self.generic_stats, self.driver_stats)
  621. except ZeroDivisionError:
  622. v = None
  623. computed[fname] = v
  624. return computed
  625. def add_formula(self, vname, formula):
  626. """Add a function to work with generic_stats, driver_stats."""
  627. self.formulas[vname] = formula
  628. def add(self, vname, value):
  629. """Add a value to generic stat counter."""
  630. if vname in self.generic_stats:
  631. self.generic_stats[vname] += value
  632. else:
  633. self.generic_stats[vname] = value
  634. def add_for(self, dclass, vname, value):
  635. """Add a value to driver stat counter."""
  636. dname = dclass.__name__
  637. if dname not in self.driver_stats:
  638. self._register(dname)
  639. if vname in self.driver_stats[dname]:
  640. self.driver_stats[dname][vname] += value
  641. else:
  642. self.driver_stats[dname][vname] = value
  643. def count(self, vname):
  644. """Alias to add(vname, 1)"""
  645. self.add(vname, 1)
  646. def count_for(self, dclass, vname):
  647. """Alias to add_for(vname, 1)"""
  648. self.add_for(dclass, vname, 1)
  649. def all_stats(self):
  650. """Compute stats from formulas and add them to colledted data."""
  651. stats = self.generic_stats
  652. for dname, dstats in self.driver_stats.iteritems():
  653. for key, value in dstats.iteritems():
  654. stats[dname + "_" + key] = value
  655. stats.update(self._computed_stats())
  656. return stats
  657. class Tracker(dict):
  658. """Error tracker to allow for usable reports from huge regression tests.
  659. Best used as a result bearer from `regression_test`, this class keeps
  660. a simple in-memory "database" of errors seen during the regression
  661. test, and methods for interface.
  662. The basic useage is:
  663. 1. Instantiate (no parameters)
  664. 2. Each time you have a result of a test, you pass it to `update()`
  665. method along with the argument set (as a single object, typically
  666. a dict) that caused the error.
  667. If boolean value of the result is False, the object is thrown away
  668. and nothing happen. Otherwise, its string value is used as a key
  669. under which the argument set is saved.
  670. As you can see, the string is supposed to be ''as deterministic
  671. as possible'', i.e. it should provide as little information
  672. about the error as is necessary. Do not include any timestamps
  673. or "volatile" values.
  674. 3. At final stage, you can retrieve statistics as how many (distinct)
  675. errors have been recorded, what was the duration of the whole test,
  676. how many times `update()` was called, etc.
  677. 4. Optionally, you can also call `format_report()` to get a nicely
  678. formatted report with list of arguments for each error string.
  679. 5. Since in bigger tests, argument lists can grow really large,
  680. complete lists are not normally printed. Instead, you can use
  681. `write_stats_csv()`, which will create one CSV per each error,
  682. named as first 7 chars of its SHA1 (inspired by Git).
  683. Note that you need to pass an existing writable folder path.
  684. """
  685. ##
  686. # internal methods
  687. #
  688. def __init__(self):
  689. self._start = time.time()
  690. self._db = {}
  691. self.tests_done = 0
  692. self.tests_passed = 0
  693. self.argsets_done = 0
  694. self.driver_stats = {}
  695. def _csv_fname(self, errstr, prefix):
  696. """Format name of file for this error string"""
  697. return '%s/%s.csv' % (prefix, self._eid(errstr))
  698. def _eid(self, errstr):
  699. """Return EID for the error string (first 7 chars of SHA1)."""
  700. return hashlib.sha1(errstr).hexdigest()[:7]
  701. def _insert(self, errstr, argset):
  702. """Insert the argset into DB."""
  703. if not errstr in self._db:
  704. self._db[errstr] = []
  705. self._db[errstr].append(argset)
  706. def _format_error(self, errstr, max_aa=0):
  707. """Format single error for output."""
  708. argsets_affected = self._db[errstr]
  709. num_aa = len(argsets_affected)
  710. # trim if list is too long for Jenkins
  711. argsets_shown = argsets_affected
  712. if max_aa and (num_aa > max_aa):
  713. div = ["[...] not showing %s cases, see %s.csv for full list"
  714. % (num_aa - max_aa, self._eid(errstr))]
  715. argsets_shown = argsets_affected[0:max_aa] + div
  716. # format error
  717. formatted_aa = "\n".join([str(arg) for arg in argsets_shown])
  718. return ("~~~ ERROR FOUND (%s) ~~~~~~~~~~~~~~~~~~~~~~~~~\n"
  719. "--- error string: -----------------------------------\n%s\n"
  720. "--- argsets affected (%d) ---------------------------\n%s\n"
  721. % (self._eid(errstr), errstr, num_aa, formatted_aa))
  722. ##
  723. # public methods
  724. #
  725. def errors_found(self):
  726. """Return number of non-distinct errors in db."""
  727. return bool(self._db)
  728. def format_report(self, max_aa=0):
  729. """Return complete report formatted as string."""
  730. error_list = "\n".join([self._format_error(e, max_aa=max_aa)
  731. for e in self._db])
  732. return ("Found %(total_errors)s (%(distinct_errors)s distinct) errors"
  733. " in %(tests_done)s tests with %(argsets)s argsets"
  734. " (duration: %(time)ss):"
  735. % self.getstats()
  736. + "\n\n" + error_list)
  737. def getstats(self):
  738. """Return basic and driver stats
  739. argsets_done - this should must be raised by outer code,
  740. once per each unique argset
  741. tests_done - how many times Tracker.update() was called
  742. distinct_errors - how many distinct errors (same `str(error)`)
  743. were seen by Tracker.update()
  744. total_errors - how many times `Tracker.update()` saw an
  745. error, i.e. how many argsets are in DB
  746. time - how long since init (seconds)
  747. """
  748. def total_errors():
  749. return reduce(lambda x, y: x + len(y), self._db.values(), 0)
  750. stats = {
  751. "argsets": self.argsets_done,
  752. "tests_done": self.tests_done,
  753. "distinct_errors": len(self._db),
  754. "total_errors": total_errors(),
  755. "time": int(time.time() - self._start)
  756. }
  757. stats.update(self.driver_stats)
  758. return stats
  759. def update(self, error, argset):
  760. """Update tracker with test result.
  761. If `bool(error)` is true, it is considered error and argset
  762. is inserted to DB with `str(error)` as key. This allows for later
  763. sorting and analysis.
  764. """
  765. self.tests_done += 1
  766. if error:
  767. errstr = str(error)
  768. self._insert(errstr, argset)
  769. def write_stats_csv(self, fname):
  770. """Write write stats to a simple one row (plus header) CSV."""
  771. stats = self.getstats()
  772. colnames = sorted(stats.keys())
  773. with open(fname, 'a') as fh:
  774. cw = csv.DictWriter(fh, colnames)
  775. cw.writerow(dict(zip(colnames, colnames))) # header
  776. cw.writerow(stats)
  777. def write_args_csv(self, prefix=''):
  778. """Write out a set of CSV files, one per distinctive error.
  779. Each CSV is named with error EID (first 7 chars of SHA1) and lists
  780. all argument sets affected by this error. This is supposed to make
  781. easier to further analyse impact and trigerring values of errors,
  782. perhaps using a table processor software."""
  783. def get_all_colnames():
  784. cn = {}
  785. for errstr, affected in self._db.iteritems():
  786. for argset in affected:
  787. cn.update(dict.fromkeys(argset.keys()))
  788. return sorted(cn.keys())
  789. all_colnames = get_all_colnames()
  790. for errstr in self._db:
  791. with open(self._csv_fname(errstr, prefix), 'a') as fh:
  792. cw = csv.DictWriter(fh, all_colnames)
  793. cw.writerow(dict(zip(all_colnames, all_colnames))) # header
  794. for argset in self._db[errstr]:
  795. cw.writerow(argset)
  796. ## ............................................................................
  797. ## dataMatch -- a data structure matcher
  798. ##
  799. #
  800. def dataMatch(pattern, data, rmax=10, _r=0):
  801. """Check if data structure matches a pattern data structure.
  802. Supports lists, dictionaries and scalars (int, float, string).
  803. For scalars, simple `==` is used. Lists are converted to sets and
  804. "to match" means "to have a matching subset (e.g. `[1, 2, 3, 4]`
  805. matches `[3, 2]`). Both lists and dictionaries are matched recursively.
  806. """
  807. def listMatch(pattern, data):
  808. """Match list-like objects"""
  809. assert all([hasattr(o, 'append') for o in [pattern, data]])
  810. results = []
  811. for pv in pattern:
  812. if any([dataMatch(pv, dv, _r=_r+1) for dv in data]):
  813. results.append(True)
  814. else:
  815. results.append(False)
  816. return all(results)
  817. def dictMatch(pattern, data):
  818. """Match dict-like objects"""
  819. assert all([hasattr(o, 'iteritems') for o in [pattern, data]])
  820. results = []
  821. try:
  822. for pk, pv in pattern.iteritems():
  823. results.append(dataMatch(pv, data[pk], _r=_r+1))
  824. except KeyError:
  825. results.append(False)
  826. return all(results)
  827. if _r == rmax:
  828. raise RuntimeError("recursion limit hit")
  829. result = None
  830. if pattern == data:
  831. result = True
  832. else:
  833. for handler in [dictMatch, listMatch]:
  834. try:
  835. result = handler(pattern, data)
  836. except AssertionError:
  837. continue
  838. return result
  839. def jsDump(data):
  840. """A human-readable JSON dump."""
  841. return json.dumps(data, sort_keys=True, indent=4,
  842. separators=(',', ': '))
  843. def jsDiff(dira, dirb, namea="A", nameb="B", chara="a", charb="b"):
  844. """JSON-based human-readable diff of two data structures.
  845. '''BETA''' version.
  846. jsDiff is based on unified diff of two human-readable JSON dumps except
  847. that instead of showing line numbers and context based on proximity to
  848. the changed lines, it prints only context important from the data
  849. structure point.
  850. The goal is to be able to quickly tell the story of what has changed
  851. where in the structure, no matter size and complexity of the data set.
  852. For example:
  853. a = {
  854. 'w': {1: 2, 3: 4},
  855. 'x': [1, 2, 3],
  856. 'y': [3, 1, 2]
  857. }
  858. b = {
  859. 'w': {1: 2, 3: 4},
  860. 'x': [1, 1, 3],
  861. 'y': [3, 1, 3]
  862. }
  863. print jsDiff(a, b)
  864. will output:
  865. aaa ~/A
  866. "x": [
  867. a 2,
  868. "y": [
  869. a 2
  870. bbb ~/B
  871. "x": [
  872. b 1,
  873. "y": [
  874. b 3
  875. Notice that the final output somehow resembles the traditional unified
  876. diff, so to avoid confusion, +/- is changed to a/b (the characters can
  877. be provided as well as the names A/B).
  878. """
  879. def compress(lines):
  880. def is_body(line):
  881. return line.startswith(("-", "+", " "))
  882. def is_diff(line):
  883. return line.startswith(("-", "+"))
  884. def is_diffA(line):
  885. return line.startswith("-")
  886. def is_diffB(line):
  887. return line.startswith("+")
  888. def is_context(line):
  889. return line.startswith(" ")
  890. def is_hdr(line):
  891. return line.startswith(("@@", "---", "+++"))
  892. def is_hdr_hunk(line):
  893. return line.startswith("@@")
  894. def is_hdr_A(line):
  895. return line.startswith("---")
  896. def is_hdr_B(line):
  897. return line.startswith("+++")
  898. class Level(object):
  899. def __init__(self, hint):
  900. self.hint = hint
  901. self.hinted = False
  902. def __str__(self):
  903. return str(self.hint)
  904. def get_hint(self):
  905. if not self.hinted:
  906. self.hinted = True
  907. return self.hint
  908. class ContextTracker(object):
  909. def __init__(self):
  910. self.trace = []
  911. self.last_line = None
  912. self.last_indent = -1
  913. def indent_of(self, line):
  914. meat = line[1:].lstrip(" ")
  915. ind = len(line) - len(meat) - 1
  916. return ind
  917. def check(self, line):
  918. indent = self.indent_of(line)
  919. if indent > self.last_indent:
  920. self.trace.append(Level(self.last_line))
  921. elif indent < self.last_indent:
  922. self.trace.pop()
  923. self.last_line = line
  924. self.last_indent = indent
  925. def get_hint(self):
  926. return self.trace[-1].get_hint()
  927. buffa = []
  928. buffb = []
  929. ct = ContextTracker()
  930. for line in lines:
  931. if is_hdr_hunk(line):
  932. continue
  933. elif is_hdr_A(line):
  934. line = line.replace("---", chara * 3, 1)
  935. buffa.insert(0, line)
  936. elif is_hdr_B(line):
  937. line = line.replace("+++", charb * 3, 1)
  938. buffb.insert(0, line)
  939. elif is_body(line):
  940. ct.check(line)
  941. if is_diff(line):
  942. hint = ct.get_hint()
  943. if hint:
  944. buffa.append(hint)
  945. buffb.append(hint)
  946. if is_diffA(line):
  947. line = line.replace("-", chara, 1)
  948. buffa.append(line)
  949. elif is_diffB(line):
  950. line = line.replace("+", charb, 1)
  951. buffb.append(line)
  952. else:
  953. raise AssertionError("difflib.unified_diff emited"
  954. " unknown format (%s chars):\n%s"
  955. % (len(line), line))
  956. return buffa + buffb
  957. dumpa = jsDump(dira)
  958. dumpb = jsDump(dirb)
  959. udiff = difflib.unified_diff(dumpa.split("\n"), dumpb.split("\n"),
  960. "~/" + namea, "~/" + nameb,
  961. n=10000, lineterm='')
  962. return "\n".join(compress([line for line in udiff]))
  963. #
  964. ## Cartman - create dict arguments from dicts of available values (iterables)
  965. # and a defined scheme
  966. #
  967. class Cartman(object):
  968. """Create argument sets from ranges (or ay iterators) of values.
  969. This class is to enable easy definition and generation of dictionary
  970. argument sets using Cartesian product. You only need to define:
  971. * structure of argument set (can be more than just flat dict)
  972. * ranges, or arbitrary iterators of values on each "leaf" of the
  973. argument set
  974. Since there is expectation that any argument can have any kind of values
  975. even another iterables, the pure logic "iterate it if you can"
  976. is insufficient. Instead, definition is divided in two parts:
  977. * scheme, which is a "prototype" of a final argument set, except
  978. that for each value that will change, a `Cartman.Iterable`
  979. sentinel is used. For each leaf that is constant, `Cartman.Scalar`
  980. is used
  981. * source, which has the same structure, except that where in scheme
  982. is `Iterable`, an iterable object is expected, whereas in places
  983. where `Scalar` is used, a value is assigned that does not change
  984. during iteration.
  985. Finally, when such instance is used in loop, argument sets are generated
  986. uising Cartesian product of each iterable found. This allows for
  987. relatively easy definition of complex scenarios.
  988. Consider this example:
  989. You have a system (wrapped up in test driver) that takes ''size''
  990. argument, that is supposed to be ''width'', ''height'' and ''depth'',
  991. each an integer ranging from 1 to 100, and ''color'' that can
  992. be "white", "black" or "yellow".
  993. For a test using all-combinations strategy, you will need to generate
  994. 100 * 100 * 100 * 3 argument sets, i.e. 3M tests.
  995. All you need to do is:
  996. scheme = {
  997. 'size': {
  998. 'width': Cartman.Iterable,
  999. 'height': Cartman.Iterable,
  1000. 'depth': Cartman.Iterable,
  1001. }
  1002. 'color': Cartman.Iterable,
  1003. }
  1004. source = {
  1005. 'size': {
  1006. 'width': range(1, 100),
  1007. 'height': range(1, 100),
  1008. 'depth': range(1, 100),
  1009. }
  1010. 'color': ['white', 'black', 'yellow'],
  1011. }
  1012. c = Cartman(source, scheme)
  1013. for argset in c:
  1014. result = my_test(argset)
  1015. # assert ...
  1016. The main advantage is that you can separate the definition from
  1017. the code, and you can keep yor iterators as big or as small as
  1018. needed, and add / remove values.
  1019. Also in case your parameters vary in structure over time, or from
  1020. one test to another, it gets much easier to keep up with changes
  1021. without much jumping through hoops.
  1022. Note: `Cartman.Scalar` is provided mainly to make your definitions
  1023. more readable. Following constructions are functionally equal:
  1024. c = Cartman({'a': 1}, {'a': Cartman.Scalar})
  1025. c = Cartman({'a': [1]}, {'a': Cartman.Iterable})
  1026. In future, however, this might change, though, mainly in case
  1027. optimization became possible based on what was used.
  1028. """
  1029. # TODO: support for arbitrary ordering (profile / nginx)
  1030. # TODO: implement getstats and fmtstats
  1031. # TODO: N-wise
  1032. class _BaseMark(object):
  1033. pass
  1034. class Scalar(_BaseMark):
  1035. pass
  1036. class Iterable(_BaseMark):
  1037. pass
  1038. def __init__(self, source, scheme, recursion_limit=10, _r=0):
  1039. self.source = source
  1040. self.scheme = scheme
  1041. self.recursion_limit = recursion_limit
  1042. self._r = _r
  1043. if self._r > self.recursion_limit:
  1044. raise RuntimeError("recursion limit exceeded")
  1045. # validate scheme + source and throw useful error
  1046. scheme_ok = isinstance(self.scheme, collections.Mapping)
  1047. source_ok = isinstance(self.source, collections.Mapping)
  1048. if not scheme_ok:
  1049. raise ValueError("scheme must be a mapping (e.g. dict)")
  1050. elif scheme_ok and not source_ok:
  1051. raise ValueError("scheme vs. source mismatch")
  1052. def __deepcopy__(self, memo):
  1053. return Cartman(deepcopy(self.source, memo),
  1054. deepcopy(self.scheme, memo))
  1055. def _is_mark(self, subscheme):
  1056. try:
  1057. return issubclass(subscheme, Cartman._BaseMark)
  1058. except TypeError:
  1059. return False
  1060. def _means_scalar(self, subscheme):
  1061. if self._is_mark(subscheme):
  1062. return issubclass(subscheme, Cartman.Scalar)
  1063. def _means_iterable(self, subscheme):
  1064. if self._is_mark(subscheme):
  1065. return issubclass(subscheme, Cartman.Iterable)
  1066. def _get_iterable_for(self, key):
  1067. subscheme = self.scheme[key]
  1068. subsource = self.source[key]
  1069. if self._means_scalar(subscheme):
  1070. return [subsource]
  1071. elif self._means_iterable(subscheme):
  1072. return subsource
  1073. else: # try to use it as scheme
  1074. return iter(Cartman(subsource, subscheme, _r=self._r+1))
  1075. def __iter__(self):
  1076. names = []
  1077. iterables = []
  1078. keys = self.scheme.keys()
  1079. for key in keys:
  1080. try:
  1081. iterables.append(self._get_iterable_for(key))
  1082. except KeyError:
  1083. pass # ignore that subsource mentioned by scheme is missing
  1084. else:
  1085. names.append(key)
  1086. for values in itertools.product(*iterables):
  1087. yield dict(zip(names, values))
  1088. def getstats(self):
  1089. return {}
  1090. def fmtstats(self):
  1091. return ""