Advertisement
Guest User

Untitled

a guest
Feb 5th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. # coding: utf-8
  2.  
  3. from __future__ import unicode_literals
  4. from __future__ import print_function
  5. from __future__ import division
  6.  
  7.  
  8. from hypothesis.extra.datetime import datetimes
  9.  
  10. import hypothesis.strategies as st
  11.  
  12.  
  13. from sqlalchemy import (
  14. DateTime,
  15. Integer,
  16. String,
  17. )
  18. from sqlalchemy.dialects.postgresql import JSON
  19.  
  20.  
  21. def mk_generator(mapping_class, column_generators=None):
  22. """
  23. :param mapping_class: A class inhering a declarative_base()
  24. :param column_generators: A optional dict from column names to hypothesis generators to use for that column
  25. :return: A generator that constructs instances of the mapping class
  26. """
  27. if column_generators is None:
  28. column_generators = {}
  29. derived_generators = derive_generators(mapping_class, omit_columns=column_generators.keys())
  30. return st.builds(
  31. mapping_class,
  32. **merge_dicts(derived_generators, column_generators)
  33. )
  34.  
  35.  
  36. def derive_generators(mapping_class, omit_columns):
  37. columns = _columns_for_mapping_class(mapping_class)
  38. derive_columns = (c for c in columns if c.name not in omit_columns)
  39. return {c.name: column_generator(c) for c in derive_columns}
  40.  
  41.  
  42. def column_generator(column):
  43. gen = None
  44. if isinstance(column.type, Integer):
  45. gen = st.integers()
  46. elif isinstance(column.type, String):
  47. gen = st.text(max_size=column.type.length)
  48. elif isinstance(column.type, DateTime):
  49. allow_naive = not column.type.timezone
  50. gen = datetimes(allow_naive=allow_naive)
  51. elif isinstance(column.type, JSON):
  52. raise ValueError("Unable to derive generator for column {c.name} with type {c.type}: Supply one manually".format(c=column)) # pylint: disable=line-too-long
  53.  
  54. if gen is None:
  55. raise ValueError("Unable to derive generator for column {c.name} with type {c.type}".format(c=column))
  56.  
  57. if column.nullable:
  58. return st.one_of(st.none(), gen)
  59. else:
  60. return gen
  61.  
  62.  
  63. def merge_dicts(*dicts):
  64. merged = {}
  65. for d in dicts:
  66. merged.update(d)
  67. return merged
  68.  
  69.  
  70. def _columns_for_mapping_class(mapping_class):
  71. table = mapping_class.metadata.tables[mapping_class.__table__.name]
  72. return table.columns.values()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement