/
factories.py
329 lines (235 loc) · 10.5 KB
/
factories.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
'''This is a collection of factory classes for building CKAN users, datasets,
etc.
These are meant to be used by tests to create any objects that are needed for
the tests. They're written using ``factory_boy``:
http://factoryboy.readthedocs.org/en/latest/
These are not meant to be used for the actual testing, e.g. if you're writing a
test for the :py:func:`~ckan.logic.action.create.user_create` function then
call :py:func:`~ckan.new_tests.helpers.call_action`, don't test it
via the :py:class:`~ckan.new_tests.factories.User` factory below.
Usage::
# Create a user with the factory's default attributes, and get back a
# user dict:
user_dict = factories.User()
# You can create a second user the same way. For attributes that can't be
# the same (e.g. you can't have two users with the same name) a new value
# will be generated each time you use the factory:
another_user_dict = factories.User()
# Create a user and specify your own user name and email (this works
# with any params that CKAN's user_create() accepts):
custom_user_dict = factories.User(name='bob', email='bob@bob.com')
# Get a user dict containing the attributes (name, email, password, etc.)
# that the factory would use to create a user, but without actually
# creating the user in CKAN:
user_attributes_dict = factories.User.attributes()
# If you later want to create a user using these attributes, just pass them
# to the factory:
user = factories.User(**user_attributes_dict)
'''
import factory
import mock
import ckan.model
import ckan.logic
import ckan.new_tests.helpers as helpers
def _get_action_user_name(kwargs):
'''Return the name of the user that should perform the create action
When creating an instance of the factory, users can provide an 'auth_user'
keyword argument with the name of the user that should perform the action.
If they don't provide the 'auth_user' argument the site user will be used
(this user is a sysadmin). If the action should be performed anonymously
(ie no logged in user), auth_user=None should be provided.
The user name can be passed on the context['user'] property to the action
function.
Examples:
* Creating a new group with the site user:
group = factories.Group()
* Creating an Organization with the user 'daniel'
org = factories.Organization(auth_user='daniel')
* Creating a Dataset anonymously
org = factories.Organization(auth_user=None)
'''
if 'auth_user' in kwargs:
user_name = kwargs.get('auth_user')
else:
user_name = helpers.call_action('get_site_user')['name']
return user_name
def _generate_email(user):
'''Return an email address for the given User factory stub object.'''
return '{0}@ckan.org'.format(user.name).lower()
def _generate_reset_key(user):
'''Return a reset key for the given User factory stub object.'''
return '{0}_reset_key'.format(user.name).lower()
def _generate_user_id(user):
'''Return a user id for the given User factory stub object.'''
return '{0}_user_id'.format(user.name).lower()
class User(factory.Factory):
'''A factory class for creating CKAN users.'''
# This is the class that UserFactory will create and return instances
# of.
FACTORY_FOR = ckan.model.User
# These are the default params that will be used to create new users.
fullname = 'Mr. Test User'
password = 'pass'
about = 'Just another test user.'
# Generate a different user name param for each user that gets created.
name = factory.Sequence(lambda n: 'test_user_{n}'.format(n=n))
# Compute the email param for each user based on the values of the other
# params above.
email = factory.LazyAttribute(_generate_email)
# I'm not sure how to support factory_boy's .build() feature in CKAN,
# so I've disabled it here.
@classmethod
def _build(cls, target_class, *args, **kwargs):
raise NotImplementedError(".build() isn't supported in CKAN")
# To make factory_boy work with CKAN we override _create() and make it call
# a CKAN action function.
# We might also be able to do this by using factory_boy's direct SQLAlchemy
# support: http://factoryboy.readthedocs.org/en/latest/orms.html#sqlalchemy
@classmethod
def _create(cls, target_class, *args, **kwargs):
if args:
assert False, "Positional args aren't supported, use keyword args."
user_dict = helpers.call_action('user_create', **kwargs)
return user_dict
class Resource(factory.Factory):
'''A factory class for creating CKAN resources.'''
FACTORY_FOR = ckan.model.Resource
name = 'test_resource'
description = 'test resource desc'
format = 'res_format'
url = 'http://link.to.some.data'
@classmethod
def _build(cls, target_class, *args, **kwargs):
raise NotImplementedError(".build() isn't supported in CKAN")
@classmethod
def _create(cls, target_class, *args, **kwargs):
if args:
assert False, "Positional args aren't supported, use keyword args."
context = {'user': _get_action_user_name(kwargs)}
assert kwargs.get('package_id'), 'You must provide a package_id'
resource_dict = helpers.call_action('resource_create', context=context,
**kwargs)
return resource_dict
def _generate_dataset_title(dataset):
'''Return a title for the given Dataset factory stub object.'''
return dataset.name.replace('_', ' ').title()
class Dataset(factory.Factory):
'''A factory class for creating CKAN datasets.'''
FACTORY_FOR = ckan.model.Package
name = factory.Sequence(lambda n: 'test_dataset_{n}'.format(n=n))
title = factory.LazyAttribute(_generate_dataset_title)
author = 'test dataset author'
author_email = 'test_dataset_author@test_dataset.io'
maintainer = 'test dataset maintainer'
maintainer_email = 'test_dataset_maintainer@test_dataset.io'
license_id = 'cc-by'
notes = 'Some test notes about this test dataset'
url = 'test_dataset.io'
version = '0.1 beta'
resources = [
{
'name': 'test_resource',
'description': 'test resource desc',
'format': 'res_format',
'url': 'http://link.to.some.data',
}
]
extras = [
{'key': 'extra1', 'value': 'test'}
]
tags = [
{'name': 'test_tag_1'},
]
@classmethod
def _build(cls, target_class, *args, **kwargs):
raise NotImplementedError(".build() isn't supported in CKAN")
@classmethod
def _create(cls, target_class, *args, **kwargs):
if args:
assert False, "Positional args aren't supported, use keyword args."
context = {'user': _get_action_user_name(kwargs)}
dataset_dict = helpers.call_action('dataset_create', context=context,
**kwargs)
return dataset_dict
class Group(factory.Factory):
'''A factory class for creating CKAN groups.'''
# This is the class that GroupFactory will create and return instances
# of.
FACTORY_FOR = ckan.model.Group
# These are the default params that will be used to create new groups.
type = 'group'
is_organization = False
title = 'Test Group'
description = 'Just another test group.'
image_url = 'http://placekitten.com/g/200/200'
# Generate a different group name param for each user that gets created.
name = factory.Sequence(lambda n: 'test_group_{n}'.format(n=n))
@classmethod
def _build(cls, target_class, *args, **kwargs):
raise NotImplementedError(".build() isn't supported in CKAN")
@classmethod
def _create(cls, target_class, *args, **kwargs):
if args:
assert False, "Positional args aren't supported, use keyword args."
context = {'user': _get_action_user_name(kwargs)}
group_dict = helpers.call_action('group_create',
context=context,
**kwargs)
return group_dict
class Organization(factory.Factory):
'''A factory class for creating CKAN organizations.'''
# This is the class that OrganizationFactory will create and return
# instances of.
FACTORY_FOR = ckan.model.Group
# These are the default params that will be used to create new
# organizations.
type = 'organization'
is_organization = True
title = 'Test Organization'
description = 'Just another test organization.'
image_url = 'http://placekitten.com/g/200/100'
# Generate a different group name param for each user that gets created.
name = factory.Sequence(lambda n: 'test_org_{n}'.format(n=n))
@classmethod
def _build(cls, target_class, *args, **kwargs):
raise NotImplementedError(".build() isn't supported in CKAN")
@classmethod
def _create(cls, target_class, *args, **kwargs):
if args:
assert False, "Positional args aren't supported, use keyword args."
context = {'user': _get_action_user_name(kwargs)}
group_dict = helpers.call_action('organization_create',
context=context,
**kwargs)
return group_dict
class MockUser(factory.Factory):
'''A factory class for creating mock CKAN users using the mock library.'''
FACTORY_FOR = mock.MagicMock
fullname = 'Mr. Mock User'
password = 'pass'
about = 'Just another mock user.'
name = factory.Sequence(lambda n: 'mock_user_{n}'.format(n=n))
email = factory.LazyAttribute(_generate_email)
reset_key = factory.LazyAttribute(_generate_reset_key)
id = factory.LazyAttribute(_generate_user_id)
@classmethod
def _build(cls, target_class, *args, **kwargs):
raise NotImplementedError(".build() isn't supported in CKAN")
@classmethod
def _create(cls, target_class, *args, **kwargs):
if args:
assert False, "Positional args aren't supported, use keyword args."
mock_user = mock.MagicMock()
for name, value in kwargs.items():
setattr(mock_user, name, value)
return mock_user
def validator_data_dict():
'''Return a data dict with some arbitrary data in it, suitable to be passed
to validator functions for testing.
'''
return {('other key',): 'other value'}
def validator_errors_dict():
'''Return an errors dict with some arbitrary errors in it, suitable to be
passed to validator functions for testing.
'''
return {('other key',): ['other error']}