aboutsummaryrefslogtreecommitdiffstats
path: root/tests/test_backend.py
blob: 3ca33add70f56f22c19c75819cf55e681ede4d74 (plain)
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

import os
import json
import pytest
import fatcat
import fatcat.sql
from fatcat.models import *
import unittest
import tempfile

# TODO: http://alextechrants.blogspot.com/2013/08/unit-testing-sqlalchemy-apps.html

## Helpers ##################################################################

def check_entity_fields(e):
    for key in ('rev', 'is_live', 'redirect_id'):
        assert key in e
    for key in ('id',):
        assert e[key] is not None

def check_release(e):
    for key in ('work', 'release_type'):
        assert key in e
    for key in ('title'):
        assert e[key] is not None
    for key in ('refs', 'creators'):
        assert type(e[key]) == list

def check_creator(e):
    for key in ('name',):
        assert e[key] is not None

def check_container(e):
    for key in ('name',):
        assert e[key] is not None

def check_file(e):
    for key in ('size', 'sha1'):
        assert e[key] is not None

class FatcatTestCase(unittest.TestCase):

    def setUp(self):
        fatcat.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        fatcat.app.testing = True
        fatcat.app.debug = True
        self.app = fatcat.app.test_client()
        fatcat.db.session.remove()
        fatcat.db.drop_all()
        fatcat.db.create_all()
        fatcat.sql.populate_db()


## Model Tests ###############################################################

class ModelTestCase(FatcatTestCase):

    def test_example_works(self):
        fatcat.dummy.insert_example_works()

    def test_random_works(self):
        fatcat.dummy.insert_random_works()

    def test_load_crossref(self):
        with open('./tests/files/crossref-works.2018-01-21.badsample.json', 'r') as f:
            raw = [json.loads(l) for l in f.readlines() if len(l) > 3]
        for obj in raw:
            fatcat.sql.add_crossref_via_model(obj)

    def test_schema_release_rev(self):
        assert ReleaseRev.query.count() == 0
        e = {
            "title": "Bogus title",
            "release_type": "book",
            "creators": [],
            "refs": [],
        }
        model = release_rev_schema.load(e)
        fatcat.db.session.add(model.data)
        fatcat.db.session.commit()
        assert ReleaseRev.query.count() == 1
        model_after = ReleaseRev.query.first()
        serial = release_rev_schema.dump(model_after).data
        #check_release(serial)
        for k in e.keys():
            assert e[k] == serial[k]

    def test_schema_creator_rev(self):
        assert ReleaseRev.query.count() == 0
        e = {
            "name": "Robin (Batman)",
        }
        model = creator_rev_schema.load(e)
        fatcat.db.session.add(model.data)
        fatcat.db.session.commit()
        assert CreatorRev.query.count() == 1
        model_after = CreatorRev.query.first()
        serial = creator_rev_schema.dump(model_after).data
        check_creator(serial)
        for k in e.keys():
            assert e[k] == serial[k]

    def test_schema_container_rev(self):
        assert ReleaseRev.query.count() == 0
        e = {
            "name": "Papers Monthly",
        }
        model = container_rev_schema.load(e)
        fatcat.db.session.add(model.data)
        fatcat.db.session.commit()
        assert ContainerRev.query.count() == 1
        model_after = ContainerRev.query.first()
        serial = container_rev_schema.dump(model_after).data
        check_container(serial)
        for k in e.keys():
            assert e[k] == serial[k]

    def test_schema_file_rev(self):
        assert ReleaseRev.query.count() == 0
        e = {
            "sha1": "asdf",
            "size": 6,
        }
        model = file_rev_schema.load(e)
        print(model)
        fatcat.db.session.add(model.data)
        fatcat.db.session.commit()
        assert FileRev.query.count() == 1
        model_after = FileRev.query.first()
        serial = file_rev_schema.dump(model_after).data
        check_file(serial)
        for k in e.keys():
            assert e[k] == serial[k]

## API Tests #################################################################

class APITestCase(FatcatTestCase):

    def test_health(self):
        rv = self.app.get('/health')
        obj = json.loads(rv.data.decode('utf-8'))
        assert obj['ok']

    def test_api_work(self):
        fatcat.dummy.insert_example_works()

        # Invalid Id
        rv = self.app.get('/v0/work/_')
        assert rv.status_code == 404

        # Random
        rv = self.app.get('/v0/work/random')
        rv = self.app.get(rv.location)
        work = json.loads(rv.data.decode('utf-8'))
        check_entity_fields(work)
        print(work)
        assert work['title']
        assert work['work_type']

        # Valid Id (from random above)
        rv = self.app.get('/v0/work/{}'.format(work['id']))
        assert rv.status_code == 200

        # Missing Id
        rv = self.app.get('/v0/work/r3zga5b9cd7ef8gh084714iljk')
        assert rv.status_code == 404

    def test_api_work_create(self):
        assert WorkIdent.query.count() == 0
        assert WorkRev.query.count() == 0
        assert WorkEdit.query.count() == 0
        rv = self.app.post('/v0/work',
            data=json.dumps(dict(title="dummy", work_type="thing", extra=dict(a=1, b="zing"))),
            headers={"content-type": "application/json"})
        print(rv)
        assert rv.status_code == 200
        assert WorkIdent.query.count() == 1
        assert WorkRev.query.count() == 1
        assert WorkEdit.query.count() == 1
        # not alive yet
        assert WorkIdent.query.filter(WorkIdent.is_live==True).count() == 0

    def test_api_complete_create(self):

        # TODO: create user?

        rv = self.app.post('/v0/editgroup',
            data=json.dumps(dict(
                extra=dict(q=1, u="zing"))),
            headers={"content-type": "application/json"})
        assert rv.status_code == 200
        obj = json.loads(rv.data.decode('utf-8'))
        editgroup_id = obj['id']

        for cls in (WorkIdent, WorkRev, WorkEdit,
                    ContainerIdent, ContainerRev, ContainerEdit,
                    CreatorIdent, CreatorRev, CreatorEdit,
                    ReleaseIdent, ReleaseRev, ReleaseEdit,
                    FileIdent, FileRev, FileEdit,
                    ChangelogEntry):
            assert cls.query.count() == 0

        rv = self.app.post('/v0/container',
            data=json.dumps(dict(
                name="schmournal",
                publisher="society of authors",
                issn="2222-3333",
                editgroup=editgroup_id)),
                #extra=dict(a=1, i="zing"))),
            headers={"content-type": "application/json"})
        assert rv.status_code == 200
        obj = json.loads(rv.data.decode('utf-8'))
        container_id = obj['id']

        rv = self.app.post('/v0/creator',
            data=json.dumps(dict(
                name="anon y. mouse",
                orcid="0000-0002-1825-0097",
                editgroup=editgroup_id)),
                #extra=dict(w=1, q="zing"))),
            headers={"content-type": "application/json"})
        assert rv.status_code == 200
        obj = json.loads(rv.data.decode('utf-8'))
        creator_id = obj['id']

        rv = self.app.post('/v0/work',
            data=json.dumps(dict(
                title="dummy work",
                work_type="book",
                editgroup=editgroup_id)),
                #extra=dict(a=1, b="zing"))),
            headers={"content-type": "application/json"})
        assert rv.status_code == 200
        obj = json.loads(rv.data.decode('utf-8'))
        work_id = obj['id']

        rv = self.app.post('/v0/release',
            data=json.dumps(dict(
                title="dummy work",
                work_type="book",
                #work=work_id,
                #container=container_id,
                #creators=[creator_id],
                doi="10.1234/5678",
                editgroup=editgroup_id,
                refs=[
                    dict(stub="some other journal article"),
                ])),
                #extra=dict(f=7, b="zing"))),
            headers={"content-type": "application/json"})
        assert rv.status_code == 200
        obj = json.loads(rv.data.decode('utf-8'))
        release_id = obj['id']

        rv = self.app.post('/v0/file',
            data=json.dumps(dict(
                sha1="deadbeefdeadbeef",
                size=1234,
                release=release_id,
                editgroup=editgroup_id)),
                #extra=dict(f=7, b="zing"))),
            headers={"content-type": "application/json"})
        assert rv.status_code == 200
        obj = json.loads(rv.data.decode('utf-8'))

        for cls in (WorkIdent, WorkRev, WorkEdit,
                    ContainerIdent, ContainerRev, ContainerEdit,
                    CreatorIdent, CreatorRev, CreatorEdit,
                    ReleaseIdent, ReleaseRev, ReleaseEdit,
                    FileIdent, FileRev, FileEdit):
            assert cls.query.count() == 1
            # Ident only: assert cls.query.filter(is_live=True).count() == 1

        rv = self.app.post('/v0/editgroup/{}/accept'.format(editgroup_id),
            headers={"content-type": "application/json"})
        # XXX: assert rv.status_code == 200
        # XXX: assert ChangelogEntry.query.count() == 1

        for cls in (WorkIdent, WorkRev, WorkEdit,
                    ContainerIdent, ContainerRev, ContainerEdit,
                    CreatorIdent, CreatorRev, CreatorEdit,
                    ReleaseIdent, ReleaseRev, ReleaseEdit,
                    FileIdent, FileRev, FileEdit):
            assert cls.query.count() == 1
            # Ident only: assert cls.query.filter(is_live=True).count() == 1