File: test_core.py

package info (click to toggle)
python-activipy 0.1-11
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 464 kB
  • sloc: python: 1,262; makefile: 171; lisp: 18; sh: 13
file content (482 lines) | stat: -rw-r--r-- 16,347 bytes parent folder | download | duplicates (6)
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# coding=utf-8
## Activipy --- ActivityStreams 2.0 implementation and validator for Python
## Copyright © 2015 Christopher Allan Webber <cwebber@dustycloud.org>
##
## This file is part of Activipy, which is GPLv3+ or Apache v2, your option
## (see COPYING); since that means effectively Apache v2 here's those headers
##
## Apache v2 header:
##   Licensed under the Apache License, Version 2.0 (the "License");
##   you may not use this file except in compliance with the License.
##   You may obtain a copy of the License at
##
##       http://www.apache.org/licenses/LICENSE-2.0
##
##   Unless required by applicable law or agreed to in writing, software
##   distributed under the License is distributed on an "AS IS" BASIS,
##   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
##   See the License for the specific language governing permissions and
##   limitations under the License.

import copy

import pytest

from activipy import core, vocab




# Fake inheritance tree below

def fake_type_uri(type_name):
    return "http://example.org/ns#" + type_name
    
ASObject = core.ASType(fake_type_uri("object"), [], "Object")
ASLink = core.ASType(fake_type_uri("link"), [], "Link")

ASActivity = core.ASType(fake_type_uri("activity"), [ASObject], "Activity")
ASPost = core.ASType(fake_type_uri("post"), [ASActivity], "Post")
ASDelete = core.ASType(fake_type_uri("delete"), [ASActivity], "Delete")

ASCollection = core.ASType(
    fake_type_uri("collection"), [ASObject], "Collection")
ASOrderedCollection = core.ASType(
    fake_type_uri("orderedcollection"),
    [ASCollection],
    "OrderedCollection")
ASCollectionPage = core.ASType(
    fake_type_uri("collectionpage"),
    [ASCollection],
    "CollectionPage")
ASOrderedCollectionPage = core.ASType(
    fake_type_uri("orderedcollectionpage"),
    [ASOrderedCollection, ASCollectionPage],
    "OrderedCollectionPage")

# BS testing widget
ASWidget = core.ASType(
    fake_type_uri("widget"),
    [ASObject],
    "Widget")

ASFancyWidget = core.ASType(
    fake_type_uri("fancywidget"),
    [ASWidget],
    "FancyWidget")


# Example vocab and environment
ExampleVocab = core.ASVocab(
    [ASObject, ASLink,
     ASActivity, ASPost, ASDelete,
     ASCollection, ASOrderedCollection, ASCollectionPage,
     ASOrderedCollectionPage,
     ASWidget, ASFancyWidget])

ExampleEnv = core.Environment(
    vocabs=[ExampleVocab],
    shortids=core.shortids_from_vocab(ExampleVocab),
    c_accessors=core.shortids_from_vocab(ExampleVocab))




# Basic tests

def test_inheritance_list():
    # Should just be itself
    assert core.astype_inheritance_list(ASObject) == \
        [ASObject]
    assert core.astype_inheritance_list(ASLink) == \
        [ASLink]

    # Should be itself, then its parent
    assert core.astype_inheritance_list(ASActivity) == \
        [ASActivity, ASObject]
    assert core.astype_inheritance_list(ASCollection) == \
        [ASCollection, ASObject]

    # A slightly longer inheritance chain
    assert core.astype_inheritance_list(ASPost) == \
        [ASPost, ASActivity, ASObject]
    assert core.astype_inheritance_list(ASDelete) == \
        [ASDelete, ASActivity, ASObject]
    assert core.astype_inheritance_list(ASOrderedCollection) == \
        [ASOrderedCollection, ASCollection, ASObject]
    assert core.astype_inheritance_list(ASCollectionPage) == \
        [ASCollectionPage, ASCollection, ASObject]

    # Multiple inheritance!  Egads.
    # ... this clearly demonstrates our present depth-first
    # traversal.  A breadth-first traversal would mean
    # ASCollectionPage would go before ASCollection, which may be more
    # to a user's expectations.
    assert core.astype_inheritance_list(ASOrderedCollectionPage) == \
        [ASOrderedCollectionPage, ASOrderedCollection,
         ASCollectionPage, ASCollection, ASObject,]

    # does the property version also work?
    assert ASOrderedCollectionPage.inheritance_chain == \
        [ASOrderedCollectionPage, ASOrderedCollection,
         ASCollectionPage, ASCollection, ASObject]

    # What about composite core
    assert core.astype_inheritance_list(
        ASFancyWidget, ASOrderedCollectionPage) == [
            ASFancyWidget, ASWidget,
            ASOrderedCollectionPage, ASOrderedCollection,
            ASCollectionPage, ASCollection, ASObject]
    


ROOT_BEER_NOTE_JSOBJ = {
    "@type": "Create",
    "@id": "http://tsyesika.co.uk/act/foo-id-here/",
    "actor": {
        "@type": "Person",
        "@id": "http://tsyesika.co.uk/",
        "displayName": "Jessica Tallon"},
    "to": ["acct:cwebber@identi.ca",
           "acct:justaguy@rhiaro.co.uk",
           "acct:ladyaeva@hedgehog.example"],
    "object": {
        "@type": "Note",
        "@id": "http://tsyesika.co.uk/chat/sup-yo/",
        "content": "Up for some root beer floats?"}}

ROOT_BEER_NOTE_MIXED_ASOBJ = {
    "@type": "Create",
    "@id": "http://tsyesika.co.uk/act/foo-id-here/",
    "actor": core.ASObj({
        "@type": "Person",
        "@id": "http://tsyesika.co.uk/",
        "displayName": "Jessica Tallon"}),
    "to": ["acct:cwebber@identi.ca",
           "acct:justaguy@rhiaro.co.uk",
           "acct:ladyaeva@hedgehog.example"],
    "object": core.ASObj({
        "@type": "Note",
        "@id": "http://tsyesika.co.uk/chat/sup-yo/",
        "content": "Up for some root beer floats?"})}

ROOT_BEER_NOTE_VOCAB = vocab.Create(
    "http://tsyesika.co.uk/act/foo-id-here/",
    actor=vocab.Person(
        "http://tsyesika.co.uk/",
        displayName="Jessica Tallon"),
    to=["acct:cwebber@identi.ca",
        "acct:justaguy@rhiaro.co.uk",
        "acct:ladyaeva@hedgehog.example"],
    object=vocab.Note(
        "http://tsyesika.co.uk/chat/sup-yo/",
        content="Up for some root beer floats?"))


def _looks_like_root_beer_note(jsobj):
    return (
        len(jsobj) == 5 and
        jsobj["@type"] == "Create" and
        jsobj["@id"] == "http://tsyesika.co.uk/act/foo-id-here/" and
        isinstance(jsobj["actor"], dict) and
        len(jsobj["actor"]) == 3 and
        jsobj["actor"]["@type"] == "Person" and
        jsobj["actor"]["@id"] == "http://tsyesika.co.uk/" and
        jsobj["actor"]["displayName"] == "Jessica Tallon" and
        isinstance(jsobj["to"], list) and
        jsobj["to"] == ["acct:cwebber@identi.ca",
                        "acct:justaguy@rhiaro.co.uk",
                        "acct:ladyaeva@hedgehog.example"] and
        isinstance(jsobj["object"], dict) and
        len(jsobj["object"]) == 3 and
        jsobj["object"]["@type"] == "Note" and
        jsobj["object"]["@id"] == "http://tsyesika.co.uk/chat/sup-yo/" and
        jsobj["object"]["content"] == "Up for some root beer floats?")


def test_deepcopy_jsobj_in():
    # We'll mutate later, so let's make a copy of this
    root_beer_note = copy.deepcopy(ROOT_BEER_NOTE_JSOBJ)
    assert _looks_like_root_beer_note(root_beer_note)

    # Test copying a compicated datastructure
    copied_root_beer_note = core.deepcopy_jsobj_in(
        root_beer_note, vocab.BasicEnv)
    assert _looks_like_root_beer_note(copied_root_beer_note)

    # Mutate
    root_beer_note["to"].append("sneaky@mcsneakers.example")
    assert not _looks_like_root_beer_note(root_beer_note)
    # but things are still as they were in our copy right??
    assert _looks_like_root_beer_note(copied_root_beer_note)

    # Test nested asobj copying
    assert _looks_like_root_beer_note(
        core.deepcopy_jsobj_in(
            ROOT_BEER_NOTE_MIXED_ASOBJ,
            vocab.BasicEnv))

# TODO: test_deepcopy_jsobj_out():


def test_vocab_constructor():
    assert isinstance(
        ROOT_BEER_NOTE_VOCAB,
        core.ASObj)

    assert _looks_like_root_beer_note(
        ROOT_BEER_NOTE_VOCAB.json())


ROOT_BEER_NOTE_ASOBJ = core.ASObj({
    "@type": "Create",
    "@id": "http://tsyesika.co.uk/act/foo-id-here/",
    "actor": core.ASObj({
        "@type": "Person",
        "@id": "http://tsyesika.co.uk/",
        "displayName": "Jessica Tallon"}),
    "to": ["acct:cwebber@identi.ca",
           "acct:justaguy@rhiaro.co.uk"],
    "object": core.ASObj({
        "@type": "Note",
        "@id": "http://tsyesika.co.uk/chat/sup-yo/",
        "content": "Up for some root beer floats?"})})


def test_asobj_keyaccess():
    assert ROOT_BEER_NOTE_ASOBJ["@type"] == "Create"
    assert ROOT_BEER_NOTE_ASOBJ["@id"] == \
        "http://tsyesika.co.uk/act/foo-id-here/"

    # Accessing things that look like asobjects
    # will return asobjects
    assert isinstance(
        ROOT_BEER_NOTE_ASOBJ["object"],
        core.ASObj)

    # However, we should still be able to get the
    # dictionary edition by pulling down .json()
    assert isinstance(
        ROOT_BEER_NOTE_ASOBJ.json()["object"],
        dict)

    # Traversal of traversal should work
    assert ROOT_BEER_NOTE_ASOBJ["object"]["content"] == \
        "Up for some root beer floats?"


def test_handle_one():
    # Fake value boxes
    received_args = []
    received_kwargs = []

    def test_method1(*args, **kwargs):
        received_args.append(args)
        received_kwargs.append(kwargs)
        return "Got it!"

    def test_method2(*args, **kwargs):
        # we should never hit this
        assert False
        return "skip me!"

    # well if we got this far we never hit test_method2, which is good
    # did we run test_method1 then?
    our_jsobj = ASWidget(foo="bar")
    handler = core.handle_one(
        [(test_method1, ASWidget), (test_method2, ASObject)],
        our_jsobj)
    assert handler(1, 2, foo="bar") == "Got it!"
    assert received_args[0] == (our_jsobj, 1, 2)
    assert received_kwargs[0] == {"foo": "bar"}

    # Okay, let's try running with no methods available
    with pytest.raises(core.NoMethodFound):
        core.handle_one([], our_jsobj)

    # Let's try running something with a custom fallback...
    # ... this fallback drinks the half empty glass
    glass = ["half_empty"]
    def drink_glass(asobj):
        # down the hatch
        glass.pop()
    core.handle_one([], our_jsobj, _fallback=drink_glass)
    assert len(glass) == 0  # if this passes, the pessimists win


def test_handle_map():
    def test_one(*args, **kwargs):
        return (1, args, kwargs)

    def test_two(*args, **kwargs):
        return (2, args, kwargs)

    def test_three(*args, **kwargs):
        return (3, args, kwargs)

    our_asobj = ASWidget(snorf="snizzle")
    handler = core.handle_map([(test_one, ASFancyWidget),
                                (test_two, ASWidget), (test_three, ASObject)],
                               our_asobj)
    result = handler("one", "two", "three", lets="go!")
    assert result[0][0] == 1
    assert result[1][0] == 2
    assert result[2][0] == 3
    for r in result:
        assert r[1] == (our_asobj, "one", "two", "three")
        assert r[2] == {"lets": "go!"}


def test_handle_fold():
    def test_one(asobj, val, location):
        return val + "one %s... " % location

    def test_two(asobj, val, location):
        return val + "two %s... " % location

    def test_three(asobj, val, location):
        return val + "three %s... " % location

    our_asobj = ASWidget(snorf="snizzle")
    handler = core.handle_fold([(test_one, ASFancyWidget),
                                 (test_two, ASWidget), (test_three, ASObject)],
                                our_asobj)
    result = handler("Counting down! ", "mississippi")
    assert result == (
        "Counting down! one mississippi... "
        "two mississippi... three mississippi... ")

    # Now test breaking out early
    def test_two_breaks_out(asobj, val, location):
        return core.HaltIteration(val + "two %s... " % location)

    handler = core.handle_fold([(test_one, ASFancyWidget),
                                 (test_two_breaks_out, ASWidget),
                                 (test_three, ASObject)],
                                our_asobj)
    result = handler("Counting down! ", "mississippi")
    # we never get to three in this version
    assert result == (
        "Counting down! one mississippi... "
        "two mississippi... ")




# Methods testing
# ===============

### begin testing methods ###

save = core.MethodId("save", "Save things", core.handle_one)
get_things = core.MethodId("get_things", "Build up a map of stuff",
                           core.handle_map)
# This one's name intentionally different than its variable name
# for testing reasons
combine_things = core.MethodId("combine", "combine things", core.handle_fold)

def _object_save(asobj, db):
    db[asobj["@id"]] = ("saved as object", asobj)

def _widget_save(asobj, db):
    db[asobj["@id"]] = ("saved as widget", asobj)

def _object_get_things(asobj):
    return "objects are fun"

def _activity_get_things(asobj):
    return "activities are neat"

def _post_get_things(asobj):
    return "posts are cool"

def _collection_combine_things(asobj, val, chant):
    return val + chant + ", my friend, and remember us collected\n"
    
def _ordered_collection_combine_things(asobj, val, chant):
    return val + chant + ", my dear, and cherish the order\n"

def _ordered_collection_page_combine_things(asobj, val, chant):
    return val + chant + ", my sweet, a new page is turning\n"

### end testing methods ###

MethodEnv = core.Environment(
    vocabs=[ExampleVocab],
    methods={
        (save, ASObject): _object_save,
        (save, ASWidget): _widget_save,
        (get_things, ASObject): _object_get_things,
        (get_things, ASActivity): _activity_get_things,
        (get_things, ASPost): _post_get_things,
        (combine_things, ASCollection): _collection_combine_things,
        (combine_things, ASOrderedCollection): (
            _ordered_collection_combine_things),
        (combine_things, ASOrderedCollectionPage): (
            _ordered_collection_page_combine_things)},
    shortids=core.shortids_from_vocab(ExampleVocab),
    c_accessors=core.shortids_from_vocab(ExampleVocab))


def test_environment_c_access():
    widget = MethodEnv.c.Widget(foo="bar")
    assert widget["foo"] == "bar"
    assert widget.types_astype == [ASWidget]
    assert widget.env == MethodEnv
    assert MethodEnv.c.Widget.astype == ASWidget


def test_environment_m_access_handle_one():
    db = {}
    widget = MethodEnv.c.Widget("fooid:12345")
    MethodEnv.m.save(widget, db)
    assert db["fooid:12345"] == ("saved as widget", widget)

    foo_object = MethodEnv.c.Object("fooid:00001")
    MethodEnv.m.save(foo_object, db)
    assert db["fooid:00001"] == ("saved as object", foo_object)

    collection = MethodEnv.c.Collection("fooid:8888")
    MethodEnv.m.save(collection, db)
    assert db["fooid:8888"] == ("saved as object", collection)


def test_environment_m_access_handle_map():
    result = MethodEnv.m.get_things(MethodEnv.c.Widget("fooid:12345"))
    assert result == ["objects are fun"]

    result = MethodEnv.m.get_things(MethodEnv.c.Activity("fooid:0202"))
    assert result == ["activities are neat", "objects are fun"]

    result = MethodEnv.m.get_things(MethodEnv.c.Delete("fooid:0303"))
    assert result == ["activities are neat", "objects are fun"]

    result = MethodEnv.m.get_things(MethodEnv.c.Post("fooid:0808"))
    assert result == ["posts are cool", "activities are neat",
                      "objects are fun"]


def test_environment_m_access_handle_fold():
    # This test function is kinda disturbing
    result = MethodEnv.m.combine(MethodEnv.c.Collection("fooid:1"), "",
                                 "Huzzah")
    assert result == "Huzzah, my friend, and remember us collected\n"
    
    result = MethodEnv.m.combine(MethodEnv.c.OrderedCollection("fooid:2"), "",
                                 "Huzzah")
    assert result == (
        "Huzzah, my dear, and cherish the order\n"
        "Huzzah, my friend, and remember us collected\n")

    result = MethodEnv.m.combine(MethodEnv.c.OrderedCollectionPage("fooid:2"),
                                 "", "Rejoice")
    assert result == (
        "Rejoice, my sweet, a new page is turning\n"
        "Rejoice, my dear, and cherish the order\n"
        "Rejoice, my friend, and remember us collected\n")

    # nothing for this one
    result = MethodEnv.m.combine(MethodEnv.c.Widget("fooid:12345"), "",
                                 "Huzzah")
    assert result == ""