Skip to content

Commit 37b8fb3

Browse files
committed
cp to tests
1 parent 5cf703f commit 37b8fb3

File tree

1 file changed

+311
-0
lines changed

1 file changed

+311
-0
lines changed

tests/test_relation.py

Lines changed: 311 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,311 @@
1+
from inspect import getmembers
2+
import re
3+
import pandas
4+
import numpy as np
5+
from nose.tools import (
6+
assert_equal,
7+
assert_not_equal,
8+
assert_true,
9+
assert_list_equal,
10+
raises,
11+
)
12+
import datajoint as dj
13+
from datajoint.table import Table
14+
from unittest.mock import patch
15+
16+
from . import schema
17+
18+
19+
def relation_selector(attr):
20+
try:
21+
return issubclass(attr, Table)
22+
except TypeError:
23+
return False
24+
25+
26+
class TestRelation:
27+
"""
28+
Test base relations: insert, delete
29+
"""
30+
31+
@classmethod
32+
def setup_class(cls):
33+
cls.test = schema.TTest()
34+
cls.test_extra = schema.TTestExtra()
35+
cls.test_no_extra = schema.TTestNoExtra()
36+
cls.user = schema.User()
37+
cls.subject = schema.Subject()
38+
cls.experiment = schema.Experiment()
39+
cls.trial = schema.Trial()
40+
cls.ephys = schema.Ephys()
41+
cls.channel = schema.Ephys.Channel()
42+
cls.img = schema.Image()
43+
cls.trash = schema.UberTrash()
44+
45+
def test_contents(self):
46+
"""
47+
test the ability of tables to self-populate using the contents property
48+
"""
49+
# test contents
50+
assert_true(self.user)
51+
assert_true(len(self.user) == len(self.user.contents))
52+
u = self.user.fetch(order_by=["username"])
53+
assert_list_equal(
54+
list(u["username"]), sorted([s[0] for s in self.user.contents])
55+
)
56+
57+
# test prepare
58+
assert_true(self.subject)
59+
assert_true(len(self.subject) == len(self.subject.contents))
60+
u = self.subject.fetch(order_by=["subject_id"])
61+
assert_list_equal(
62+
list(u["subject_id"]), sorted([s[0] for s in self.subject.contents])
63+
)
64+
65+
@raises(dj.DataJointError)
66+
def test_misnamed_attribute1(self):
67+
self.user.insert([dict(username="Bob"), dict(user="Alice")])
68+
69+
@raises(KeyError)
70+
def test_misnamed_attribute2(self):
71+
self.user.insert1(dict(user="Bob"))
72+
73+
@raises(KeyError)
74+
def test_extra_attribute1(self):
75+
self.user.insert1(dict(username="Robert", spouse="Alice"))
76+
77+
def test_extra_attribute2(self):
78+
self.user.insert1(
79+
dict(username="Robert", spouse="Alice"), ignore_extra_fields=True
80+
)
81+
82+
@raises(NotImplementedError)
83+
def test_missing_definition(self):
84+
@schema.schema
85+
class MissingDefinition(dj.Manual):
86+
definitions = """ # misspelled definition
87+
id : int
88+
---
89+
comment : varchar(16) # otherwise everything's normal
90+
"""
91+
92+
@raises(dj.DataJointError)
93+
def test_empty_insert1(self):
94+
self.user.insert1(())
95+
96+
@raises(dj.DataJointError)
97+
def test_empty_insert(self):
98+
self.user.insert([()])
99+
100+
@raises(dj.DataJointError)
101+
def test_wrong_arguments_insert(self):
102+
self.user.insert1(("First", "Second"))
103+
104+
@raises(dj.DataJointError)
105+
def test_wrong_insert_type(self):
106+
self.user.insert1(3)
107+
108+
def test_insert_select(self):
109+
schema.TTest2.delete()
110+
schema.TTest2.insert(schema.TTest)
111+
assert_equal(len(schema.TTest2()), len(schema.TTest()))
112+
113+
original_length = len(self.subject)
114+
elements = self.subject.proj(..., s="subject_id")
115+
elements = elements.proj(
116+
"real_id",
117+
"date_of_birth",
118+
"subject_notes",
119+
subject_id="s+1000",
120+
species='"human"',
121+
)
122+
self.subject.insert(elements, ignore_extra_fields=True)
123+
assert_equal(len(self.subject), 2 * original_length)
124+
125+
def test_insert_pandas_roundtrip(self):
126+
"""ensure fetched frames can be inserted"""
127+
schema.TTest2.delete()
128+
n = len(schema.TTest())
129+
assert_true(n > 0)
130+
df = schema.TTest.fetch(format="frame")
131+
assert_true(isinstance(df, pandas.DataFrame))
132+
assert_equal(len(df), n)
133+
schema.TTest2.insert(df)
134+
assert_equal(len(schema.TTest2()), n)
135+
136+
def test_insert_pandas_userframe(self):
137+
"""
138+
ensure simple user-created frames (1 field, non-custom index)
139+
can be inserted without extra index adjustment
140+
"""
141+
schema.TTest2.delete()
142+
n = len(schema.TTest())
143+
assert_true(n > 0)
144+
df = pandas.DataFrame(schema.TTest.fetch())
145+
assert_true(isinstance(df, pandas.DataFrame))
146+
assert_equal(len(df), n)
147+
schema.TTest2.insert(df)
148+
assert_equal(len(schema.TTest2()), n)
149+
150+
@raises(dj.DataJointError)
151+
def test_insert_select_ignore_extra_fields0(self):
152+
"""need ignore extra fields for insert select"""
153+
self.test_extra.insert1((self.test.fetch("key").max() + 1, 0, 0))
154+
self.test.insert(self.test_extra)
155+
156+
def test_insert_select_ignore_extra_fields1(self):
157+
"""make sure extra fields works in insert select"""
158+
self.test_extra.delete()
159+
keyno = self.test.fetch("key").max() + 1
160+
self.test_extra.insert1((keyno, 0, 0))
161+
self.test.insert(self.test_extra, ignore_extra_fields=True)
162+
assert keyno in self.test.fetch("key")
163+
164+
def test_insert_select_ignore_extra_fields2(self):
165+
"""make sure insert select still works when ignoring extra fields when there are none"""
166+
self.test_no_extra.delete()
167+
self.test_no_extra.insert(self.test, ignore_extra_fields=True)
168+
169+
def test_insert_select_ignore_extra_fields3(self):
170+
"""make sure insert select works for from query result"""
171+
self.test_no_extra.delete()
172+
keystr = str(self.test_extra.fetch("key").max())
173+
self.test_no_extra.insert(
174+
(self.test_extra & "`key`=" + keystr), ignore_extra_fields=True
175+
)
176+
177+
def test_skip_duplicates(self):
178+
"""test that skip_duplicates works when inserting from another table"""
179+
self.test_no_extra.delete()
180+
self.test_no_extra.insert(
181+
self.test, ignore_extra_fields=True, skip_duplicates=True
182+
)
183+
self.test_no_extra.insert(
184+
self.test, ignore_extra_fields=True, skip_duplicates=True
185+
)
186+
187+
def test_replace(self):
188+
"""
189+
Test replacing or ignoring duplicate entries
190+
"""
191+
key = dict(subject_id=7)
192+
date = "2015-01-01"
193+
self.subject.insert1(dict(key, real_id=7, date_of_birth=date, subject_notes=""))
194+
assert_equal(
195+
date, str((self.subject & key).fetch1("date_of_birth")), "incorrect insert"
196+
)
197+
date = "2015-01-02"
198+
self.subject.insert1(
199+
dict(key, real_id=7, date_of_birth=date, subject_notes=""),
200+
skip_duplicates=True,
201+
)
202+
assert_not_equal(
203+
date,
204+
str((self.subject & key).fetch1("date_of_birth")),
205+
"inappropriate replace",
206+
)
207+
self.subject.insert1(
208+
dict(key, real_id=7, date_of_birth=date, subject_notes=""), replace=True
209+
)
210+
assert_equal(
211+
date, str((self.subject & key).fetch1("date_of_birth")), "replace failed"
212+
)
213+
214+
def test_delete_quick(self):
215+
"""Tests quick deletion"""
216+
tmp = np.array(
217+
[
218+
(2, "Klara", "monkey", "2010-01-01", ""),
219+
(1, "Peter", "mouse", "2015-01-01", ""),
220+
],
221+
dtype=self.subject.heading.as_dtype,
222+
)
223+
self.subject.insert(tmp)
224+
s = self.subject & (
225+
"subject_id in (%s)" % ",".join(str(r) for r in tmp["subject_id"])
226+
)
227+
assert_true(len(s) == 2, "insert did not work.")
228+
s.delete_quick()
229+
assert_true(len(s) == 0, "delete did not work.")
230+
231+
def test_skip_duplicate(self):
232+
"""Tests if duplicates are properly skipped."""
233+
tmp = np.array(
234+
[
235+
(2, "Klara", "monkey", "2010-01-01", ""),
236+
(1, "Peter", "mouse", "2015-01-01", ""),
237+
],
238+
dtype=self.subject.heading.as_dtype,
239+
)
240+
self.subject.insert(tmp)
241+
tmp = np.array(
242+
[
243+
(2, "Klara", "monkey", "2010-01-01", ""),
244+
(1, "Peter", "mouse", "2015-01-01", ""),
245+
],
246+
dtype=self.subject.heading.as_dtype,
247+
)
248+
self.subject.insert(tmp, skip_duplicates=True)
249+
250+
@raises(dj.errors.DuplicateError)
251+
def test_not_skip_duplicate(self):
252+
"""Tests if duplicates are not skipped."""
253+
tmp = np.array(
254+
[
255+
(2, "Klara", "monkey", "2010-01-01", ""),
256+
(2, "Klara", "monkey", "2010-01-01", ""),
257+
(1, "Peter", "mouse", "2015-01-01", ""),
258+
],
259+
dtype=self.subject.heading.as_dtype,
260+
)
261+
self.subject.insert(tmp, skip_duplicates=False)
262+
263+
@raises(dj.errors.MissingAttributeError)
264+
def test_no_error_suppression(self):
265+
"""skip_duplicates=True should not suppress other errors"""
266+
self.test.insert([dict(key=100)], skip_duplicates=True)
267+
268+
def test_blob_insert(self):
269+
"""Tests inserting and retrieving blobs."""
270+
X = np.random.randn(20, 10)
271+
self.img.insert1((1, X))
272+
Y = self.img.fetch()[0]["img"]
273+
assert_true(np.all(X == Y), "Inserted and retrieved image are not identical")
274+
275+
def test_drop(self):
276+
"""Tests dropping tables"""
277+
dj.config["safemode"] = True
278+
with patch.object(dj.utils, "input", create=True, return_value="yes"):
279+
self.trash.drop()
280+
try:
281+
self.trash.fetch()
282+
raise Exception("Fetched after table dropped.")
283+
except dj.DataJointError:
284+
pass
285+
finally:
286+
dj.config["safemode"] = False
287+
288+
def test_table_regexp(self):
289+
"""Test whether table names are matched by regular expressions"""
290+
tiers = [dj.Imported, dj.Manual, dj.Lookup, dj.Computed]
291+
for name, rel in getmembers(schema, relation_selector):
292+
assert_true(
293+
re.match(rel.tier_regexp, rel.table_name),
294+
"Regular expression does not match for {name}".format(name=name),
295+
)
296+
for tier in tiers:
297+
assert_true(
298+
issubclass(rel, tier)
299+
or not re.match(tier.tier_regexp, rel.table_name),
300+
"Regular expression matches for {name} but should not".format(
301+
name=name
302+
),
303+
)
304+
305+
def test_table_size(self):
306+
"""test getting the size of the table and its indices in bytes"""
307+
number_of_bytes = self.experiment.size_on_disk
308+
assert_true(isinstance(number_of_bytes, int) and number_of_bytes > 100)
309+
310+
def test_repr_html(self):
311+
assert_true(self.ephys._repr_html_().strip().startswith("<style"))

0 commit comments

Comments
 (0)