Debian Codegraph @

src/launchpadlib/testing/launchpad.py

raw
1 # Copyright 2008 Canonical Ltd.
2
3 # This file is part of launchpadlib.
4 #
5 # launchpadlib is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Lesser General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 #
10 # launchpadlib is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with launchpadlib. If not, see
17 # <http://www.gnu.org/licenses/>.
18
19 """Testing API allows fake data to be used in unit tests.
20
21 Testing launchpadlib code is tricky, because it depends so heavily on a
22 remote, unique webservice: Launchpad. This module helps you write tests for
23 your launchpadlib application that can be run locally and quickly.
24
25 Say you were writing some code that needed to call out to Launchpad and get
26 the branches owned by the logged-in person, and then do something to them. For
27 example, something like this::
28
29 def collect_unique_names(lp):
30 names = []
31 for branch in lp.me.getBranches():
32 names.append(branch.unique_name)
33 return names
34
35 To test it, you would first prepare a L{FakeLaunchpad} object, and give it
36 some sample data of your own devising::
37
38 lp = FakeLaunchpad()
39 my_branches = [dict(unique_name='~foo/bar/baz')]
40 lp.me = dict(getBranches: lambda status: my_branches)
41
42 Then, in the test, call your own code and assert that it behaves correctly
43 given the data.
44
45 names = collect_unique_names(lp)
46 self.assertEqual(['~foo/bar/baz'], names)
47
48 And that's it.
49
50 The L{FakeLaunchpad} code uses a WADL file to type-check any objects created
51 or returned. This means you can be sure that you won't accidentally store
52 sample data with misspelled attribute names.
53
54 The WADL file that we use by default is for version 1.0 of the Launchpad API.
55 If you want to work against a more recent version of the API, download the
56 WADL yourself (see <https://help.launchpad.net/API/Hacking>) and construct
57 your C{FakeLaunchpad} like this::
58
59 from wadllib.application import Application
60 lp = FakeLaunchpad(
61 Application('https://api.launchpad.net/devel/',
62 '/path/to/wadl.xml'))
63
64 Where 'https://api.launchpad.net/devel/' is the URL for the WADL file, found
65 also in the WADL file itelf.
66 """
67
68 from collections.abc import Callable
69 from datetime import datetime
70
71
72 class IntegrityError(Exception):
73 """Raised when bad sample data is used with a L{FakeLaunchpad} instance."""
74
75
76 class FakeLaunchpad:
77 """A fake Launchpad API class for unit tests that depend on L{Launchpad}.
78
79 @param application: A C{wadllib.application.Application} instance for a
80 Launchpad WADL definition file.
81 """
82
83 def __init__(
84 self,
85 credentials=None,
86 service_root=None,
87 cache=None,
88 timeout=None,
89 proxy_info=None,
90 application=None,
91 ):
92 if application is None:
93 from launchpadlib.testing.resources import get_application
94
95 application = get_application()
96 root_resource = FakeRoot(application)
97 self.__dict__.update(
98 {
99 "credentials": credentials,
100 "_application": application,
101 "_service_root": root_resource,
102 }
103 )
104
105 def __setattr__(self, name, values):
106 """Set sample data.
107
108 @param name: The name of the attribute.
109 @param values: A dict representing an object matching a resource
110 defined in Launchpad's WADL definition.
111 """
112 service_root = self._service_root
113 setattr(service_root, name, values)
114
115 def __getattr__(self, name):
116 """Get sample data.
117
118 @param name: The name of the attribute.
119 """
120 return getattr(self._service_root, name)
121
122 @classmethod
123 def login(
124 cls,
125 consumer_name,
126 token_string,
127 access_secret,
128 service_root=None,
129 cache=None,
130 timeout=None,
131 proxy_info=None,
132 ):
133 """Convenience for setting up access credentials."""
134 from launchpadlib.testing.resources import get_application
135
136 return cls(object(), application=get_application())
137
138 @classmethod
139 def get_token_and_login(
140 cls,
141 consumer_name,
142 service_root=None,
143 cache=None,
144 timeout=None,
145 proxy_info=None,
146 ):
147 """Get credentials from Launchpad and log into the service root."""
148 from launchpadlib.testing.resources import get_application
149
150 return cls(object(), application=get_application())
151
152 @classmethod
153 def login_with(
154 cls,
155 consumer_name,
156 service_root=None,
157 launchpadlib_dir=None,
158 timeout=None,
159 proxy_info=None,
160 ):
161 """Log in to Launchpad with possibly cached credentials."""
162 from launchpadlib.testing.resources import get_application
163
164 return cls(object(), application=get_application())
165
166
167 def find_by_attribute(element, name, value):
168 """Find children of element where attribute name is equal to value."""
169 return [child for child in element if child.get(name) == value]
170
171
172 def strip_suffix(string, suffix):
173 if string.endswith(suffix):
174 return string[: -len(suffix)]
175 return string
176
177
178 def wadl_tag(tag_name):
179 """Scope a tag name with the WADL namespace."""
180 return "{http://research.sun.com/wadl/2006/10}" + tag_name
181
182
183 class FakeResource:
184 """
185 Represents valid sample data on L{FakeLaunchpad} instances.
186
187 @ivar _children: A dictionary of child resources, each of type
188 C{FakeResource}.
189 @ivar _values: A dictionary of values associated with this resource. e.g.
190 "display_name" or "date_created". The values of this dictionary will
191 never be C{FakeResource}s.
192
193 Note that if C{_children} has a key, then C{_values} will not, and vice
194 versa. That is, they are distinct dicts.
195 """
196
197 special_methods = ["lp_save"]
198
199 def __init__(self, application, resource_type, values=None):
200 """Construct a FakeResource.
201
202 @param application: A C{waddlib.application.Application} instance.
203 @param resource_type: A C{wadllib.application.ResourceType} instance
204 for this resource.
205 @param values: Optionally, a dict representing attribute key/value
206 pairs for this resource.
207 """
208 if values is None:
209 values = {}
210 self.__dict__.update(
211 {
212 "_application": application,
213 "_resource_type": resource_type,
214 "_children": {},
215 "_values": values,
216 }
217 )
218
219 def __setattr__(self, name, value):
220 """Set sample data.
221
222 C{value} can be a dict representing an object matching a resource
223 defined in the WADL definition. Alternatively, C{value} could be a
224 resource itself. Either way, it is checked for type correctness
225 against the WADL definition.
226 """
227 if isinstance(value, dict):
228 self._children[name] = self._create_child_resource(name, value)
229 else:
230 values = {}
231 values.update(self._values)
232 values[name] = value
233 # Confirm that the new 'values' dict is a partial type match for
234 # this resource.
235 self._check_resource_type(self._resource_type, values)
236 self.__dict__["_values"] = values
237
238 def __getattr__(self, name, _marker=object()):
239 """Get sample data.
240
241 @param name: The name of the attribute.
242 """
243 result = self._children.get(name, _marker)
244 if result is _marker:
245 result = self._values.get(name, _marker)
246 if isinstance(result, Callable):
247 return self._wrap_method(name, result)
248 if name in self.special_methods:
249 return lambda: True
250 if result is _marker:
251 raise AttributeError("%r has no attribute '%s'" % (self, name))
252 return result
253
254 def _wrap_method(self, name, method):
255 """Wrapper around methods validates results when it's run.
256
257 @param name: The name of the method.
258 @param method: The callable to run when the method is called.
259 """
260
261 def wrapper(*args, **kwargs):
262 return self._run_method(name, method, *args, **kwargs)
263
264 return wrapper
265
266 def _create_child_resource(self, name, values):
267 """
268 Ensure that C{values} is a valid object for the C{name} attribute and
269 return a resource object to represent it as API data.
270
271 @param name: The name of the attribute to check the C{values} object
272 against.
273 @param values: A dict with key/value pairs representing attributes and
274 methods of an object matching the C{name} resource's definition.
275 @return: A L{FakeEntry} for an ordinary resource or a
276 L{FakeCollection} for a resource that represents a collection.
277 @raises IntegrityError: Raised if C{name} isn't a valid attribute for
278 this resource or if C{values} isn't a valid object for the C{name}
279 attribute.
280 """
281 xml_id = self._find_representation_id(self._resource_type, "get")
282 representation = self._application.representation_definitions[xml_id]
283 params = {
284 child.name: child
285 for child in representation.params(representation)
286 }
287 is_link = False
288 param = params.get(name + "_collection_link")
289 if param is None:
290 is_link = True
291 param = params.get(name + "_link")
292 if param is None:
293 raise IntegrityError("%s isn't a valid property." % (name,))
294 resource_type = self._get_resource_type(param)
295 if is_link:
296 self._check_resource_type(resource_type, values)
297 return FakeEntry(self._application, resource_type, values)
298 else:
299 name, child_resource_type = self._check_collection_type(
300 resource_type, values
301 )
302 return FakeCollection(
303 self._application,
304 resource_type,
305 values,
306 name,
307 child_resource_type,
308 )
309
310 def _get_resource_type(self, param):
311 """Get the resource type for C{param}.
312
313 @param param: An object representing a C{_link} or C{_collection_link}
314 parameter.
315 @return: The resource type for the parameter, or None if one isn't
316 available.
317 """
318 link = param.tag.find(wadl_tag("link"))
319 name = link.get("resource_type")
320 return self._application.get_resource_type(name)
321
322 def _check_resource_type(self, resource_type, partial_object):
323 """
324 Ensure that attributes and methods defined for C{partial_object} match
325 attributes and methods defined for C{resource_type}.
326
327 @param resource_type: The resource type to check the attributes and
328 methods against.
329 @param partial_object: A dict with key/value pairs representing
330 attributes and methods.
331 """
332 for name, value in partial_object.items():
333 if isinstance(value, Callable):
334 # Performs an integrity check.
335 self._get_method(resource_type, name)
336 else:
337 self._check_attribute(resource_type, name, value)
338
339 def _check_collection_type(self, resource_type, partial_object):
340 """
341 Ensure that attributes and methods defined for C{partial_object} match
342 attributes and methods defined for C{resource_type}. Collection
343 entries are treated specially.
344
345 @param resource_type: The resource type to check the attributes and
346 methods against.
347 @param partial_object: A dict with key/value pairs representing
348 attributes and methods.
349 @return: (name, resource_type), where 'name' is the name of the child
350 resource type and 'resource_type' is the corresponding resource
351 type.
352 """
353 name = None
354 child_resource_type = None
355 for name, value in partial_object.items():
356 if name == "entries":
357 name, child_resource_type = self._check_entries(
358 resource_type, value
359 )
360 elif isinstance(value, Callable):
361 # Performs an integrity check.
362 self._get_method(resource_type, name)
363 else:
364 self._check_attribute(resource_type, name, value)
365 return name, child_resource_type
366
367 def _find_representation_id(self, resource_type, name):
368 """Find the WADL XML id for the representation of C{resource_type}.
369
370 Looks in the WADL for the first representiation associated with the
371 method for a resource type.
372
373 :return: An XML id (a string).
374 """
375 get_method = self._get_method(resource_type, name)
376 for response in get_method:
377 for representation in response:
378 representation_url = representation.get("href")
379 if representation_url is not None:
380 return self._application.lookup_xml_id(representation_url)
381
382 def _check_attribute(self, resource_type, name, value):
383 """
384 Ensure that C{value} is a valid C{name} attribute on C{resource_type}.
385
386 Does this by finding the representation for the default, canonical GET
387 method (as opposed to the many "named" GET methods that exist.)
388
389 @param resource_type: The resource type to check the attribute
390 against.
391 @param name: The name of the attribute.
392 @param value: The value to check.
393 """
394 xml_id = self._find_representation_id(resource_type, "get")
395 self._check_attribute_representation(xml_id, name, value)
396
397 def _check_attribute_representation(self, xml_id, name, value):
398 """
399 Ensure that C{value} is a valid value for C{name} with the
400 representation definition matching C{xml_id}.
401
402 @param xml_id: The XML ID for the representation to check the
403 attribute against.
404 @param name: The name of the attribute.
405 @param value: The value to check.
406 @raises IntegrityError: Raised if C{name} is not a valid attribute
407 name or if C{value}'s type is not valid for the attribute.
408 """
409 representation = self._application.representation_definitions[xml_id]
410 params = {
411 child.name: child
412 for child in representation.params(representation)
413 }
414 if name + "_collection_link" in params:
415 resource_type = self._get_resource_type(
416 params[name + "_collection_link"]
417 )
418 child_name, child_resource_type = self._check_collection_type(
419 resource_type, value
420 )
421 elif name + "_link" in params:
422 resource_type = self._get_resource_type(params[name + "_link"])
423 self._check_resource_type(resource_type, value)
424 else:
425 param = params.get(name)
426 if param is None:
427 raise IntegrityError("%s not found" % name)
428 if param.type is None:
429 if not isinstance(value, str):
430 raise IntegrityError(
431 "%s is not a str or unicode for %s" % (value, name)
432 )
433 elif param.type == "xsd:dateTime":
434 if not isinstance(value, datetime):
435 raise IntegrityError(
436 "%s is not a datetime for %s" % (value, name)
437 )
438
439 def _get_method(self, resource_type, name):
440 """Get the C{name} method on C{resource_type}.
441
442 @param resource_type: The method's resource type.
443 @param name: The name of the method.
444 @raises IntegrityError: Raised if a method called C{name} is not
445 available on C{resource_type}.
446 @return: The XML element for the method from the WADL.
447 """
448 if name in self.special_methods:
449 return
450 resource_name = resource_type.tag.get("id")
451 xml_id = "%s-%s" % (resource_name, name)
452 try:
453 [get_method] = find_by_attribute(resource_type.tag, "id", xml_id)
454 except ValueError:
455 raise IntegrityError(
456 "%s is not a method of %s" % (name, resource_name)
457 )
458 return get_method
459
460 def _run_method(self, name, method, *args, **kwargs):
461 """Run a method and convert its result into a L{FakeResource}.
462
463 If the result represents an object it is validated against the WADL
464 definition before being returned.
465
466 @param name: The name of the method.
467 @param method: A callable.
468 @param args: Arguments to pass to the callable.
469 @param kwargs: Keyword arguments to pass to the callable.
470 @return: A L{FakeResource} representing the result if it's an object.
471 @raises IntegrityError: Raised if the return value from the method
472 isn't valid.
473 """
474 result = method(*args, **kwargs)
475 if name in self.special_methods or result is None:
476 return result
477 else:
478 return self._create_resource(self._resource_type, name, result)
479
480 def _create_resource(self, resource_type, name, result):
481 """Create new L{FakeResource} for C{resource_type} method call result.
482
483 @param resource_type: The resource type of the method.
484 @param name: The name of the method on C{resource_type}.
485 @param result: The result of calling the method.
486 @raises IntegrityError: Raised if C{result} is an invalid return value
487 for the method.
488 @return: A L{FakeResource} for C{result}, or just C{result} if no
489 response representation is defined for the method.
490 """
491 resource_name = resource_type.tag.get("id")
492 if resource_name == name:
493 name = "get"
494 xml_id = self._find_representation_id(resource_type, name)
495 if xml_id is None:
496 return result
497 xml_id = strip_suffix(xml_id, "-full")
498 if xml_id not in self._application.resource_types:
499 xml_id += "-resource"
500 result_resource_type = self._application.resource_types[xml_id]
501 if xml_id.endswith("-page-resource"):
502 name, child_resource_type = self._check_collection_type(
503 result_resource_type, result
504 )
505 return FakeCollection(
506 self._application,
507 result_resource_type,
508 result,
509 name,
510 child_resource_type,
511 )
512 else:
513 self._check_resource_type(result_resource_type, result)
514 resource = FakeEntry(self._application, result_resource_type)
515 for child_name, child_value in result.items():
516 setattr(resource, child_name, child_value)
517 return resource
518
519 def _get_child_resource_type(self, resource_type):
520 """Get the name and resource type for the entries in a collection.
521
522 @param resource_type: The resource type for a collection.
523 @return: (name, resource_type), where 'name' is the name of the child
524 resource type and 'resource_type' is the corresponding resource
525 type.
526 """
527 xml_id = self._find_representation_id(resource_type, "get")
528 representation_definition = (
529 self._application.representation_definitions[xml_id]
530 )
531
532 [entry_links] = find_by_attribute(
533 representation_definition.tag, "name", "entry_links"
534 )
535 [resource_type] = list(entry_links)
536 resource_type_url = resource_type.get("resource_type")
537 resource_type_name = resource_type_url.split("#")[1]
538 return (
539 resource_type_name,
540 self._application.get_resource_type(resource_type_url),
541 )
542
543 def _check_entries(self, resource_type, entries):
544 """Ensure that C{entries} are valid for a C{resource_type} collection.
545
546 @param resource_type: The resource type of the collection the entries
547 are in.
548 @param entries: A list of dicts representing objects in the
549 collection.
550 @return: (name, resource_type), where 'name' is the name of the child
551 resource type and 'resource_type' is the corresponding resource
552 type.
553 """
554 name, child_resource_type = self._get_child_resource_type(
555 resource_type
556 )
557 for entry in entries:
558 self._check_resource_type(child_resource_type, entry)
559 return name, child_resource_type
560
561 def __repr__(self):
562 """
563 The resource type, identifier if available, and memory address are
564 used to generate a representation of this fake resource.
565 """
566 name = self._resource_type.tag.get("id")
567 key = "object"
568 key = self._values.get("id", key)
569 key = self._values.get("name", key)
570 return "<%s %s %s at %s>" % (
571 self.__class__.__name__,
572 name,
573 key,
574 hex(id(self)),
575 )
576
577
578 class FakeRoot(FakeResource):
579 """Fake root object for an application."""
580
581 def __init__(self, application):
582 """Create a L{FakeResource} for the service root of C{application}.
583
584 @param application: A C{wadllib.application.Application} instance.
585 """
586 resource_type = application.get_resource_type(
587 application.markup_url + "#service-root"
588 )
589 super().__init__(application, resource_type)
590
591
592 class FakeEntry(FakeResource):
593 """A fake resource for an entry."""
594
595
596 class FakeCollection(FakeResource):
597 """A fake resource for a collection."""
598
599 def __init__(
600 self,
601 application,
602 resource_type,
603 values=None,
604 name=None,
605 child_resource_type=None,
606 ):
607 super().__init__(application, resource_type, values)
608 self.__dict__.update(
609 {"_name": name, "_child_resource_type": child_resource_type}
610 )
611
612 def __iter__(self):
613 """Iterate items if this resource has an C{entries} attribute."""
614 entries = self._values.get("entries", ())
615 for entry in entries:
616 yield self._create_resource(
617 self._child_resource_type, self._name, entry
618 )
619
620 def __getitem__(self, key):
621 """Look up a slice, or a subordinate resource by index.
622
623 @param key: An individual object key or a C{slice}.
624 @raises IndexError: Raised if an invalid key is provided.
625 @return: A L{FakeResource} instance for the entry matching C{key}.
626 """
627 entries = list(self)
628 if isinstance(key, slice):
629 start = key.start or 0
630 stop = key.stop
631 if start < 0:
632 raise ValueError(
633 "Collection slices must have a nonnegative " "start point."
634 )
635 if stop < 0:
636 raise ValueError(
637 "Collection slices must have a definite, "
638 "nonnegative end point."
639 )
640 return entries.__getitem__(key)
641 elif isinstance(key, int):
642 return entries.__getitem__(key)
643 else:
644 raise IndexError("Do not support index lookups yet.")