PageRenderTime 94ms CodeModel.GetById 65ms RepoModel.GetById 0ms app.codeStats 0ms

/CLMSVault/CLMSVault_app/tests/models_factories.py

https://gitlab.com/courcelm/clmsvault
Python | 343 lines | 318 code | 14 blank | 11 comment | 0 complexity | 869ae281a69fcce8449e6ce18d8bcc4a MD5 | raw file
  1. # # Copyright 2013 Mathieu Courcelles
  2. # # Mike Tyers's lab / IRIC / Universite de Montreal
  3. # Import standard librariesdjang
  4. from datetime import datetime
  5. import factory
  6. import random
  7. import string
  8. # Import Django related libraries
  9. from django.contrib.auth.models import User
  10. from django.http import HttpRequest
  11. # Import project libraries
  12. from ..models import Dataset
  13. def random_datetime():
  14. """
  15. Returns datetime object with random year, month, day, hour, minute.
  16. """
  17. year = random.choice(range(1950, 2100))
  18. month = random.choice(range(1, 12))
  19. day = random.choice(range(1, 28))
  20. hour = random.choice(range(0, 23))
  21. minute = random.choice(range(0,59))
  22. return datetime(year, month, day, hour, minute)
  23. def random_string(length=10):
  24. """
  25. Returns a random string made of ascii characters of specified length.
  26. """
  27. return u''.join(random.choice(string.ascii_letters) for _ in range(length))
  28. # Factory boy Django documentation
  29. # https://factoryboy.readthedocs.org/en/latest/orms.html
  30. class ProjectFactory(factory.django.DjangoModelFactory):
  31. """
  32. Factory to create a Project object.
  33. """
  34. FACTORY_FOR = 'CLMSpipeline_app.Project'
  35. FACTORY_DJANGO_GET_OR_CREATE = ('name',)
  36. creation_date = factory.LazyAttribute(lambda t: random_datetime())
  37. name = factory.LazyAttribute(lambda t: random_string())
  38. class FastaDBFactory(factory.django.DjangoModelFactory):
  39. """
  40. Factory to create a FastaDB object.
  41. Note some attributes are not yet implemented.
  42. """
  43. FACTORY_FOR = 'CLMSpipeline_app.FastaDB'
  44. FACTORY_DJANGO_GET_OR_CREATE = ('name',)
  45. creation_date = factory.LazyAttribute(lambda t: random_datetime())
  46. name = factory.LazyAttribute(lambda t: random_string())
  47. file = factory.django.FileField(filename='FastaDB_file.csv')
  48. identifier_regexp = r'^([^\s]+)'
  49. # gene_name_regexp = models.CharField(max_length=50, blank=True)
  50. #
  51. # description_regexp = models.CharField(max_length=50, blank=True)
  52. #
  53. # species_regexp = models.CharField(max_length=50, blank=True)
  54. #
  55. # parsing_status = models.BooleanField(default=False)
  56. #
  57. # parsing_log = models.CharField(max_length=1000, blank=True, null=True)
  58. #
  59. # sequence_count = models.IntegerField(default=0)
  60. update = factory.LazyAttribute(lambda t: [True, False][random.randrange(1)])
  61. class FastaDb_SequenceFactory(factory.django.DjangoModelFactory):
  62. """
  63. Factory to create a FastaDb_Sequence object.
  64. """
  65. FACTORY_FOR = 'CLMSpipeline_app.FastaDb_Sequence'
  66. fastadb = factory.SubFactory(FastaDBFactory)
  67. identifier = factory.LazyAttribute(lambda t: random_string())
  68. gene_name = factory.LazyAttribute(lambda t: random_string())
  69. raw_description = factory.LazyAttribute(lambda t: random_string())
  70. description = factory.LazyAttribute(lambda t: random_string())
  71. species = factory.LazyAttribute(lambda t: random_string())
  72. sequence = factory.LazyAttribute(lambda t: random_string(length=int(random.uniform(100, 2000))).upper())
  73. class DatasetFactory(factory.django.DjangoModelFactory):
  74. """
  75. Factory to create a Dataset object.
  76. Note some attributes are not yet implemented.
  77. """
  78. FACTORY_FOR = 'CLMSpipeline_app.Dataset'
  79. FACTORY_DJANGO_GET_OR_CREATE = ('name',)
  80. creation_date = factory.LazyAttribute(lambda t: random_datetime())
  81. name = factory.LazyAttribute(lambda t: random_string())
  82. project = factory.SubFactory(ProjectFactory)
  83. #cross_linker = models.ForeignKey(CrossLinker, null=True)
  84. #instrument_name = models.ForeignKey(Instrument, null=True)
  85. fasta_db = factory.SubFactory(FastaDBFactory)
  86. #search_algorithm = models.ForeignKey(SearchAlgorithm, null=True)
  87. description = factory.LazyAttribute(lambda t: random_string())
  88. class RawDatasetFactory(factory.django.DjangoModelFactory):
  89. """
  90. Factory to create a RawDataset object.
  91. Note some attributes are not yet implemented.
  92. """
  93. FACTORY_FOR = 'CLMSpipeline_app.RawDataset'
  94. FACTORY_DJANGO_GET_OR_CREATE = ('name',)
  95. creation_date = factory.LazyAttribute(lambda t: random_datetime())
  96. name = factory.LazyAttribute(lambda t: random_string())
  97. project = factory.SubFactory(ProjectFactory)
  98. #cross_linker = models.ForeignKey(CrossLinker, null=True)
  99. #instrument_name = models.ForeignKey(Instrument, null=True)
  100. fasta_db = factory.SubFactory(FastaDBFactory)
  101. #search_algorithm = models.ForeignKey(SearchAlgorithm, null=True)
  102. description = factory.LazyAttribute(lambda t: random_string())
  103. file = factory.django.FileField(filename='Rawdataset_file.csv')
  104. extra_file = factory.django.FileField(filename='RawDataset_extra_file.csv')
  105. parsing_status = factory.LazyAttribute(lambda t: [True, False][random.randrange(1)])
  106. parsing_log = ''
  107. class CLPeptideFactory(factory.django.DjangoModelFactory):
  108. """
  109. Factory to create a CLPeptide object.
  110. """
  111. FACTORY_FOR = 'CLMSpipeline_app.CLPeptide'
  112. #dataset = factory.SubFactory(DatasetFactory) # See at bottom to fix ManyToManyField problem
  113. run_name = factory.LazyAttribute(lambda t: random_string())
  114. scan_number = factory.LazyAttribute(lambda t: random.randrange(10000))
  115. precursor_mz = factory.LazyAttribute(lambda t: random.uniform(300, 2000))
  116. precursor_charge = factory.LazyAttribute(lambda t: random.randrange(7) + 1)
  117. precursor_intensity = factory.LazyAttribute(lambda t: random.uniform(100, 10000000))
  118. rank = factory.LazyAttribute(lambda t: random.randrange(10))
  119. match_score = factory.LazyAttribute(lambda t: random.uniform(0, 100))
  120. spectrum_intensity_coverage = factory.LazyAttribute(lambda t: random.uniform(0, 100))
  121. total_fragment_matches = factory.LazyAttribute(lambda t: random.randrange(100))
  122. delta = factory.LazyAttribute(lambda t: random.gauss(0, 2))
  123. error = factory.LazyAttribute(lambda t: random.uniform(0, 20))
  124. display_protein1 = factory.LazyAttribute(lambda t: t.fs_prot1_id.raw_description)
  125. fs_prot1_id = factory.SubFactory(FastaDb_SequenceFactory)
  126. peptide_position1 = factory.LazyAttribute(lambda t: random.randrange(len(t.fs_prot1_id.sequence)) + 1)
  127. peptide1 = factory.LazyAttribute(lambda t: t.fs_prot1_id.sequence[t.peptide_position1 - 1: t.peptide_position1 + random.randrange(20)])
  128. pep1_link_pos = factory.LazyAttribute(lambda t: random.randrange(len(t.peptide1)) + 1)
  129. peptide_wo_mod1 = factory.LazyAttribute(lambda t: t.peptide1)
  130. display_protein2 = factory.LazyAttribute(lambda t: t.fs_prot2_id.raw_description)
  131. fs_prot2_id = factory.SubFactory(FastaDb_SequenceFactory)
  132. peptide_position2 = factory.LazyAttribute(lambda t: random.randrange(len(t.fs_prot2_id.sequence)) + 1)
  133. peptide2 = factory.LazyAttribute(lambda t: t.fs_prot2_id.sequence[t.peptide_position2 - 1: t.peptide_position2 + random.randrange(20)])
  134. pep2_link_pos = factory.LazyAttribute(lambda t: random.randrange(len(t.peptide2)) + 1)
  135. peptide_wo_mod2 = factory.LazyAttribute(lambda t: t.peptide2)
  136. autovalidated = factory.LazyAttribute(lambda t: [True, False][random.randrange(1)])
  137. validated = factory.LazyAttribute(lambda t: random_string())
  138. rejected = factory.LazyAttribute(lambda t: [True, False][random.randrange(1)])
  139. notes = factory.LazyAttribute(lambda t: random_string())
  140. link_type = factory.LazyAttribute(lambda t: ['Inter-protein',
  141. 'Intra-protein',
  142. 'Intra-peptide',
  143. 'Dead-end'][random.randrange(4)])
  144. cross_link = factory.LazyAttribute(lambda t: [True, False][random.randrange(1)])
  145. not_decoy = factory.LazyAttribute(lambda t: [True, False][random.randrange(1)])
  146. @classmethod
  147. def _prepare(cls, create, **kwargs):
  148. """
  149. Fix 'dataset' ManyToManyField problem
  150. """
  151. d = random.choice(Dataset.objects.all())
  152. clpep = super(CLPeptideFactory, cls)._prepare(create, **kwargs)
  153. clpep.dataset.add(d)
  154. return clpep
  155. class FakeMessages:
  156. """
  157. Mocks the Django message framework, makes it easier to get the messages out.
  158. Code from
  159. http://chase-seibert.github.io/blog/2012/07/27/faster-django-view-unit-tests-with-mocks.html
  160. """
  161. messages = []
  162. def add(self, level, message, extra_tags):
  163. self.messages.append(str(message))
  164. @property
  165. def pop(self):
  166. return self.messages.pop()
  167. def FakeRequestFactory(*args, **kwargs):
  168. """
  169. FakeRequestFactory, FakeMessages and FakeRequestContext are good for
  170. mocking out django views; they are MUCH faster than the Django test client.
  171. Code from
  172. http://chase-seibert.github.io/blog/2012/07/27/faster-django-view-unit-tests-with-mocks.html
  173. """
  174. user = UserFactory()
  175. if kwargs.get('authenticated'):
  176. user.is_authenticated = lambda: True
  177. request = HttpRequest()
  178. request.user = user
  179. request._messages = FakeMessages()
  180. request.session = kwargs.get('session', {})
  181. if kwargs.get('POST'):
  182. request.method = 'POST'
  183. request.POST = kwargs.get('POST')
  184. else:
  185. request.method = 'GET'
  186. request.POST = kwargs.get('GET', {})
  187. return request
  188. class UserFactory(factory.Factory):
  189. """
  190. Factory to create a User object.
  191. Code from
  192. http://chase-seibert.github.io/blog/2012/07/27/faster-django-view-unit-tests-with-mocks.html
  193. """
  194. FACTORY_FOR = User
  195. username = factory.Sequence(lambda i: 'test_%s' % i)
  196. first_name = 'Test'
  197. last_name = 'Test'
  198. email = factory.Sequence(lambda i: 'test%s@test.com' % i)