| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
from __future__ import print_function |
| 7 |
|
| 8 |
from __future__ import division |
| 9 |
from __future__ import absolute_import |
| 10 |
|
| 11 |
import sys,os |
| 12 |
|
| 13 |
import unittest |
| 14 |
import CifFile |
| 15 |
from CifFile import StarFile |
| 16 |
from CifFile.StarFile import StarDict, StarList, StarLengthError |
| 17 |
import re |
| 18 |
try: |
| 19 |
from StringIO import StringIO |
| 20 |
except: |
| 21 |
from io import StringIO |
| 22 |
|
| 23 |
|
| 24 |
class BasicUtilitiesTestCase(unittest.TestCase): |
| 25 |
def testPlainLineFolding(self): |
| 26 |
"""Test that we can fold a line correctly""" |
| 27 |
test_string = "1234567890123456789012" |
| 28 |
outstring = CifFile.apply_line_folding(test_string,5,10) |
| 29 |
out_lines = outstring.split('\n') |
| 30 |
|
| 31 |
self.assertTrue(out_lines[0]=="\\") |
| 32 |
self.assertTrue(len(out_lines[1])==10) |
| 33 |
|
| 34 |
def testPreWrappedFolding(self): |
| 35 |
"""Test that pre-wrapped lines are untouched""" |
| 36 |
test_string = "123456789\n012345678\n9012" |
| 37 |
outstring = CifFile.apply_line_folding(test_string,5,10) |
| 38 |
self.assertTrue(outstring == test_string) |
| 39 |
|
| 40 |
def testManyLineEndings(self): |
| 41 |
"""Test that empty lines are handled OK""" |
| 42 |
test_string = "123456789\n\n012345678\n\n9012\n\n" |
| 43 |
outstring = CifFile.apply_line_folding(test_string,5,10) |
| 44 |
self.assertTrue(outstring == test_string) |
| 45 |
|
| 46 |
def testOptionalBreak(self): |
| 47 |
"""Test that internal whitespace is used to break""" |
| 48 |
test_string = "123456 7890123 45678\n90 12\n\n" |
| 49 |
outstring = CifFile.apply_line_folding(test_string,5,10) |
| 50 |
|
| 51 |
out_lines = outstring.split('\n') |
| 52 |
self.assertTrue(len(out_lines[1]) == 7) |
| 53 |
|
| 54 |
def testCorrectEnding(self): |
| 55 |
"""Make sure that no line feeds are added/removed""" |
| 56 |
test_string = "123456 7890123 45678\n90 12\n\n" |
| 57 |
outstring = CifFile.apply_line_folding(test_string,5,10) |
| 58 |
self.assertTrue(outstring[-4:] == "12\n\n") |
| 59 |
|
| 60 |
def testFoldingRemoval(self): |
| 61 |
"""Test that we round-trip correctly""" |
| 62 |
test_string = "123456 7890123 45678\n90 12\n\n" |
| 63 |
outstring = CifFile.apply_line_folding(test_string,5,10) |
| 64 |
old_string = CifFile.remove_line_folding(outstring) |
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
self.assertTrue(old_string == test_string) |
| 69 |
|
| 70 |
def testTrickyFoldingRemoval(self): |
| 71 |
"""Try to produce a tough string for unfolding""" |
| 72 |
test_string = "\n1234567890\\\n r t s 345 19\n\nlife don't talk to me about life" |
| 73 |
outstring = CifFile.apply_line_folding(test_string,5,10) |
| 74 |
old_string = CifFile.remove_line_folding(outstring) |
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
self.assertTrue(old_string == test_string) |
| 79 |
|
| 80 |
def testTrailingBackslash(self): |
| 81 |
"""Make sure that a trailing backslash is not removed""" |
| 82 |
test_string = "\n123\\\n 456\\n\n" |
| 83 |
outstring = CifFile.apply_line_folding(test_string,5,10) |
| 84 |
old_string = CifFile.remove_line_folding(outstring) |
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
self.assertTrue(old_string == test_string) |
| 89 |
|
| 90 |
def testFinalBackslash(self): |
| 91 |
"""Make sure that a single final backslash is removed when unfolding""" |
| 92 |
test_string = "\n1234567890\\\n r t s 345 19\n\nlife don't talk to me about life" |
| 93 |
folded_string = CifFile.apply_line_folding(test_string,5,10) |
| 94 |
folded_string = folded_string + r"\ " |
| 95 |
old_string = CifFile.remove_line_folding(folded_string) |
| 96 |
self.assertTrue(old_string == test_string) |
| 97 |
|
| 98 |
def testAddIndent(self): |
| 99 |
"""Test insertion of a line prefix""" |
| 100 |
test_string = "\n12345\n678910\n\n" |
| 101 |
outstring = CifFile.apply_line_prefix(test_string,"abc>") |
| 102 |
print("Converted %s to %s " %(test_string,outstring)) |
| 103 |
self.assertTrue(outstring == "abc>\\\nabc>\nabc>12345\nabc>678910\nabc>\nabc>") |
| 104 |
|
| 105 |
def testRemoveIndent(self): |
| 106 |
"""Test removal of a line prefix""" |
| 107 |
test_string = "abc>\\\nabc>12345\nabc>678910\nabc>\nabc>" |
| 108 |
outstring = CifFile.remove_line_prefix(test_string) |
| 109 |
print("Removed indent: " + repr(outstring)) |
| 110 |
self.assertTrue(outstring == "12345\n678910\n\n") |
| 111 |
|
| 112 |
def testReverseIndent(self): |
| 113 |
"""Test reversible indentation of line""" |
| 114 |
test_string = "12345\n678910\n\n" |
| 115 |
outstring = CifFile.apply_line_prefix(test_string,"cif><") |
| 116 |
newtest = CifFile.remove_line_prefix(outstring) |
| 117 |
print('Before indenting: ' + repr(test_string)) |
| 118 |
print('After indenting: ' + repr(outstring)) |
| 119 |
print('After unindent: ' + repr(newtest)) |
| 120 |
self.assertTrue(newtest == test_string) |
| 121 |
|
| 122 |
def testPrefixAndFold(self): |
| 123 |
"""Test reversible folding and indenting""" |
| 124 |
test_string = "\n1234567890\\\n r t s 345 19\n\nlife don't talk to me about life" |
| 125 |
outstring = CifFile.apply_line_folding(test_string,5,10) |
| 126 |
indoutstring = CifFile.apply_line_prefix(outstring,"CIF>") |
| 127 |
newoutstring = CifFile.remove_line_prefix(indoutstring) |
| 128 |
newtest_string = CifFile.remove_line_folding(newoutstring) |
| 129 |
print("%s -> %s -> %s -> %s -> %s" % (repr(test_string),repr(outstring),repr(indoutstring),repr(newoutstring),repr(newtest_string))) |
| 130 |
self.assertTrue(newtest_string == test_string) |
| 131 |
|
| 132 |
def testStringiness(self): |
| 133 |
"""Check that we can detect string-valued items correctly""" |
| 134 |
import numpy |
| 135 |
self.assertEqual(CifFile.check_stringiness(['1','2','3']),True) |
| 136 |
self.assertEqual(CifFile.check_stringiness([1,2,'3']),False) |
| 137 |
self.assertEqual(CifFile.check_stringiness(['1',['2',['3',4,'5'],'6','7'],'8']),False) |
| 138 |
self.assertEqual(CifFile.check_stringiness(['1',['2',['3','4','5'],'6','7'],'8']),True) |
| 139 |
p = numpy.array([[1,2,3],[4,5,6]]) |
| 140 |
self.assertEqual(CifFile.check_stringiness(p),False) |
| 141 |
|
| 142 |
def testStarList(self): |
| 143 |
"""Test that starlists allow comma-based access""" |
| 144 |
p = StarList([StarList([1,2,3]),StarList([4,5,6])]) |
| 145 |
self.assertTrue(p[1,0]==4) |
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
class BlockRWTestCase(unittest.TestCase): |
| 150 |
def setUp(self): |
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
self.cf = CifFile.CifBlock() |
| 155 |
|
| 156 |
def tearDown(self): |
| 157 |
|
| 158 |
del self.cf |
| 159 |
|
| 160 |
def testTupleNumberSet(self): |
| 161 |
"""Test tuple setting with numbers""" |
| 162 |
self.cf['_test_tuple'] = (11,13.5,-5.6) |
| 163 |
self.assertTrue([float(a) for a in self.cf['_test_tuple']]== [11,13.5,-5.6]) |
| 164 |
|
| 165 |
def testStringSet(self): |
| 166 |
"""test string setting""" |
| 167 |
self.cf['_test_string_'] = 'A short string' |
| 168 |
self.assertTrue(self.cf['_test_string_'] == 'A short string') |
| 169 |
|
| 170 |
def testTooLongSet(self): |
| 171 |
"""test setting overlong data names""" |
| 172 |
dataname = '_a_long_long_'*7 |
| 173 |
try: |
| 174 |
self.cf[dataname] = 1.0 |
| 175 |
except (CifFile.StarError,CifFile.CifError): pass |
| 176 |
else: self.fail() |
| 177 |
|
| 178 |
def testTooLongLoopSet(self): |
| 179 |
"""test setting overlong data names in a loop""" |
| 180 |
dataname = '_a_long_long_'*7 |
| 181 |
try: |
| 182 |
self.cf[dataname] = (1.0,2.0,3.0) |
| 183 |
except (CifFile.StarError,CifFile.CifError): pass |
| 184 |
else: self.fail() |
| 185 |
|
| 186 |
def testBadStringSet(self): |
| 187 |
"""test setting values with bad characters""" |
| 188 |
dataname = '_name_is_ok' |
| 189 |
try: |
| 190 |
self.cf[dataname] = "eca234\f\vaqkadlf" |
| 191 |
except CifFile.StarError: pass |
| 192 |
else: self.fail() |
| 193 |
|
| 194 |
def testBadNameSet(self): |
| 195 |
"""test setting names with bad characters""" |
| 196 |
dataname = "_this_is_not ok" |
| 197 |
try: |
| 198 |
self.cf[dataname] = "nnn" |
| 199 |
except CifFile.StarError: pass |
| 200 |
else: self.fail() |
| 201 |
|
| 202 |
def testMoreBadStrings(self): |
| 203 |
dataname = "_name_is_ok" |
| 204 |
val = (b"so far, ok, but now we have a " + bytearray([128])).decode('latin_1') |
| 205 |
try: |
| 206 |
self.cf[dataname] = val |
| 207 |
except CifFile.StarError: pass |
| 208 |
else: self.fail() |
| 209 |
|
| 210 |
def testEmptyString(self): |
| 211 |
"""An empty string is, in fact, legal""" |
| 212 |
self.cf['_an_empty_string'] = '' |
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
class BlockChangeTestCase(unittest.TestCase): |
| 218 |
def setUp(self): |
| 219 |
self.cf = CifFile.CifBlock() |
| 220 |
self.names = ('_item_name_1','_item_name#2','_item_%$#3') |
| 221 |
self.values = ((1,2,3,4),('hello','good_bye','a space','# 4'), |
| 222 |
(15.462, -99.34,10804,0.0001)) |
| 223 |
for n,v in zip(self.names, self.values): |
| 224 |
self.cf.AddItem(n, v) |
| 225 |
self.cf.CreateLoop(self.names) |
| 226 |
|
| 227 |
self.cf['_non_loop_item'] = 'Non loop string item' |
| 228 |
self.cf['_number_item'] = 15.65 |
| 229 |
self.cf['_planet'] = 'Saturn' |
| 230 |
self.cf['_satellite'] = 'Titan' |
| 231 |
self.cf['_rings'] = 'True' |
| 232 |
|
| 233 |
def tearDown(self): |
| 234 |
del self.cf |
| 235 |
|
| 236 |
def testFromBlockSet(self): |
| 237 |
"""Test that we can use a CifBlock to set a CifBlock""" |
| 238 |
df = CifFile.CifFile() |
| 239 |
df.NewBlock('testname',self.cf) |
| 240 |
self.assertEqual(df['testname']['_planet'],'Saturn') |
| 241 |
self.assertEqual(df['testname']['_item_name#2'],list(self.values[1])) |
| 242 |
|
| 243 |
def testSimpleRemove(self): |
| 244 |
"""Check item deletion outside loop""" |
| 245 |
self.cf.RemoveCifItem('_non_loop_item') |
| 246 |
try: |
| 247 |
a = self.cf['_non_loop_item'] |
| 248 |
except KeyError: pass |
| 249 |
else: self.fail() |
| 250 |
|
| 251 |
def testLoopRemove(self): |
| 252 |
"""Check item deletion inside loop""" |
| 253 |
print("Before:\n") |
| 254 |
print(self.cf.printsection()) |
| 255 |
self.cf.RemoveCifItem(self.names[1]) |
| 256 |
print("After:\n") |
| 257 |
print(self.cf.printsection()) |
| 258 |
try: |
| 259 |
a = self.cf[self.names[1]] |
| 260 |
except KeyError: pass |
| 261 |
else: self.fail() |
| 262 |
|
| 263 |
def testFullLoopRemove(self): |
| 264 |
"""Check removal of all loop items""" |
| 265 |
for name in self.names: self.cf.RemoveCifItem(name) |
| 266 |
self.assertTrue(len(self.cf.loops)==0, repr(self.cf.loops)) |
| 267 |
|
| 268 |
def testChangeLoop(self): |
| 269 |
"""Test changing pre-existing item in loop""" |
| 270 |
|
| 271 |
self.cf["_item_name_1"] = (5,6,7,8) |
| 272 |
|
| 273 |
|
| 274 |
|
| 275 |
|
| 276 |
def testGetOperation(self): |
| 277 |
"""Test the get mapping call""" |
| 278 |
self.cf.get("_item_name_1") |
| 279 |
self.cf.get("_item_name_nonexist") |
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
def testDataNameCase(self): |
| 285 |
"""Test same name, different case causes error""" |
| 286 |
self.assertEqual(self.cf["_Item_Name_1"],self.cf["_item_name_1"]) |
| 287 |
self.cf["_Item_NaMe_1"] = "the quick pewse fox" |
| 288 |
self.assertEqual(self.cf["_Item_NaMe_1"],self.cf["_item_name_1"]) |
| 289 |
|
| 290 |
class SyntaxErrorTestCase(unittest.TestCase): |
| 291 |
"""Check that files with syntax errors are found""" |
| 292 |
def tearDown(self): |
| 293 |
try: |
| 294 |
os.remove("tests/syntax_check.cif") |
| 295 |
except: |
| 296 |
pass |
| 297 |
|
| 298 |
def testTripleApostropheCase(self): |
| 299 |
teststrg = "#\\#CIF_2.0\ndata_testblock\n _item_1 ''' ''' '''\n" |
| 300 |
f = open("tests/syntax_check.cif","w") |
| 301 |
f.write(teststrg) |
| 302 |
f.close() |
| 303 |
self.assertRaises(CifFile.StarError, CifFile.ReadCif,"tests/syntax_check.cif",grammar="2.0") |
| 304 |
|
| 305 |
def testTripleQuoteCase(self): |
| 306 |
teststrg = '#\\#CIF_2.0\ndata_testblock\n _item_1 """ """ """\n' |
| 307 |
f = open("tests/syntax_check.cif","w") |
| 308 |
f.write(teststrg) |
| 309 |
f.close() |
| 310 |
self.assertRaises(CifFile.StarError, CifFile.ReadCif,"tests/syntax_check.cif",grammar="2.0") |
| 311 |
|
| 312 |
class LoopBlockTestCase(unittest.TestCase): |
| 313 |
"""Check operations on loop blocks""" |
| 314 |
def setUp(self): |
| 315 |
self.cf = CifFile.CifBlock() |
| 316 |
self.names = ('_Item_Name_1','_item_name#2','_item_%$#3') |
| 317 |
self.values = ((1,2,3,4),('hello','good_bye','a space','# 4'), |
| 318 |
(15.462, -99.34,10804,0.0001)) |
| 319 |
for n,v in zip(self.names, self.values): |
| 320 |
self.cf.AddItem(n, v) |
| 321 |
self.cf.CreateLoop(self.names) |
| 322 |
|
| 323 |
self.cf['_non_loop_item'] = 'Non loop string item' |
| 324 |
self.cf['_number_item'] = 15.65 |
| 325 |
self.cf['_planet'] = 'Saturn' |
| 326 |
self.cf['_satellite'] = 'Titan' |
| 327 |
self.cf['_rings'] = 'True' |
| 328 |
|
| 329 |
self.cf['_ck_1'] = ['1','1','1','2','2','2','3','3','3'] |
| 330 |
self.cf['_Ck_2'] = ['r','g','b','r','g','b','r','g','b'] |
| 331 |
self.cf['_stuff'] = ['Q','W','E','R','T','Y','U','I','O'] |
| 332 |
self.cf.CreateLoop(['_ck_1','_ck_2','_stuff']) |
| 333 |
|
| 334 |
def tearDown(self): |
| 335 |
del self.cf |
| 336 |
|
| 337 |
def testLoop(self): |
| 338 |
"""Check GetLoop returns values and names in matching order""" |
| 339 |
results = self.cf.GetLoop(self.names[2]) |
| 340 |
lowernames = [a.lower() for a in self.names] |
| 341 |
for key in results.keys(): |
| 342 |
self.assertTrue(key.lower() in lowernames) |
| 343 |
self.assertTrue(tuple(results[key]) == self.values[lowernames.index(key.lower())]) |
| 344 |
|
| 345 |
def testLoopCharCase(self): |
| 346 |
"""Test that upper/lower case names in loops works correctly""" |
| 347 |
|
| 348 |
self.cf['_item_name_20'] = ['a','b','c','q'] |
| 349 |
self.cf.AddLoopName('_item_Name_1','_Item_name_20') |
| 350 |
self.assertTrue(self.cf.FindLoop('_Item_name_1')==self.cf.FindLoop('_Item_Name_20')) |
| 351 |
|
| 352 |
def testGetLoopCase(self): |
| 353 |
"""Check that getloop works for any case""" |
| 354 |
results = self.cf.GetLoop('_Item_Name_1') |
| 355 |
self.assertEqual(results['_item_name_1'][1],2) |
| 356 |
|
| 357 |
def testLoopOutputOrder(self): |
| 358 |
"""Check that an item placed in a loop no longer appears in the output order""" |
| 359 |
self.cf['_item_name_20'] = ['a','b','c','q'] |
| 360 |
self.cf.AddLoopName('_item_Name_1','_Item_name_20') |
| 361 |
self.assertTrue('_item_name_20' not in self.cf.GetItemOrder()) |
| 362 |
|
| 363 |
def testLoopify(self): |
| 364 |
"""Test changing unlooped data to looped data""" |
| 365 |
self.cf.CreateLoop(["_planet","_satellite","_rings"]) |
| 366 |
newloop = self.cf.GetLoop("_rings") |
| 367 |
self.assertFalse(newloop.has_key("_number_item")) |
| 368 |
|
| 369 |
def testLoopifyCif(self): |
| 370 |
"""Test changing unlooped data to looped data does |
| 371 |
not touch already looped data for a CIF file""" |
| 372 |
self.cf.CreateLoop(["_planet","_satellite","_rings"]) |
| 373 |
newloop = self.cf.GetLoop("_rings") |
| 374 |
self.assertTrue(newloop.has_key('_planet')) |
| 375 |
self.assertTrue(isinstance(self.cf["_planet"],list)) |
| 376 |
|
| 377 |
|
| 378 |
|
| 379 |
def testIteration(self): |
| 380 |
"""We create an iterator and iterate""" |
| 381 |
testloop = self.cf.GetLoop("_item_name_1") |
| 382 |
i = 0 |
| 383 |
for test_pack in testloop: |
| 384 |
self.assertEqual(test_pack._item_name_1,self.values[0][i]) |
| 385 |
self.assertEqual(getattr(test_pack,"_item_name#2"),self.values[1][i]) |
| 386 |
i += 1 |
| 387 |
|
| 388 |
def testPacketContents(self): |
| 389 |
"""Test that body of packet is filled in as well""" |
| 390 |
testloop = self.cf.GetLoop("_item_name_1") |
| 391 |
it_order = testloop.GetItemOrder() |
| 392 |
itn_pos = it_order.index("_item_name_1") |
| 393 |
for test_pack in testloop: |
| 394 |
print('Test pack: ' + repr(test_pack)) |
| 395 |
self.assertEqual(test_pack._item_name_1,test_pack[itn_pos]) |
| 396 |
|
| 397 |
def testPacketAttr(self): |
| 398 |
"""Test that packets have attributes""" |
| 399 |
testloop = self.cf.GetLoop("_item_name_1") |
| 400 |
self.assertEqual(testloop[1]._item_name_1,2) |
| 401 |
|
| 402 |
def testKeyPacket(self): |
| 403 |
"""Test that a packet can be returned by key value""" |
| 404 |
testpack = self.cf.GetKeyedPacket("_item_name_1",2) |
| 405 |
self.assertEqual("good_bye",getattr(testpack,"_item_name#2")) |
| 406 |
|
| 407 |
def testCompoundKeyPacket(self): |
| 408 |
"""Test that a compound key can also be used""" |
| 409 |
testpack = self.cf.GetCompoundKeyedPacket({"_ck_1":('2',False),"_ck_2":('b',False)}) |
| 410 |
self.assertEqual("Y",getattr(testpack,"_stuff")) |
| 411 |
|
| 412 |
def testPacketMerge(self): |
| 413 |
"""Test that a packet can be merged with another packet""" |
| 414 |
bigcf = CifFile.CifFile("tests/C13H22O3.cif") |
| 415 |
bigcf = bigcf["II"] |
| 416 |
testpack = bigcf.GetKeyedPacket("_atom_site_label","C4A") |
| 417 |
newpack = bigcf.GetKeyedPacket("_atom_site_aniso_label","C4A") |
| 418 |
testpack.merge_packet(newpack) |
| 419 |
self.assertEqual(getattr(testpack,'_atom_site_aniso_U_22'),'0.0312(15)') |
| 420 |
self.assertEqual(getattr(testpack,'_atom_site_fract_x'),'0.7192(3)') |
| 421 |
|
| 422 |
def testRemovePacket(self): |
| 423 |
"""Test that removing a packet works properly""" |
| 424 |
print('Before packet removal') |
| 425 |
print(str(self.cf)) |
| 426 |
testloop = self.cf.GetLoop("_item_name_1") |
| 427 |
testloop.RemoveKeyedPacket("_item_name_1",3) |
| 428 |
print('After packet 3 removal:') |
| 429 |
jj = testloop.GetKeyedPacket("_item_name_1",2) |
| 430 |
kk = testloop.GetKeyedPacket("_item_name_1",4) |
| 431 |
self.assertEqual(getattr(jj,"_item_name#2"),"good_bye") |
| 432 |
self.assertEqual(getattr(kk,"_item_name#2"),"# 4") |
| 433 |
self.assertRaises(ValueError,testloop.GetKeyedPacket,"_item_name_1",3) |
| 434 |
print('After packet removal:') |
| 435 |
print(str(self.cf)) |
| 436 |
|
| 437 |
def testAddPacket(self): |
| 438 |
"""Test that we can add a packet""" |
| 439 |
import copy |
| 440 |
testloop = self.cf.GetLoop("_item_name_1") |
| 441 |
workingpacket = copy.copy(testloop.GetPacket(0)) |
| 442 |
workingpacket._item_name_1 = '5' |
| 443 |
workingpacket.__setattr__("_item_name#2", 'new' ) |
| 444 |
testloop.AddPacket(workingpacket) |
| 445 |
|
| 446 |
|
| 447 |
self.assertEqual(testloop["_item_name_1"][4],'5') |
| 448 |
self.assertEqual(testloop["_item_name#2"][4],'new') |
| 449 |
|
| 450 |
|
| 451 |
|
| 452 |
|
| 453 |
def testChangeOrder(self): |
| 454 |
"""We move some stuff around""" |
| 455 |
testloop = self.cf.GetLoop("_item_name_1") |
| 456 |
self.cf.ChangeItemOrder("_Number_Item",0) |
| 457 |
testloop.ChangeItemOrder("_Item_Name_1",2) |
| 458 |
self.assertEqual(testloop.GetItemOrder()[2],"_Item_Name_1".lower()) |
| 459 |
self.assertEqual(self.cf.GetItemOrder()[0],"_Number_Item".lower()) |
| 460 |
|
| 461 |
def testGetOrder(self): |
| 462 |
"""Test that the correct order value is returned""" |
| 463 |
self.assertEqual(self.cf.GetItemPosition("_Number_Item"),(-1,2)) |
| 464 |
|
| 465 |
def testReplaceOrder(self): |
| 466 |
"""Test that a replaced item is at the same position it |
| 467 |
previously held""" |
| 468 |
testloop = self.cf.GetLoop("_item_name_1") |
| 469 |
oldpos = testloop.GetItemPosition('_item_name#2') |
| 470 |
testloop['_item_name#2'] = ("I'm",' a ','little','teapot') |
| 471 |
self.assertEqual(testloop.GetItemPosition('_item_name#2'),oldpos) |
| 472 |
|
| 473 |
|
| 474 |
|
| 475 |
|
| 476 |
class BlockNameTestCase(unittest.TestCase): |
| 477 |
def testBlockName(self): |
| 478 |
"""Make sure long block names cause errors""" |
| 479 |
df = CifFile.CifBlock() |
| 480 |
cf = CifFile.CifFile() |
| 481 |
try: |
| 482 |
cf['a_very_long_block_name_which_should_be_rejected_out_of_hand123456789012345678']=df |
| 483 |
except CifFile.StarError: pass |
| 484 |
else: self.fail() |
| 485 |
|
| 486 |
def testBlockOverwrite(self): |
| 487 |
"""Upper/lower case should be seen as identical""" |
| 488 |
df = CifFile.CifBlock() |
| 489 |
ef = CifFile.CifBlock() |
| 490 |
cf = CifFile.CifFile(standard=None) |
| 491 |
df['_random_1'] = 'oldval' |
| 492 |
ef['_random_1'] = 'newval' |
| 493 |
print('cf.standard is ' + repr(cf.standard)) |
| 494 |
cf['_lowercaseblock'] = df |
| 495 |
cf['_LowerCaseBlock'] = ef |
| 496 |
assert(cf['_Lowercaseblock']['_random_1'] == 'newval') |
| 497 |
assert(len(cf) == 1) |
| 498 |
|
| 499 |
def testEmptyBlock(self): |
| 500 |
"""Test that empty blocks are not the same object""" |
| 501 |
cf = CifFile.CifFile() |
| 502 |
cf.NewBlock('first_block') |
| 503 |
cf.NewBlock('second_block') |
| 504 |
cf['first_block']['_test1'] = 'abc' |
| 505 |
cf['second_block']['_test1'] = 'def' |
| 506 |
self.assertEqual(cf['first_block']['_test1'],'abc') |
| 507 |
|
| 508 |
|
| 509 |
|
| 510 |
|
| 511 |
class FileWriteTestCase(unittest.TestCase): |
| 512 |
def setUp(self): |
| 513 |
"""Write out a file, then read it in again. Non alphabetic ordering to |
| 514 |
check order preservation and mixed case.""" |
| 515 |
|
| 516 |
items = (('_item_1','Some data'), |
| 517 |
('_item_3','34.2332'), |
| 518 |
('_item_4','Some very long data which we hope will overflow the single line and force printing of another line aaaaa bbbbbb cccccc dddddddd eeeeeeeee fffffffff hhhhhhhhh iiiiiiii jjjjjj'), |
| 519 |
('_item_2','Some_underline_data'), |
| 520 |
('_item_empty',''), |
| 521 |
('_item_quote',"'ABC"), |
| 522 |
('_item_apost','"def'), |
| 523 |
('_item_sws'," \n "), |
| 524 |
('_item_bad_beg',"data_journal"), |
| 525 |
(('_item_5','_item_7','_item_6'), |
| 526 |
([1,2,3,4], |
| 527 |
['a','b','c','d'], |
| 528 |
[5,6,7,8])), |
| 529 |
(('_string_1','_string_2'), |
| 530 |
([';this string begins with a semicolon', |
| 531 |
'this string is way way too long and should overflow onto the next line eventually if I keep typing for long enough', |
| 532 |
';just_any_old_semicolon-starting-string'], |
| 533 |
['a string with a final quote"', |
| 534 |
'a string with a " and a safe\';', |
| 535 |
'a string with a final \'']))) |
| 536 |
|
| 537 |
s_items = (('_sitem_1','Some save data'), |
| 538 |
('_sitem_2','Some_underline_data'), |
| 539 |
('_sitem_3','34.2332'), |
| 540 |
('_sitem_4','Some very long data which we hope will overflow the single line and force printing of another line aaaaa bbbbbb cccccc dddddddd eeeeeeeee fffffffff hhhhhhhhh iiiiiiii jjjjjj'), |
| 541 |
(('_sitem_5','_sitem_6','_sitem_7'), |
| 542 |
([1,2,3,4], |
| 543 |
[5,6,7,8], |
| 544 |
['a','b','c','d'])), |
| 545 |
(('_string_1','_string_2'), |
| 546 |
([';this string begins with a semicolon', |
| 547 |
'this string is way way too long and should overflow onto the next line eventually if I keep typing for long enough', |
| 548 |
';just_any_old_semicolon-starting-string'], |
| 549 |
['a string with a final quote"', |
| 550 |
'a string with a " and a safe\';', |
| 551 |
'a string with a final \'']))) |
| 552 |
self.cf = CifFile.CifBlock(items) |
| 553 |
cif = CifFile.CifFile(scoping='dictionary',maxoutlength=80) |
| 554 |
cif['Testblock'] = self.cf |
| 555 |
|
| 556 |
self.save_block = CifFile.CifBlock(s_items) |
| 557 |
cif.NewBlock("test_Save_frame",self.save_block,parent='testblock') |
| 558 |
self.cfs = cif["test_save_frame"] |
| 559 |
outfile = open('tests/test.cif','w') |
| 560 |
outfile.write(str(cif)) |
| 561 |
outfile.close() |
| 562 |
self.ef = CifFile.CifFile('tests/test.cif',scoping='dictionary') |
| 563 |
self.df = self.ef['testblock'] |
| 564 |
self.dfs = self.ef["test_save_frame"] |
| 565 |
flfile = CifFile.ReadCif('tests/test.cif',scantype="flex",scoping='dictionary') |
| 566 |
|
| 567 |
tstream = open('tests/test.cif') |
| 568 |
CifFile.CifFile(tstream,scantype="flex") |
| 569 |
CifFile.ReadCif(tstream,scantype="flex") |
| 570 |
self.flf = flfile['testblock'] |
| 571 |
self.flfs = flfile["Test_save_frame"] |
| 572 |
|
| 573 |
def tearDown(self): |
| 574 |
try: |
| 575 |
os.remove('tests/test.cif') |
| 576 |
os.remove('tests/test2.cif') |
| 577 |
except: |
| 578 |
pass |
| 579 |
|
| 580 |
del self.dfs |
| 581 |
del self.df |
| 582 |
del self.cf |
| 583 |
del self.ef |
| 584 |
del self.flf |
| 585 |
del self.flfs |
| 586 |
|
| 587 |
def testStringInOut(self): |
| 588 |
"""Test writing short strings in and out""" |
| 589 |
self.assertTrue(self.cf['_item_1']==self.df['_item_1']) |
| 590 |
self.assertTrue(self.cf['_item_2']==self.df['_item_2']) |
| 591 |
self.assertTrue(self.cfs['_sitem_1']==self.dfs['_sitem_1']) |
| 592 |
self.assertTrue(self.cfs['_sitem_2']==self.dfs['_sitem_2']) |
| 593 |
self.assertTrue(self.cfs['_sitem_1']==self.flfs['_sitem_1']) |
| 594 |
self.assertTrue(self.cfs['_sitem_2']==self.flfs['_sitem_2']) |
| 595 |
|
| 596 |
def testApostropheInOut(self): |
| 597 |
"""Test correct behaviour for values starting with apostrophes |
| 598 |
or quotation marks""" |
| 599 |
self.assertTrue(self.cf['_item_quote']==self.df['_item_quote']) |
| 600 |
self.assertTrue(self.cf['_item_apost']==self.df['_item_apost']) |
| 601 |
self.assertTrue(self.cf['_item_quote']==self.flf['_item_quote']) |
| 602 |
self.assertTrue(self.cf['_item_apost']==self.flf['_item_apost']) |
| 603 |
|
| 604 |
def testNumberInOut(self): |
| 605 |
"""Test writing number in and out""" |
| 606 |
self.assertTrue(self.cf['_item_3']==(self.df['_item_3'])) |
| 607 |
self.assertTrue(self.cfs['_sitem_3']==(self.dfs['_sitem_3'])) |
| 608 |
self.assertTrue(self.cf['_item_3']==(self.flf['_item_3'])) |
| 609 |
self.assertTrue(self.cfs['_sitem_3']==(self.flfs['_sitem_3'])) |
| 610 |
|
| 611 |
def testLongStringInOut(self): |
| 612 |
"""Test writing long string in and out |
| 613 |
Note that whitespace may vary due to carriage returns, |
| 614 |
so we remove all returns before comparing""" |
| 615 |
import re |
| 616 |
compstring = re.sub('\n','',self.df['_item_4']) |
| 617 |
self.assertTrue(compstring == self.cf['_item_4']) |
| 618 |
compstring = re.sub('\n','',self.dfs['_sitem_4']) |
| 619 |
self.assertTrue(compstring == self.cfs['_sitem_4']) |
| 620 |
compstring = re.sub('\n','',self.flf['_item_4']) |
| 621 |
self.assertTrue(compstring == self.cf['_item_4']) |
| 622 |
compstring = re.sub('\n','',self.flfs['_sitem_4']) |
| 623 |
self.assertTrue(compstring == self.cfs['_sitem_4']) |
| 624 |
|
| 625 |
def testEmptyStringInOut(self): |
| 626 |
"""An empty string is in fact kosher""" |
| 627 |
self.assertTrue(self.cf['_item_empty']=='') |
| 628 |
self.assertTrue(self.flf['_item_empty']=='') |
| 629 |
|
| 630 |
def testSemiWhiteSpace(self): |
| 631 |
"""Test that white space in a semicolon string is preserved""" |
| 632 |
self.assertTrue(self.cf['_item_sws']==self.df['_item_sws']) |
| 633 |
self.assertTrue(self.cf['_item_sws']==self.flf['_item_sws']) |
| 634 |
|
| 635 |
def testLoopDataInOut(self): |
| 636 |
"""Test writing in and out loop data""" |
| 637 |
olditems = self.cf.GetLoop('_item_5') |
| 638 |
for key,value in olditems.items(): |
| 639 |
self.assertTrue(tuple(map(str,value))==tuple(self.df[key])) |
| 640 |
self.assertTrue(tuple(map(str,value))==tuple(self.flf[key])) |
| 641 |
|
| 642 |
olditems = self.cfs.GetLoop('_sitem_5').items() |
| 643 |
for key,value in olditems: |
| 644 |
self.assertTrue(tuple(map(str,value))==tuple(self.dfs[key])) |
| 645 |
self.assertTrue(tuple(map(str,value))==tuple(self.flfs[key])) |
| 646 |
|
| 647 |
def testLoopStringInOut(self): |
| 648 |
"""Test writing in and out string loop data""" |
| 649 |
olditems = self.cf.GetLoop('_string_1') |
| 650 |
newitems = self.df.GetLoop('_string_1') |
| 651 |
flexnewitems = self.flf.GetLoop('_string_1') |
| 652 |
for key,value in olditems.items(): |
| 653 |
compstringa = [re.sub('\n','',a) for a in value] |
| 654 |
compstringb = [re.sub('\n','',a) for a in self.df[key]] |
| 655 |
compstringc = [re.sub('\n','',a) for a in self.flf[key]] |
| 656 |
self.assertTrue(compstringa==compstringb and compstringa==compstringc) |
| 657 |
|
| 658 |
def testGetLoopData(self): |
| 659 |
"""Test the get method for looped data""" |
| 660 |
newvals = self.df.get('_string_1') |
| 661 |
self.assertTrue(len(newvals)==3) |
| 662 |
|
| 663 |
def testCopySaveFrame(self): |
| 664 |
"""Early implementations didn't copy the save frame properly""" |
| 665 |
jj = CifFile.CifFile(self.ef,scoping='dictionary') |
| 666 |
self.assertTrue(len(jj["test_save_frame"])>0) |
| 667 |
|
| 668 |
def testFirstBlock(self): |
| 669 |
"""Test that first_block returns a block""" |
| 670 |
self.ef.scoping = 'instance' |
| 671 |
jj = self.ef.first_block() |
| 672 |
self.assertTrue(jj==self.df) |
| 673 |
|
| 674 |
def testWrongLoop(self): |
| 675 |
"""Test derived from error observed during dREL testing""" |
| 676 |
teststrg = """data_test |
| 677 |
loop_ |
| 678 |
_atom_type.symbol |
| 679 |
_atom_type.oxidation_number |
| 680 |
_atom_type.atomic_mass |
| 681 |
_atom_type.number_in_cell |
| 682 |
O ? 15.999 12 |
| 683 |
C ? 12.011 28 |
| 684 |
H ? 1.008 24 |
| 685 |
""" |
| 686 |
q = open("tests/test2.cif","w") |
| 687 |
q.write(teststrg) |
| 688 |
q.close() |
| 689 |
testcif = CifFile.CifFile("tests/test2.cif").first_block() |
| 690 |
self.assertTrue(testcif['_atom_type.symbol']==['O','C','H']) |
| 691 |
|
| 692 |
def testDupName(self): |
| 693 |
"""Test that duplicate blocknames are allowed in non-standard mode""" |
| 694 |
outstr = """data_block1 _data_1 b save_ab1 _data_2 c |
| 695 |
save_ |
| 696 |
save_ab1 _data_3 d save_""" |
| 697 |
b = open("tests/test2.cif","w") |
| 698 |
b.write(outstr) |
| 699 |
b.close() |
| 700 |
testin = CifFile.CifFile("tests/test2.cif",standard=None) |
| 701 |
|
| 702 |
def testPrefixProtocol(self): |
| 703 |
"""Test that pathological strings round-trip correctly""" |
| 704 |
cif_as_text = open('tests/test.cif','r').read() |
| 705 |
bf = CifFile.CifFile(maxoutlength=80) |
| 706 |
bb = CifFile.CifBlock() |
| 707 |
bb['_data_embedded'] = cif_as_text |
| 708 |
bf['tough_one'] = bb |
| 709 |
out_f = open('tests/embedded.cif','w') |
| 710 |
out_f.write(str(bf)) |
| 711 |
out_f.close() |
| 712 |
in_emb = CifFile.CifFile('tests/embedded.cif',grammar='2.0') |
| 713 |
self.assertEqual(in_emb['tough_one']['_data_embedded'],cif_as_text) |
| 714 |
|
| 715 |
def testBadBeginning(self): |
| 716 |
"""Test that strings with forbidden beginnings round-trip OK""" |
| 717 |
self.assertTrue(self.cf['_item_bad_beg']==self.df['_item_bad_beg']) |
| 718 |
|
| 719 |
def testStrayCharacter(self): |
| 720 |
"""Test that CIF1 fails with non-ASCII characters""" |
| 721 |
outstr = b"""data_block1 _normal_str 'hello sunshine' |
| 722 |
_latin1_str abc\xB0efgh""" |
| 723 |
b = open("tests/test3_latin1.cif","wb") |
| 724 |
b.write(outstr) |
| 725 |
b.close() |
| 726 |
try: |
| 727 |
testin = CifFile.CifFile("tests/test3_latin1.cif",grammar="1.0",permissive=False) |
| 728 |
except CifFile.StarError: |
| 729 |
pass |
| 730 |
|
| 731 |
def testPermissiveRead(self): |
| 732 |
"""Test that stray latin-1 characters are accepted in permissive mode""" |
| 733 |
outstr = b"""data_block1 _normal_str 'hello sunshine' |
| 734 |
_latin1_str abc\xB0efgh""" |
| 735 |
b = open("tests/test3_latin1.cif","wb") |
| 736 |
b.write(outstr) |
| 737 |
b.close() |
| 738 |
testin = CifFile.CifFile("tests/test3_latin1.cif",grammar="1.0",permissive=True) |
| 739 |
|
| 740 |
def testItemChange(self): |
| 741 |
"""Test that an item from in input file can be changed""" |
| 742 |
self.flf['_item_quote']= '2.3' |
| 743 |
self.assertTrue(self.flf['_item_quote']=='2.3') |
| 744 |
|
| 745 |
def testEmptyDict(self): |
| 746 |
"""Test that a dictionary is processed correctly""" |
| 747 |
outstr = b"""#\\#CIF_2.0\ndata_block1 _a_dict {"a":2}\n""" |
| 748 |
b = open("tests/test4_dict.cif","wb") |
| 749 |
b.write(outstr) |
| 750 |
b.close() |
| 751 |
testin = CifFile.CifFile("tests/test4_dict.cif",grammar="2.0") |
| 752 |
self.assertTrue(testin["block1"]["_a_dict"] == {"a":"2"}) |
| 753 |
|
| 754 |
class SimpleWriteTestCase(unittest.TestCase): |
| 755 |
def setUp(self): |
| 756 |
self.bf = CifFile.CifBlock() |
| 757 |
self.cf = CifFile.CifFile() |
| 758 |
self.cf['testblock'] = self.bf |
| 759 |
self.testfile = "tests/test_3.cif" |
| 760 |
|
| 761 |
def tearDown(self): |
| 762 |
try: |
| 763 |
os.remove(self.testfile) |
| 764 |
except: |
| 765 |
pass |
| 766 |
|
| 767 |
def testNumpyArray(self): |
| 768 |
"""Check that an array can be output properly""" |
| 769 |
import numpy |
| 770 |
vector = numpy.array([1,2,3]) |
| 771 |
self.bf['_a_vector'] = vector |
| 772 |
open(self.testfile,"w").write(self.cf.WriteOut()) |
| 773 |
df = CifFile.CifFile(self.testfile,grammar="auto").first_block() |
| 774 |
print('vector is ' + repr(df['_a_vector'])) |
| 775 |
self.assertTrue(df['_a_vector'] == ['1','2','3']) |
| 776 |
|
| 777 |
def testNumpyLoop(self): |
| 778 |
"""Check that an array in a loop can be output properly""" |
| 779 |
import numpy |
| 780 |
vector_list = [numpy.array([1,2,3]),numpy.array([11,12,13]),numpy.array([-1.0,1.0,0.0])] |
| 781 |
self.bf['_a_vector'] = vector_list |
| 782 |
self.bf.CreateLoop(["_a_vector"]) |
| 783 |
open(self.testfile,"w").write(self.cf.WriteOut()) |
| 784 |
df = CifFile.CifFile(self.testfile,grammar="auto").first_block() |
| 785 |
print('vector is ' + repr(df['_a_vector'])) |
| 786 |
self.assertTrue(df['_a_vector'][2] == ['-1.0','1.0','0.0']) |
| 787 |
|
| 788 |
def testNDString(self): |
| 789 |
"""Check that a string containing square brackets is properly quoted for CIF2.0""" |
| 790 |
self.bf['_tst'] = '3[4^6].8^5[3]' |
| 791 |
self.cf.set_grammar("2.0") |
| 792 |
open(self.testfile,"w").write(self.cf.WriteOut()) |
| 793 |
df = CifFile.CifFile(self.testfile,grammar="2.0").first_block() |
| 794 |
result = df['_tst'] |
| 795 |
self.assertTrue(df['_tst']== self.bf['_tst']) |
| 796 |
|
| 797 |
def testLong(self): |
| 798 |
"""Check that a long integer is acceptable in Python 2""" |
| 799 |
if sys.version_info < (3,): |
| 800 |
self.bf['_tst'] = long(12) |
| 801 |
else: |
| 802 |
self.bf['_tst'] = 12 |
| 803 |
q = str(self.bf) |
| 804 |
|
| 805 |
class TemplateTestCase(unittest.TestCase): |
| 806 |
def setUp(self): |
| 807 |
"""Create a template""" |
| 808 |
template_string = r"""#\#CIF_2.0 |
| 809 |
# Template |
| 810 |
# |
| 811 |
data_TEST_DIC |
| 812 |
|
| 813 |
_dictionary.title DDL_DIC |
| 814 |
_definition.update 2011-07-27 |
| 815 |
_description.text |
| 816 |
; |
| 817 |
This dictionary specifies through its layout how we desire to |
| 818 |
format datanames. It is not a valid dictionary, but it must |
| 819 |
be a valid CIF file. |
| 820 |
; |
| 821 |
_name.category_id blahblah |
| 822 |
_name.object_id ALIAS |
| 823 |
_category.key_id '_alias.definition_id' |
| 824 |
_category.key_list ['_alias.definition_id'] |
| 825 |
_type.purpose Key |
| 826 |
_type.dimension [*] |
| 827 |
_import.get [{"file":'templ_enum.cif' "save":'units_code'}] |
| 828 |
loop_ |
| 829 |
_enumeration_set.state |
| 830 |
_enumeration_set.detail |
| 831 |
Dictionary "applies to all defined items in the dictionary" |
| 832 |
Category "applies to all defined items in the category" |
| 833 |
Item "applies to a single item definition" |
| 834 |
_enumeration.default Item |
| 835 |
""" |
| 836 |
f = open("tests/cif_template.cif","w") |
| 837 |
f.write(template_string) |
| 838 |
f.close() |
| 839 |
|
| 840 |
def tearDown(self): |
| 841 |
try: |
| 842 |
os.remove("tests/cif_template.cif") |
| 843 |
os.remove("tests/temp_test_file.cif") |
| 844 |
os.remove("tests/temp_test_file_new.cif") |
| 845 |
except: |
| 846 |
pass |
| 847 |
|
| 848 |
def testTemplateInput(self): |
| 849 |
"""Test that an output template is successfully input""" |
| 850 |
p = CifFile.CifFile() |
| 851 |
p.SetTemplate("tests/cif_template.cif") |
| 852 |
|
| 853 |
self.assertTrue(p.master_template[0]['dataname']=='_dictionary.title') |
| 854 |
self.assertTrue(p.master_template[5]['column']==31) |
| 855 |
self.assertTrue(p.master_template[2]['delimiter']=='\n;') |
| 856 |
self.assertTrue(p.master_template[11]['column']==11) |
| 857 |
self.assertTrue(p.master_template[12]['delimiter']=='"') |
| 858 |
self.assertTrue(p.master_template[2]['reformat']==True) |
| 859 |
self.assertTrue(p.master_template[2]['reformat_indent']==5) |
| 860 |
|
| 861 |
def testTemplateOutputOrder(self): |
| 862 |
"""Test that items are output in the correct order""" |
| 863 |
test_file = """## |
| 864 |
data_test |
| 865 |
_enumeration.default Item |
| 866 |
_name.object_id ALIAS |
| 867 |
_crazy_dummy_dataname 'whahey look at me' |
| 868 |
loop_ |
| 869 |
_enumeration_set.detail |
| 870 |
_enumeration_set.state |
| 871 |
_enumeration_set.dummy |
| 872 |
'applies to all' dictionary 0 |
| 873 |
'cat only' category 1 |
| 874 |
'whatever' item 2 |
| 875 |
_name.category_id blahblah |
| 876 |
_description.text |
| 877 |
;a nice long string that we would like |
| 878 |
to be formatted really nicely with an appropriate indent and so forth. Note |
| 879 |
that the template specifies an indent of 5 characters for this particular |
| 880 |
data item, and we shouldn't have more than two spaces in a row if we want it |
| 881 |
to work properly. |
| 882 |
; |
| 883 |
""" |
| 884 |
f = open("tests/temp_test_file.cif","w") |
| 885 |
f.write(test_file) |
| 886 |
f.close() |
| 887 |
p = CifFile.CifFile("tests/temp_test_file.cif") |
| 888 |
p.SetTemplate("tests/cif_template.cif") |
| 889 |
f = open("tests/temp_test_file_new.cif","w") |
| 890 |
f.write(str(p)) |
| 891 |
f.close() |
| 892 |
|
| 893 |
g = CifFile.CifFile("tests/temp_test_file_new.cif").first_block() |
| 894 |
self.assertEqual(g.item_order[1],'_name.category_id') |
| 895 |
self.assertEqual(g.loops[1][-1],'_enumeration_set.dummy') |
| 896 |
self.assertEqual(g.loops[1][0],'_enumeration_set.state') |
| 897 |
self.assertEqual(g.item_order[-1],'_crazy_dummy_dataname') |
| 898 |
|
| 899 |
def testStringInput(self): |
| 900 |
"""Test that it works when passed a stringIO object""" |
| 901 |
s = open("tests/cif_template.cif","r").read() |
| 902 |
ss = StringIO(s) |
| 903 |
p = CifFile.CifFile() |
| 904 |
p.SetTemplate(ss) |
| 905 |
self.assertTrue(p.master_template[12]['delimiter']=='"') |
| 906 |
|
| 907 |
|
| 908 |
|
| 909 |
|
| 910 |
|
| 911 |
|
| 912 |
|
| 913 |
|
| 914 |
|
| 915 |
|
| 916 |
class GrammarTestCase(unittest.TestCase): |
| 917 |
def setUp(self): |
| 918 |
"""Write out a file, then read it in again.""" |
| 919 |
teststr1_0 = """ |
| 920 |
#A test CIF file, grammar version 1.0 conformant |
| 921 |
data_Test |
| 922 |
_item_1 'A simple item' |
| 923 |
_item_2 '(Bracket always ok in quotes)' |
| 924 |
_item_3 [can_have_bracket_here_if_1.0] |
| 925 |
""" |
| 926 |
f = open("tests/test_1.0","w") |
| 927 |
f.write(teststr1_0) |
| 928 |
f.close() |
| 929 |
teststr2_0 = r"""#\#CIF_2.0 |
| 930 |
data_Test |
| 931 |
_item_1 ['a' 'b' 'c' 'd'] |
| 932 |
_item_2 'ordinary string' |
| 933 |
_item_3 {'a':2 'b':3} |
| 934 |
""" |
| 935 |
f = open("tests/test_2.0","w") |
| 936 |
f.write(teststr2_0) |
| 937 |
f.close() |
| 938 |
teststr_st = """ |
| 939 |
data_Test |
| 940 |
_item_1 ['a' , 'b' , 'c' , 'd'] |
| 941 |
_item_2 'ordinary string' |
| 942 |
_item_3 {'a':2 , 'b':3} |
| 943 |
""" |
| 944 |
f = open("tests/test_star","w") |
| 945 |
f.write(teststr_st) |
| 946 |
f.close() |
| 947 |
|
| 948 |
def tearDown(self): |
| 949 |
try: |
| 950 |
os.remove("tests/test_star") |
| 951 |
os.remove("tests/test_2.0") |
| 952 |
os.remove("tests/test_1.0") |
| 953 |
except: |
| 954 |
pass |
| 955 |
|
| 956 |
def testold(self): |
| 957 |
"""Read in 1.0 conformant file; should not fail""" |
| 958 |
f = CifFile.ReadCif("tests/test_1.0",grammar="1.0") |
| 959 |
self.assertEqual(f["test"]["_item_3"],'[can_have_bracket_here_if_1.0]') |
| 960 |
self.assertEqual(f.grammar, "1.0") |
| 961 |
|
| 962 |
def testNew(self): |
| 963 |
"""Read in a 1.0 conformant file with 1.1 grammar; should fail""" |
| 964 |
try: |
| 965 |
f = CifFile.ReadCif("tests/test_1.0",grammar="1.1") |
| 966 |
except CifFile.StarError: |
| 967 |
pass |
| 968 |
|
| 969 |
def testCIF2(self): |
| 970 |
"""Read in a 2.0 conformant file""" |
| 971 |
f = CifFile.ReadCif("tests/test_2.0",grammar="2.0") |
| 972 |
self.assertEqual(f["test"]["_item_3"]['b'],'3') |
| 973 |
self.assertEqual(f.grammar, "2.0") |
| 974 |
|
| 975 |
def testSTAR2(self): |
| 976 |
"""Read in a STAR2 conformant file""" |
| 977 |
f = CifFile.ReadCif("tests/test_star",grammar="STAR2") |
| 978 |
self.assertEqual(f["test"]["_item_3"]['b'],'3') |
| 979 |
self.assertEqual(f.grammar, "STAR2") |
| 980 |
|
| 981 |
def testAuto(self): |
| 982 |
"""Test that grammar is auto-detected""" |
| 983 |
f = CifFile.CifFile("tests/test_1.0",grammar="auto") |
| 984 |
self.assertEqual(f["test"]["_item_3"],'[can_have_bracket_here_if_1.0]') |
| 985 |
self.assertEqual(f.grammar, "1.0") |
| 986 |
h = CifFile.CifFile("tests/test_2.0",grammar="auto") |
| 987 |
self.assertEqual(h["test"]["_item_1"],StarList(['a','b','c','d'])) |
| 988 |
self.assertEqual(h.grammar, "2.0") |
| 989 |
|
| 990 |
def testFlexCIF2(self): |
| 991 |
"""Test that CIF2 grammar is detected with flex tokenizer""" |
| 992 |
f = CifFile.CifFile("tests/test_2.0",grammar="2.0",scantype="flex") |
| 993 |
self.assertEqual(f["test"]["_item_3"]['b'],'3') |
| 994 |
|
| 995 |
def testFlexSTAR2(self): |
| 996 |
"""Read in a STAR2 conformant file with flex scanner""" |
| 997 |
f = CifFile.ReadCif("tests/test_star",grammar="STAR2",scantype="flex") |
| 998 |
self.assertEqual(f["test"]["_item_3"]['b'],'3') |
| 999 |
|
| 1000 |
def testRoundTrip(self): |
| 1001 |
"""Read in STAR2, write out CIF2, read in and check """ |
| 1002 |
f = CifFile.ReadCif("tests/test_star",grammar="STAR2") |
| 1003 |
g = open("tests/star_to_cif2","w") |
| 1004 |
f.set_grammar("2.0") |
| 1005 |
g.write(str(f)) |
| 1006 |
g.close() |
| 1007 |
h = CifFile.ReadCif("tests/star_to_cif2",grammar="2.0") |
| 1008 |
self.assertEqual(f["test"]["_item_3"],h["test"]["_item_3"]) |
| 1009 |
|
| 1010 |
class ParentChildTestCase(unittest.TestCase): |
| 1011 |
def setUp(self): |
| 1012 |
"""Write out a multi-save-frame file, read in again""" |
| 1013 |
outstring = """ |
| 1014 |
data_Toplevel |
| 1015 |
_item_1 a |
| 1016 |
save_1 |
| 1017 |
_s1_item1 b |
| 1018 |
save_12 |
| 1019 |
_s12_item1 c |
| 1020 |
save_ |
| 1021 |
save_13 |
| 1022 |
_s13_item1 d |
| 1023 |
save_ |
| 1024 |
save_ |
| 1025 |
_item_2 e |
| 1026 |
save_2 |
| 1027 |
_s2_item1 f |
| 1028 |
save_21 |
| 1029 |
_s21_item1 g |
| 1030 |
save_211 |
| 1031 |
_s211_item1 h |
| 1032 |
save_ |
| 1033 |
save_212 |
| 1034 |
_s212_item1 i |
| 1035 |
save_ |
| 1036 |
save_ |
| 1037 |
save_22 |
| 1038 |
_s22_item1 j |
| 1039 |
save_ |
| 1040 |
save_ |
| 1041 |
save_toplevel |
| 1042 |
_item_1 k |
| 1043 |
save_ |
| 1044 |
""" |
| 1045 |
f = open('tests/save_test.cif','w') |
| 1046 |
f.write(outstring) |
| 1047 |
f.close() |
| 1048 |
self.testcif = CifFile.CifFile('tests/save_test.cif',scoping='dictionary') |
| 1049 |
|
| 1050 |
def testGoodRead(self): |
| 1051 |
"""Check that there is a top level block""" |
| 1052 |
self.assertTrue('toplevel+' in [a[0] for a in self.testcif.child_table.items() if a[1].parent is None]) |
| 1053 |
self.assertTrue(self.testcif.child_table['toplevel'].parent == 'toplevel+') |
| 1054 |
|
| 1055 |
def testGetParent(self): |
| 1056 |
"""Check that parent is correctly identified""" |
| 1057 |
self.assertTrue(self.testcif.get_parent('212')=='21') |
| 1058 |
self.assertTrue(self.testcif.get_parent('12')=='1') |
| 1059 |
|
| 1060 |
def testGetChildren(self): |
| 1061 |
"""Test that our child blocks are constructed correctly""" |
| 1062 |
p = self.testcif.get_children('1') |
| 1063 |
self.assertTrue(p.has_key('13')) |
| 1064 |
self.assertTrue(not p.has_key('1')) |
| 1065 |
self.assertTrue(p.get_parent('13')==None) |
| 1066 |
self.assertTrue(p['12']['_s12_item1']=='c') |
| 1067 |
|
| 1068 |
def testGetChildrenwithParent(self): |
| 1069 |
"""Test that the parent is included if necessary""" |
| 1070 |
p = self.testcif.get_children('1',include_parent=True) |
| 1071 |
self.assertTrue(p.has_key('1')) |
| 1072 |
self.assertTrue(p.get_parent('13')=='1') |
| 1073 |
|
| 1074 |
def testSetParent(self): |
| 1075 |
"""Test that the parent is correctly set""" |
| 1076 |
self.testcif.set_parent('1','211') |
| 1077 |
q = self.testcif.get_children('1') |
| 1078 |
self.assertTrue('211' in q.keys()) |
| 1079 |
|
| 1080 |
def testChangeParent(self): |
| 1081 |
"""Test that a duplicated save frame is OK if the duplicate name is a data block""" |
| 1082 |
self.assertTrue('toplevel+' in self.testcif.keys()) |
| 1083 |
self.assertTrue(self.testcif.get_parent('1')=='toplevel+') |
| 1084 |
|
| 1085 |
def testRename1(self): |
| 1086 |
"""Test that re-identifying a datablock works""" |
| 1087 |
self.testcif._rekey('2','timey-wimey') |
| 1088 |
self.assertTrue(self.testcif.get_parent('21')=='timey-wimey') |
| 1089 |
self.assertTrue(self.testcif.has_key('timey-wimey')) |
| 1090 |
self.assertTrue(self.testcif['timey-wimey']['_s2_item1']=='f') |
| 1091 |
print(str(self.testcif)) |
| 1092 |
|
| 1093 |
def testRename2(self): |
| 1094 |
"""Test that renamng a block works""" |
| 1095 |
self.testcif.rename('2','Timey-wimey') |
| 1096 |
self.assertTrue(self.testcif.has_key('timey-wimey')) |
| 1097 |
self.assertTrue(self.testcif.child_table['timey-wimey'].block_id=='Timey-wimey') |
| 1098 |
|
| 1099 |
def testUnlock(self): |
| 1100 |
"""Test that unlocking will change overwrite flag""" |
| 1101 |
self.testcif['2'].overwrite = False |
| 1102 |
self.testcif.unlock() |
| 1103 |
self.assertTrue(self.testcif['2'].overwrite is True) |
| 1104 |
|
| 1105 |
class DDLmTestCase(unittest.TestCase): |
| 1106 |
def setUp(self): |
| 1107 |
"""Write out a file, then read it in again.""" |
| 1108 |
teststr1_2 = """ |
| 1109 |
#A test CIF file, grammar version 1.2 nonconformant |
| 1110 |
data_Test |
| 1111 |
_item_1 'A simple item' |
| 1112 |
_item_2 '(Bracket always ok in quotes)' |
| 1113 |
_item_3 (can_have_bracket_here_if_1.2) |
| 1114 |
_item_4 This_is_so_wrong?*~ |
| 1115 |
""" |
| 1116 |
goodstr1_2 = """ |
| 1117 |
#A test CIF file, grammar version 1.2 conformant with nested save frames |
| 1118 |
data_Test |
| 1119 |
_name.category_id CIF_DIC |
| 1120 |
_name.object_id CIF_CORE |
| 1121 |
_import.get |
| 1122 |
[{"save":'EXPERIMENTAL', "file":'core_exptl.dic', "mode":'full' }, |
| 1123 |
{"save":'DIFFRACTION', "file":'core_diffr.dic', "mode":'full' }, |
| 1124 |
{"save":'STRUCTURE', "file":'core_struc.dic', "mode":'full' }, |
| 1125 |
{"save":'MODEL', "file":'core_model.dic', "mode":'full' }, |
| 1126 |
{"save":'PUBLICATION', "file":'core_publn.dic', "mode":'full' }, |
| 1127 |
{"save":'FUNCTION', "file":'core_funct.dic', "mode":'full' }] |
| 1128 |
save_Savelevel1 |
| 1129 |
_item_in_save [1,2,3,4] |
| 1130 |
save_saveLevel2 |
| 1131 |
_item_in_inside_save {"hello":"goodbye","e":"mc2"} |
| 1132 |
save_ |
| 1133 |
save_ |
| 1134 |
_test.1 {"piffle":poffle,"wiffle":3,'''woffle''':9.2} |
| 1135 |
_test_2 {"ping":[1,2,3,4],"pong":[a,b,c,d]} |
| 1136 |
_test_3 {"ppp":{'qqq':2,'poke':{'joke':[5,6,7],'jike':[{'aa':bb,'cc':dd},{'ee':ff,"gg":100}]}},"rrr":[11,12,13]} |
| 1137 |
_triple_quote_test '''The comma is ok if, the quotes |
| 1138 |
are ok''' |
| 1139 |
_underscore_test underscores_are_allowed_inside_text |
| 1140 |
""" |
| 1141 |
f = open("tests/test_1.2","w") |
| 1142 |
f.write(teststr1_2) |
| 1143 |
f.close() |
| 1144 |
f = open("tests/goodtest_1.2","w") |
| 1145 |
f.write(goodstr1_2) |
| 1146 |
f.close() |
| 1147 |
|
| 1148 |
def tearDown(self): |
| 1149 |
try: |
| 1150 |
os.remove("tests/test_1.2") |
| 1151 |
os.remove("tests/goodtest_1.2") |
| 1152 |
os.remove("tests/newgoodtest_1.2.cif") |
| 1153 |
os.remove("tests/cif2goodtest_1.2.cif") |
| 1154 |
except: |
| 1155 |
pass |
| 1156 |
|
| 1157 |
def testold(self): |
| 1158 |
"""Read in 1.2 nonconformant file; should fail""" |
| 1159 |
try: |
| 1160 |
f = CifFile.ReadCif("tests/test_1.2",grammar="STAR2") |
| 1161 |
except CifFile.StarError: |
| 1162 |
pass |
| 1163 |
|
| 1164 |
def testgood(self): |
| 1165 |
"""Read in 1.2 conformant file: should succeed""" |
| 1166 |
f = CifFile.ReadCif("tests/goodtest_1.2",grammar="STAR2") |
| 1167 |
|
| 1168 |
def testTables(self): |
| 1169 |
"""Test that DDLm tables are properly parsed""" |
| 1170 |
f = CifFile.ReadCif("tests/goodtest_1.2",grammar="STAR2") |
| 1171 |
self.assertTrue(f["test"]["_test.1"]["wiffle"] == '3') |
| 1172 |
|
| 1173 |
def testTables2(self): |
| 1174 |
"""Test that a plain table is properly parsed""" |
| 1175 |
f = CifFile.ReadCif("tests/goodtest_1.2",grammar="STAR2") |
| 1176 |
self.assertTrue(f["test"]["_import.get"][0]["file"] == 'core_exptl.dic') |
| 1177 |
|
| 1178 |
def testTables3(self): |
| 1179 |
"""Test that a nested structure is properly parsed""" |
| 1180 |
f = CifFile.ReadCif("tests/goodtest_1.2",grammar="STAR2") |
| 1181 |
self.assertTrue(f["test"]["_test_3"]["ppp"]["poke"]["jike"][1]["gg"]=='100') |
| 1182 |
|
| 1183 |
def testTripleQuote(self): |
| 1184 |
"""Test that triple quoted values are treated correctly""" |
| 1185 |
f = CifFile.ReadCif("tests/goodtest_1.2",grammar="STAR2") |
| 1186 |
print(f["test"]["_triple_quote_test"]) |
| 1187 |
self.assertTrue(f["test"]["_triple_quote_test"][:9] == 'The comma') |
| 1188 |
|
| 1189 |
def testRoundTrip(self): |
| 1190 |
"""Test that a DDLm file can be read in, written out and read in again""" |
| 1191 |
f = CifFile.ReadCif("tests/goodtest_1.2",grammar="STAR2") |
| 1192 |
g = open("tests/newgoodtest_1.2.cif","w") |
| 1193 |
g.write(str(f)) |
| 1194 |
g.close() |
| 1195 |
h = CifFile.ReadCif("tests/newgoodtest_1.2.cif",grammar="STAR2") |
| 1196 |
|
| 1197 |
|
| 1198 |
|
| 1199 |
|
| 1200 |
self.assertTrue(h['Test']['_import.get'][2]['file']=='core_struc.dic') |
| 1201 |
|
| 1202 |
def testUnNest(self): |
| 1203 |
"""Test that we can convert a nested save frame STAR2 file to a non-nested file""" |
| 1204 |
f = CifFile.ReadCif("tests/goodtest_1.2",grammar="STAR2") |
| 1205 |
g = open("tests/cif2goodtest_1.2.cif","w") |
| 1206 |
f.set_grammar("2.0") |
| 1207 |
g.write(str(f)) |
| 1208 |
h = CifFile.ReadCif("tests/cif2goodtest_1.2.cif") |
| 1209 |
|
| 1210 |
|
| 1211 |
|
| 1212 |
|
| 1213 |
|
| 1214 |
|
| 1215 |
class DDLmImportCase(unittest.TestCase): |
| 1216 |
def setUp(self): |
| 1217 |
self.testdic = CifFile.CifDic("dictionaries/cif_core_ddlm.dic",grammar="2.0",do_dREL=False) |
| 1218 |
self.lightdic = CifFile.CifDic("dictionaries/cif_core_ddlm.dic",grammar="2.0", |
| 1219 |
do_imports='contents',heavy=False,do_dREL=False) |
| 1220 |
|
| 1221 |
def testHeavyImport(self): |
| 1222 |
"""Test that enumerated types were imported correctly""" |
| 1223 |
pp = self.testdic['_atom_type.radius_bond'] |
| 1224 |
self.assertTrue(pp.has_key('_enumeration_default.index')) |
| 1225 |
c_pos = pp['_enumeration_default.index'].index('C') |
| 1226 |
self.assertEqual(pp['_enumeration_default.value'][c_pos],'0.77') |
| 1227 |
|
| 1228 |
def testLightImport(self): |
| 1229 |
"""Test that light importation succeeds""" |
| 1230 |
pp = self.lightdic['_atom_type.radius_bond'] |
| 1231 |
self.assertTrue(pp.has_key('_enumeration_default.index')) |
| 1232 |
c_pos = pp['_enumeration_default.index'].index('C') |
| 1233 |
self.assertEqual(pp['_enumeration_default.value'][c_pos],'0.77') |
| 1234 |
|
| 1235 |
def testLightFullImport(self): |
| 1236 |
"""Test that we properly import nested dictionaries""" |
| 1237 |
nested_dic = CifFile.CifDic("dictionaries/cif_nested.dic",grammar="2.0", |
| 1238 |
do_imports='Full',do_dREL=False,heavy=False) |
| 1239 |
self.assertTrue(nested_dic['_refine_diff.density_max']['_enumeration.range']=='-100.:') |
| 1240 |
self.assertTrue('_pd_refln.phase_id' in nested_dic['refln']['_category_key.name']) |
| 1241 |
|
| 1242 |
|
| 1243 |
|
| 1244 |
|
| 1245 |
|
| 1246 |
|
| 1247 |
|
| 1248 |
|
| 1249 |
class DictTestCase(unittest.TestCase): |
| 1250 |
def setUp(self): |
| 1251 |
self.ddldic = CifFile.CifDic("tests/dictionaries/ddl.dic",grammar='2.0',scoping='dictionary',do_minimum=True) |
| 1252 |
|
| 1253 |
def tearDown(self): |
| 1254 |
try: |
| 1255 |
os.remove("test_dic_write.cif") |
| 1256 |
except: |
| 1257 |
pass |
| 1258 |
|
| 1259 |
def testnum_and_esd(self): |
| 1260 |
"""Test conversion of numbers with esds""" |
| 1261 |
testnums = ["5.65","-76.24(3)","8(2)","6.24(3)e3","55.2(2)d4"] |
| 1262 |
res = [CifFile.get_number_with_esd(a) for a in testnums] |
| 1263 |
print(repr(res)) |
| 1264 |
self.assertTrue(res[0]==(5.65,None)) |
| 1265 |
self.assertTrue(res[1]==(-76.24,0.03)) |
| 1266 |
self.assertTrue(res[2]==(8,2)) |
| 1267 |
self.assertTrue(res[3]==(6240,30)) |
| 1268 |
self.assertTrue(res[4]==(552000,2000)) |
| 1269 |
|
| 1270 |
def testdot(self): |
| 1271 |
"""Make sure a single dot is skipped""" |
| 1272 |
res1,res2 = CifFile.get_number_with_esd(".") |
| 1273 |
self.assertTrue(res1==None) |
| 1274 |
|
| 1275 |
def testCategoryRename(self): |
| 1276 |
"""Test that renaming a category works correctly""" |
| 1277 |
self.ddldic.change_category_name('Description','Opisanie') |
| 1278 |
self.assertTrue(self.ddldic.has_key('opisanie')) |
| 1279 |
self.assertTrue(self.ddldic['opisanie']['_name.object_id']=='Opisanie') |
| 1280 |
self.assertTrue(self.ddldic.has_key('opisanie.text')) |
| 1281 |
self.assertTrue(self.ddldic['opisanie.text']['_name.category_id']=='Opisanie') |
| 1282 |
self.assertTrue(self.ddldic['opisanie.text']['_definition.id']=='_Opisanie.text') |
| 1283 |
self.assertTrue(self.ddldic.has_key('description_example')) |
| 1284 |
|
| 1285 |
def testChangeItemCategory(self): |
| 1286 |
"""Test that changing an item's category works""" |
| 1287 |
self.ddldic.change_category('_description.common','type') |
| 1288 |
self.assertTrue('_type.common' in self.ddldic) |
| 1289 |
self.assertTrue('_description.common' not in self.ddldic) |
| 1290 |
self.assertTrue(self.ddldic['_type.common']['_name.category_id'].lower()=='type') |
| 1291 |
self.assertTrue(self.ddldic.get_parent('_type.common')=='type') |
| 1292 |
|
| 1293 |
def testChangeCategoryCategory(self): |
| 1294 |
"""Test that changing a category's category works""" |
| 1295 |
self.ddldic.change_category('description_example','attributes') |
| 1296 |
self.assertTrue(self.ddldic['description_example']['_name.category_id'].lower()=='attributes') |
| 1297 |
self.assertTrue(self.ddldic.get_parent('description_example')=='attributes') |
| 1298 |
|
| 1299 |
def testChangeName(self): |
| 1300 |
"""Test that changing the object_id works""" |
| 1301 |
self.ddldic.change_name('_description.common','uncommon') |
| 1302 |
self.assertTrue('_description.uncommon' in self.ddldic) |
| 1303 |
self.assertTrue('_description.common' not in self.ddldic) |
| 1304 |
self.assertTrue(self.ddldic['_description.uncommon']['_name.object_id']=='uncommon') |
| 1305 |
self.assertTrue(self.ddldic['_description.uncommon']['_definition.id']=='_description.uncommon') |
| 1306 |
|
| 1307 |
def testNewCategory(self): |
| 1308 |
"""Test that we can add a new category""" |
| 1309 |
self.ddldic.add_category('brand-new') |
| 1310 |
self.assertTrue('brand-new' in self.ddldic) |
| 1311 |
self.assertTrue(self.ddldic['brand-new']['_name.object_id']=='brand-new') |
| 1312 |
self.assertTrue(self.ddldic.get_parent('brand-new').lower()=='ddl_dic') |
| 1313 |
self.assertTrue(self.ddldic['brand-new']['_name.category_id'].lower()=='attributes') |
| 1314 |
|
| 1315 |
def testNewDefinition(self): |
| 1316 |
"""Test that we can add a new definition""" |
| 1317 |
realname = self.ddldic.add_definition('_junkety._junkjunk','description') |
| 1318 |
print('Real name for new definition is %s' % realname) |
| 1319 |
self.assertTrue('_description.junkjunk' in self.ddldic) |
| 1320 |
self.assertTrue(self.ddldic['_description.junkjunk']['_name.category_id'].lower()=='description') |
| 1321 |
self.assertTrue(self.ddldic['_description.junkjunk']['_name.object_id']=='junkjunk') |
| 1322 |
self.assertTrue(self.ddldic['_description.junkjunk']['_definition.id']=='_description.junkjunk') |
| 1323 |
|
| 1324 |
def testNewDanglerDef(self): |
| 1325 |
"""Test that we can add a new definition with external category""" |
| 1326 |
self.ddldic.add_definition('_junkety._junkjunk','external_cat',allow_dangler=True) |
| 1327 |
self.assertTrue('_external_cat.junkjunk' in self.ddldic) |
| 1328 |
self.assertTrue(self.ddldic['_external_cat.junkjunk']['_name.category_id'].lower()=='external_cat') |
| 1329 |
self.assertTrue(self.ddldic['_external_cat.junkjunk']['_name.object_id']=='junkjunk') |
| 1330 |
self.assertTrue(self.ddldic['_external_cat.junkjunk']['_definition.id']=='_external_cat.junkjunk') |
| 1331 |
|
| 1332 |
|
| 1333 |
def testNewDanglerCat(self): |
| 1334 |
"""Test that we can add a new category with external parent""" |
| 1335 |
self.ddldic.add_category('internal_cat','atom_site',allow_dangler=True) |
| 1336 |
self.assertTrue('internal_cat' in self.ddldic) |
| 1337 |
self.assertTrue(self.ddldic['internal_cat']['_name.object_id']=='internal_cat') |
| 1338 |
self.assertTrue(self.ddldic.get_parent('internal_cat').lower()=='ddl_dic') |
| 1339 |
self.assertTrue(self.ddldic['internal_cat']['_name.category_id'].lower()=='atom_site') |
| 1340 |
|
| 1341 |
def testDeleteDefinition(self): |
| 1342 |
"""Test that we can delete a definition""" |
| 1343 |
self.ddldic.remove_definition('_alias.deprecation_date') |
| 1344 |
self.assertTrue('_alias.deprecation_date' not in self.ddldic) |
| 1345 |
|
| 1346 |
def testDeleteCategory(self): |
| 1347 |
"""test that we can delete whole categories""" |
| 1348 |
self.ddldic.remove_definition('description') |
| 1349 |
self.assertTrue('description' not in self.ddldic) |
| 1350 |
self.assertTrue('description_example' not in self.ddldic) |
| 1351 |
|
| 1352 |
def testWriteDic(self): |
| 1353 |
"""Test that we can write a dictionary after adding a category""" |
| 1354 |
self.ddldic.add_definition('_junkety._junkjunk_','description') |
| 1355 |
self.ddldic.set_grammar('2.0') |
| 1356 |
final_str = str(self.ddldic) |
| 1357 |
cwd = os.getcwd() |
| 1358 |
ffurl = os.path.join(cwd,"tests/test_dic_write.cif") |
| 1359 |
ff = open(ffurl,"w") |
| 1360 |
ff.write(final_str) |
| 1361 |
ff.close() |
| 1362 |
incif = CifFile.CifDic("file:"+ffurl,grammar='2.0',do_minimum=True) |
| 1363 |
self.assertTrue(incif.has_key('_description.junkjunk')) |
| 1364 |
|
| 1365 |
def testSemanticChildren(self): |
| 1366 |
"""Test that we can obtain the semantic children of a category""" |
| 1367 |
children = self.ddldic.ddlm_immediate_children('enumeration_set') |
| 1368 |
self.assertTrue('_enumeration_set.state' in children) |
| 1369 |
children = self.ddldic.ddlm_immediate_children('enumeration') |
| 1370 |
self.assertTrue('enumeration_set' in children) |
| 1371 |
|
| 1372 |
def testDanglers(self): |
| 1373 |
"""Test that we correctly locate missing categories""" |
| 1374 |
self.ddldic['_description.text'].overwrite = True |
| 1375 |
self.ddldic['_description.text']['_name.category_id'] = 'NNN' |
| 1376 |
p = self.ddldic.ddlm_danglers() |
| 1377 |
self.assertTrue('_description.text' in p) |
| 1378 |
self.assertTrue('ddl_dic' not in p) |
| 1379 |
self.assertTrue('attributes' not in p) |
| 1380 |
|
| 1381 |
def testAllChildren(self): |
| 1382 |
"""Test that we can pick up all children""" |
| 1383 |
children = self.ddldic.ddlm_all_children('description') |
| 1384 |
self.assertTrue('_description_example.detail' in children) |
| 1385 |
|
| 1386 |
def testDanglerChildren(self): |
| 1387 |
"""Test that danglers are found when outputting""" |
| 1388 |
self.ddldic.add_definition('_junkety._junkjunk','external_cat',allow_dangler=True) |
| 1389 |
self.ddldic.add_category('some_other_cat','atom_site',allow_dangler=True) |
| 1390 |
self.ddldic.add_definition('_xxx.more_junk','some_other_cat') |
| 1391 |
names = self.ddldic.get_full_child_list() |
| 1392 |
self.assertTrue('some_other_cat' in names) |
| 1393 |
self.assertTrue('_external_cat.junkjunk' in names) |
| 1394 |
self.assertTrue('_some_other_cat.more_junk' in names) |
| 1395 |
|
| 1396 |
def testFunnyLayout(self): |
| 1397 |
"""Test that having some of the data block at the end is OK""" |
| 1398 |
good_read = CifFile.CifDic("tests/ddl_rearranged.dic",grammar="2.0",scoping="dictionary",do_minimum=True) |
| 1399 |
|
| 1400 |
|
| 1401 |
class DDLmValueTestCase(unittest.TestCase): |
| 1402 |
def setUp(self): |
| 1403 |
filedata = """ |
| 1404 |
data_testblock |
| 1405 |
_float.value 4.2 |
| 1406 |
_hex.value 0xA2 |
| 1407 |
_list1.value [1.2, 2.3, 4.5] |
| 1408 |
_list2.value [['i',4.2],['j',1.5],['lmnop',-4.5]] |
| 1409 |
_matrix.value [[1,2,3],[4,5,6],[7,8,9]] |
| 1410 |
""" |
| 1411 |
p = open('tests/ddlm_testdata','w') |
| 1412 |
p.write(filedata) |
| 1413 |
p.close() |
| 1414 |
self.testblock = CifFile.CifFile('tests/ddlm_testdata',grammar="STAR2")['testblock'] |
| 1415 |
|
| 1416 |
def tearDown(self): |
| 1417 |
os.remove("tests/ddlm_testdata") |
| 1418 |
|
| 1419 |
def testTypeInterpretation(self): |
| 1420 |
"""Test that we decode DDLm type.contents correctly""" |
| 1421 |
import CifFile.TypeContentsParser as t |
| 1422 |
p = t.TypeParser(t.TypeParserScanner('List(Real,Real,Real)')) |
| 1423 |
q = getattr(p,"input")() |
| 1424 |
print(repr(q)) |
| 1425 |
self.assertTrue(q == ['Real','Real','Real']) |
| 1426 |
p = t.TypeParser(t.TypeParserScanner('List(Real,List(Integer,Real),Real)')) |
| 1427 |
q = getattr(p,"input")() |
| 1428 |
print(repr(q)) |
| 1429 |
self.assertTrue(q == ['Real',['Integer','Real'],'Real']) |
| 1430 |
|
| 1431 |
def testSingleConversion(self): |
| 1432 |
namedef = CifFile.CifBlock() |
| 1433 |
namedef['_type.container'] = 'Single' |
| 1434 |
namedef['_type.contents'] = 'Real' |
| 1435 |
result = CifFile.convert_type(namedef)(self.testblock['_float.value']) |
| 1436 |
self.assertTrue(result == 4.2) |
| 1437 |
|
| 1438 |
def testListConversion(self): |
| 1439 |
namedef = CifFile.CifBlock() |
| 1440 |
namedef['_type.container'] = 'List' |
| 1441 |
namedef['_type.contents'] = 'List(Text,Real)' |
| 1442 |
namedef['_type.dimension'] = '[3]' |
| 1443 |
result = CifFile.convert_type(namedef)(self.testblock['_list2.value']) |
| 1444 |
print('Result: ' + repr(result)) |
| 1445 |
self.assertTrue(result == [['i',4.2],['j',1.5],['lmnop',-4.5]]) |
| 1446 |
|
| 1447 |
def testSimpleListConversion(self): |
| 1448 |
namedef = CifFile.CifBlock() |
| 1449 |
namedef['_type.container'] = 'List' |
| 1450 |
namedef['_type.contents'] = 'Real' |
| 1451 |
namedef['_type.dimension'] = '[3]' |
| 1452 |
result = CifFile.convert_type(namedef)(self.testblock['_list1.value']) |
| 1453 |
self.assertEqual(result, [1.2, 2.3, 4.5]) |
| 1454 |
|
| 1455 |
def testMatrixConversion(self): |
| 1456 |
namedef = CifFile.CifBlock() |
| 1457 |
namedef['_type.container'] = 'Matrix' |
| 1458 |
namedef['_type.contents'] = 'Integer' |
| 1459 |
result = CifFile.convert_type(namedef)(self.testblock['_matrix.value']) |
| 1460 |
self.assertTrue(result[1][2] == 6) |
| 1461 |
|
| 1462 |
def testValuesReturned(self): |
| 1463 |
"""Test that values are returned transparently converted when a dictionary is supplied""" |
| 1464 |
pass |
| 1465 |
|
| 1466 |
|
| 1467 |
|
| 1468 |
|
| 1469 |
|
| 1470 |
|
| 1471 |
|
| 1472 |
|
| 1473 |
class DDL1TestCase(unittest.TestCase): |
| 1474 |
|
| 1475 |
def setUp(self): |
| 1476 |
self.ddl1dic = CifFile.CifDic("tests/dictionaries/cif_core.dic") |
| 1477 |
|
| 1478 |
def testReport(self): |
| 1479 |
CifFile.validate_report(CifFile.Validate("tests/C13H2203_with_errors.cif",dic=self.ddl1dic)) |
| 1480 |
|
| 1481 |
class DDLmDicTestCase(unittest.TestCase): |
| 1482 |
"""Test validation of DDLm dictionaries""" |
| 1483 |
def setUp(self): |
| 1484 |
testdic_string = r"""#\#CIF_2.0 |
| 1485 |
#\#CIF_2.0 |
| 1486 |
############################################################################## |
| 1487 |
# # |
| 1488 |
# DDLm REFERENCE DICTIONARY # |
| 1489 |
# # |
| 1490 |
############################################################################## |
| 1491 |
data_DDL_DIC |
| 1492 |
|
| 1493 |
_dictionary.title DDL_DIC |
| 1494 |
_dictionary.class Reference |
| 1495 |
_dictionary.version 3.11.08 |
| 1496 |
_dictionary.date 2015-01-28 |
| 1497 |
_dictionary.uri www.iucr.org/cif/dic/ddl.dic |
| 1498 |
_dictionary.ddl_conformance 3.11.08 |
| 1499 |
_dictionary.namespace DdlDic |
| 1500 |
_description.text |
| 1501 |
; |
| 1502 |
This dictionary contains the definitions of attributes that |
| 1503 |
make up the DDLm dictionary definition language. It provides |
| 1504 |
the meta meta data for all CIF dictionaries. |
| 1505 |
; |
| 1506 |
|
| 1507 |
save_ATTRIBUTES |
| 1508 |
|
| 1509 |
_definition.id ATTRIBUTES |
| 1510 |
_definition.scope Category |
| 1511 |
_definition.class Head |
| 1512 |
_definition.update 2011-07-27 |
| 1513 |
_description.text |
| 1514 |
; |
| 1515 |
This category is parent of all other categories in the DDLm |
| 1516 |
dictionary. |
| 1517 |
; |
| 1518 |
_name.object_id ATTRIBUTES |
| 1519 |
|
| 1520 |
save_ |
| 1521 |
|
| 1522 |
#============================================================================ |
| 1523 |
|
| 1524 |
save_ALIAS |
| 1525 |
|
| 1526 |
_definition.id ALIAS |
| 1527 |
_definition.scope Category |
| 1528 |
_definition.class Loop |
| 1529 |
_definition.update 2013-09-08 |
| 1530 |
_description.text |
| 1531 |
; |
| 1532 |
The attributes used to specify the aliased names of definitions. |
| 1533 |
; |
| 1534 |
_name.category_id ATTRIBUTES |
| 1535 |
_name.object_id ALIAS |
| 1536 |
_category.key_id '_alias.definition_id' |
| 1537 |
loop_ |
| 1538 |
_category_key.name |
| 1539 |
'_alias.definition_id' |
| 1540 |
|
| 1541 |
save_ |
| 1542 |
|
| 1543 |
|
| 1544 |
save_alias.definition_id |
| 1545 |
|
| 1546 |
_definition.id '_alias.definition_id' |
| 1547 |
_definition.class Attribute |
| 1548 |
_definition.update 2006-11-16 |
| 1549 |
_description.text |
| 1550 |
; |
| 1551 |
Identifier tag of an aliased definition. |
| 1552 |
; |
| 1553 |
_name.category_id alias |
| 1554 |
_name.object_id definition_id |
| 1555 |
_type.purpose Key |
| 1556 |
_type.source Assigned |
| 1557 |
_type.container Single |
| 1558 |
_type.contents Tag |
| 1559 |
|
| 1560 |
save_ |
| 1561 |
|
| 1562 |
save_definition.scope |
| 1563 |
|
| 1564 |
_definition.id '_definition.scope' |
| 1565 |
_definition.class Attribute |
| 1566 |
_definition.update 2006-11-16 |
| 1567 |
_description.text |
| 1568 |
; |
| 1569 |
The extent to which a definition affects other definitions. |
| 1570 |
; |
| 1571 |
_name.category_id definition |
| 1572 |
_name.object_id scope |
| 1573 |
_type.purpose State |
| 1574 |
_type.source Assigned |
| 1575 |
_type.container Single |
| 1576 |
_type.contents Code |
| 1577 |
loop_ |
| 1578 |
_enumeration_set.state |
| 1579 |
_enumeration_set.detail |
| 1580 |
_description.common |
| 1581 |
Dictionary 'applies to all defined items in the dictionary' 'whoops' |
| 1582 |
Category 'applies to all defined items in the category' 'not' |
| 1583 |
Item 'applies to a single item definition' 'allowed' |
| 1584 |
_enumeration.default Item |
| 1585 |
|
| 1586 |
save_ |
| 1587 |
|
| 1588 |
|
| 1589 |
""" |
| 1590 |
f = open('tests/ddlm_valid_test.cif2','w') |
| 1591 |
f.write(testdic_string) |
| 1592 |
f.close() |
| 1593 |
self.testcif = CifFile.CifFile('tests/ddlm_valid_test.cif2',grammar='auto') |
| 1594 |
self.refdic = CifFile.CifDic('tests/dictionaries/ddl.dic',grammar='auto') |
| 1595 |
|
| 1596 |
def tearDown(self): |
| 1597 |
pass |
| 1598 |
|
| 1599 |
|
| 1600 |
def testMandatory(self): |
| 1601 |
"""Test that missing mandatory items are found""" |
| 1602 |
del self.testcif['alias.definition_id']['_name.category_id'] |
| 1603 |
result = self.refdic.run_block_validation(self.testcif['alias.definition_id']) |
| 1604 |
self.assertTrue(dict(result['whole_block'])['check_mandatory_items']['result']==False) |
| 1605 |
|
| 1606 |
def testProhibited(self): |
| 1607 |
"""Test that prohibited items are found""" |
| 1608 |
self.testcif['alias']['_enumeration_set.state'] = [1,2,3,4] |
| 1609 |
result = self.refdic.run_block_validation(self.testcif['alias']) |
| 1610 |
self.assertTrue(dict(result['whole_block'])['check_prohibited_items']['result']==False) |
| 1611 |
|
| 1612 |
def testUnlooped(self): |
| 1613 |
"""Test that unloopable data items are found""" |
| 1614 |
result = self.refdic.run_loop_validation(self.testcif['definition.scope'].loops[1]) |
| 1615 |
self.assertTrue(dict(result['_enumeration_set.state'])['validate_looping_ddlm']['result']==False) |
| 1616 |
|
| 1617 |
def testWrongLoop(self): |
| 1618 |
"""Test that non-co-loopable data items are found""" |
| 1619 |
del self.testcif['definition.scope']['_description.common'] |
| 1620 |
self.testcif['definition.scope']['_description_example.case'] = [1,2,3] |
| 1621 |
self.testcif['definition.scope'].CreateLoop(['_enumeration_set.state', |
| 1622 |
'_enumeration_set.detail', |
| 1623 |
'_description_example.case']) |
| 1624 |
loop_no = self.testcif['definition.scope'].FindLoop('_enumeration_set.state') |
| 1625 |
result = self.refdic.run_loop_validation(self.testcif['definition.scope'].loops[loop_no]) |
| 1626 |
self.assertTrue(dict(result['_enumeration_set.state'])['validate_loop_membership']['result']==False) |
| 1627 |
|
| 1628 |
def testUnKeyed(self): |
| 1629 |
"""Test that a missing key is found""" |
| 1630 |
del self.testcif['definition.scope']['_description.common'] |
| 1631 |
del self.testcif['definition.scope']['_enumeration_set.state'] |
| 1632 |
result = self.refdic.run_loop_validation(self.testcif['definition.scope'].loops[1]) |
| 1633 |
self.assertTrue(dict(result['_enumeration_set.detail'])['validate_loop_key_ddlm']['result']==False) |
| 1634 |
|
| 1635 |
def testNotMissingKey(self): |
| 1636 |
"""Test that a key that should be present is detected""" |
| 1637 |
result = self.refdic.run_loop_validation(self.testcif['definition.scope'].loops[1]) |
| 1638 |
print(repr(result)) |
| 1639 |
self.assertTrue(dict(result['_enumeration_set.state'])['validate_loop_key_ddlm']['result']==True) |
| 1640 |
|
| 1641 |
class DicEvalTestCase(unittest.TestCase): |
| 1642 |
def setUp(self): |
| 1643 |
testdic = CifFile.CifDic("tests/dictionaries/cif_core.dic",grammar="auto") |
| 1644 |
c_old = CifFile.CifFile("tests/drel/nick_old.cif",grammar="2.0") |
| 1645 |
c_new = CifFile.CifFile("tests/drel/nick_new.cif",grammar="2.0") |
| 1646 |
self.fb = c_new['saly2'] |
| 1647 |
self.fb.assign_dictionary(testdic) |
| 1648 |
self.fb_old = c_old['saly2'] |
| 1649 |
self.fb_old.assign_dictionary(testdic) |
| 1650 |
|
| 1651 |
def check_value(self,dataname,scalar=True): |
| 1652 |
"""Generic check of value""" |
| 1653 |
target = self.fb[dataname] |
| 1654 |
del self.fb[dataname] |
| 1655 |
result = self.fb[dataname] |
| 1656 |
print("Result: {!r} Target: {!r}".format(result,target)) |
| 1657 |
if scalar: |
| 1658 |
self.assertTrue(abs(float(target)-float(result))<0.01) |
| 1659 |
else: |
| 1660 |
self.assertEqual(target,result,"Target = %s, Result = %s" % (repr(target),repr(result))) |
| 1661 |
|
| 1662 |
def testCellVolume(self): |
| 1663 |
self.check_value('_cell.volume') |
| 1664 |
|
| 1665 |
@unittest.expectedFailure |
| 1666 |
def testNoInCell(self,scalar=False): |
| 1667 |
self.check_value('_atom_type.number_in_cell',scalar=False) |
| 1668 |
|
| 1669 |
def testDensity(self): |
| 1670 |
self.check_value('_exptl_crystal.density_diffrn') |
| 1671 |
|
| 1672 |
@unittest.expectedFailure |
| 1673 |
def testReflnF(self): |
| 1674 |
self.check_value('_refln.F_calc',scalar=False) |
| 1675 |
|
| 1676 |
def testCalcOldAlias(self): |
| 1677 |
"""Test that a calculation is performed for an old dataname""" |
| 1678 |
target = self.fb['_cell.volume'] |
| 1679 |
print("CalcOldAlias target is {!r}".format(target)) |
| 1680 |
del self.fb['_cell.volume'] |
| 1681 |
self.assertTrue(abs(self.fb['_cell_volume']-float(target))<0.01) |
| 1682 |
|
| 1683 |
def testFullCalcAlias(self): |
| 1684 |
"""Test that a calculation is performed if dependent datanames |
| 1685 |
have aliased values""" |
| 1686 |
del self.fb_old['_refln.F_calc'] |
| 1687 |
result = self.fb_old['_refln.F_calc'] |
| 1688 |
|
| 1689 |
def testEigenSystem(self): |
| 1690 |
"""Test that question marks are seen as missing values""" |
| 1691 |
self.fb.provide_value = True |
| 1692 |
result = self.fb['_model_site.adp_eigen_system'] |
| 1693 |
print('adp eigensystem is: ' + repr(result)) |
| 1694 |
|
| 1695 |
def testCategoryMethod(self): |
| 1696 |
"""Test that a category method calculates and updates""" |
| 1697 |
|
| 1698 |
del self.fb['_model_site.adp_eigen_system'] |
| 1699 |
del self.fb["_model_site.label"] |
| 1700 |
del self.fb["_model_site.symop"] |
| 1701 |
self.fb.provide_value = True |
| 1702 |
result = self.fb['model_site'] |
| 1703 |
self.fb.provide_value = False |
| 1704 |
print('**Updated block:') |
| 1705 |
print(str(self.fb)) |
| 1706 |
self.assertTrue(self.fb.has_key('_model_site.Cartn_xyz')) |
| 1707 |
self.assertTrue(self.fb.has_key('_model_site.mole_index')) |
| 1708 |
|
| 1709 |
def testEmptyKey(self): |
| 1710 |
"""Test that empty keys are not stored""" |
| 1711 |
del self.fb['_atom_type_scat.symbol'] |
| 1712 |
del self.fb['_atom_type_scat.dispersion_real'] |
| 1713 |
del self.fb['_atom_type_scat.dispersion_imag'] |
| 1714 |
del self.fb['_atom_type_scat.source'] |
| 1715 |
p = self.fb.GetKeyedSemanticPacket('O','atom_type') |
| 1716 |
self.assertTrue(not hasattr(p,'_atom_type_scat.symbol')) |
| 1717 |
|
| 1718 |
|
| 1719 |
class DicStructureTestCase(unittest.TestCase): |
| 1720 |
"""Tests use of dictionary semantic information for item lookup""" |
| 1721 |
def setUp(self): |
| 1722 |
self.testdic = CifFile.CifDic("tests/dictionaries/cif_core.dic",grammar="auto") |
| 1723 |
cc = CifFile.CifFile("tests/drel/nick.cif",grammar="STAR2") |
| 1724 |
self.fb = cc["saly2"] |
| 1725 |
self.fb.assign_dictionary(self.testdic) |
| 1726 |
|
| 1727 |
def testOldAlias(self): |
| 1728 |
"""Test finding an older form of a new dataname""" |
| 1729 |
self.assertTrue(self.fb['_symmetry.space_group_name_H_M']=='P_1_21/a_1') |
| 1730 |
|
| 1731 |
def testNewAlias(self): |
| 1732 |
"""Test finding a newer form of an old dataname""" |
| 1733 |
self.assertTrue(self.fb['_symmetry_space_group_name_Hall']=='-p_2yab') |
| 1734 |
|
| 1735 |
def testCatObj(self): |
| 1736 |
"""Test that we can obtain a name by category/object specification""" |
| 1737 |
target = self.testdic.get_name_by_cat_obj('atom_type','Cromer_Mann_coeffs') |
| 1738 |
self.assertEqual(target,'_atom_type_scat.Cromer_Mann_coeffs') |
| 1739 |
target = self.testdic.get_name_by_cat_obj('cell','volume') |
| 1740 |
self.assertEqual(target,'_cell.volume') |
| 1741 |
|
| 1742 |
def testCatObj2(self): |
| 1743 |
"""Test that cat.obj with obj in the parent is found""" |
| 1744 |
target = self.testdic.get_name_by_cat_obj('atom_site_aniso','ADP_type') |
| 1745 |
assert target == '_atom_site.ADP_type' |
| 1746 |
|
| 1747 |
def testCatKey(self): |
| 1748 |
"""Test that we get a complete list of keys for child categories""" |
| 1749 |
target = self.testdic.cat_key_table |
| 1750 |
self.assertEqual(target['atom_site'],[['_atom_site.label'],['_atom_site_aniso.label']]) |
| 1751 |
|
| 1752 |
def testEquivKey(self): |
| 1753 |
"""Test that we can identify equivalent key datanames""" |
| 1754 |
target = self.testdic.key_equivs |
| 1755 |
self.assertEqual(target['_atom_site_aniso.label'],['_atom_site.label']) |
| 1756 |
|
| 1757 |
def testChildPacket(self): |
| 1758 |
"""Test that a case-insensitive child packet is included in attributes of parent category""" |
| 1759 |
target = self.fb.GetKeyedSemanticPacket("o2",'atom_site') |
| 1760 |
self.assertTrue(hasattr(target,'_atom_site_aniso.u_23')) |
| 1761 |
self.assertEqual(getattr(target,'_atom_site_aniso.U_33'),'.040(3)') |
| 1762 |
|
| 1763 |
@unittest.skip("Functionality not yet implemented") |
| 1764 |
def testChildPacketMultiKey(self): |
| 1765 |
"""Test that a case-insensitive child packet is included in attributes of parent category |
| 1766 |
using the compound key routine""" |
| 1767 |
target = self.fb.GetMultiKeyedSemanticPacket({'_atom_site.label':("o2",True)},'atom_site') |
| 1768 |
self.assertEqual(getattr(target,'_atom_site_aniso.U_33'),'.040(3)') |
| 1769 |
self.assertTrue(hasattr(target,'_atom_site_aniso.u_23')) |
| 1770 |
|
| 1771 |
def testPacketCalcs(self): |
| 1772 |
"""Test that a star packet can calculate missing values""" |
| 1773 |
target = self.fb.GetKeyedSemanticPacket("O",'atom_type') |
| 1774 |
rad = getattr(target,'_atom_type.radius_bond') |
| 1775 |
self.assertEqual(rad,0.74) |
| 1776 |
|
| 1777 |
def testEnumDefault(self): |
| 1778 |
"""Test that we can obtain enumerated values""" |
| 1779 |
target = self.fb['_atom_type.radius_bond'] |
| 1780 |
self.assertTrue(0.77 in target) |
| 1781 |
|
| 1782 |
def testCalcEnumDefault(self): |
| 1783 |
"""Test that we can calculate defaults""" |
| 1784 |
target = self.fb['_atom_sites_cartn_transform.mat_33'] |
| 1785 |
self.fb.provide_value = True |
| 1786 |
assert target == self.fb['_cell.length_c'] |
| 1787 |
self.fb.provide_value = False |
| 1788 |
|
| 1789 |
def testCatObjKey(self): |
| 1790 |
"""Test that keys are correctly handled by the cat/obj table""" |
| 1791 |
self.assertEqual(self.testdic.get_name_by_cat_obj('atom_site','label'),"_atom_site.label") |
| 1792 |
|
| 1793 |
def testRepeatedName(self): |
| 1794 |
"""Test that a repeated object_id is handled correctly""" |
| 1795 |
self.assertEqual(self.testdic.cat_obj_lookup_table[('atom_site','type_symbol')], |
| 1796 |
['_atom_site.type_symbol','_atom_site_aniso.type_symbol']) |
| 1797 |
|
| 1798 |
def testPrintOut(self): |
| 1799 |
"""Test that a block with dictionary attached can print(out string values""" |
| 1800 |
print(self.fb) |
| 1801 |
|
| 1802 |
def pullbacksetup(self): |
| 1803 |
"""Initial steps when setting up a pullback""" |
| 1804 |
dic_info = CifFile.CifDic("tests/full_demo_0.0.6.dic",grammar="auto") |
| 1805 |
start_data = CifFile.CifFile("tests/multi-image-test.cif",grammar="auto") |
| 1806 |
start_data = start_data['Merged_scans'] |
| 1807 |
start_data.assign_dictionary(dic_info) |
| 1808 |
return start_data |
| 1809 |
|
| 1810 |
def unpullbacksetup(self): |
| 1811 |
"""Initial values when setting up a pullback""" |
| 1812 |
dic_info = CifFile.CifDic("tests/full_demo_0.0.6.dic",grammar="auto") |
| 1813 |
start_data = CifFile.CifFile("tests/multi-image-test.cif.pulled_back",grammar="auto") |
| 1814 |
start_data = start_data['Merged_scans'] |
| 1815 |
start_data.assign_dictionary(dic_info) |
| 1816 |
return start_data |
| 1817 |
|
| 1818 |
def testPullBack(self): |
| 1819 |
"""Test construction of a category that is pulled back from other categories""" |
| 1820 |
start_data = self.pullbacksetup() |
| 1821 |
q = start_data['_diffrn_detector_monolithic_element.key'] |
| 1822 |
p = start_data['_diffrn_detector_monolithic_element.detector_id'] |
| 1823 |
print('p,q = ' + repr(p) + '\n' + repr(q)) |
| 1824 |
self.assertTrue(q==[['element1','adscq210-sn457']]) |
| 1825 |
self.assertTrue(p==['ADSCQ210-SN457']) |
| 1826 |
|
| 1827 |
def testMultiPullback(self): |
| 1828 |
"""Test that pullbacks with multiple matches work properly""" |
| 1829 |
start_data = self.pullbacksetup() |
| 1830 |
q = start_data['_full_frame.id'] |
| 1831 |
r = start_data['_full_frame.detector_element_id'] |
| 1832 |
print('Frames from monolithic detector:' + repr(q)) |
| 1833 |
self.assertTrue(['scan1','frame1'] in q) |
| 1834 |
self.assertTrue(['scan1','frame3'] in q) |
| 1835 |
|
| 1836 |
def testIntegerFilter(self): |
| 1837 |
"""Test construction of a block that is filtered from another category""" |
| 1838 |
start_data = self.pullbacksetup() |
| 1839 |
q = start_data['_diffrn_detector_monolithic.id'] |
| 1840 |
self.assertTrue(q == ['ADSCQ210-SN457']) |
| 1841 |
|
| 1842 |
def testTextFilter(self): |
| 1843 |
"""Test construction of a block that is filtered using a text string""" |
| 1844 |
start_data = self.pullbacksetup() |
| 1845 |
q = start_data['_detector_axis.id'] |
| 1846 |
print('q is ' + repr(q)) |
| 1847 |
self.assertTrue(['detector_y','detector'] in q) |
| 1848 |
self.assertTrue(['goniometer_phi','goniometer'] not in q) |
| 1849 |
|
| 1850 |
def testPopulateFromPullback(self): |
| 1851 |
"""Test population of a category with id items from a pulled-back category""" |
| 1852 |
start_data = self.unpullbacksetup() |
| 1853 |
q = start_data['_diffrn_data_frame.key'] |
| 1854 |
self.assertTrue(['SCAN1','FRAME1'] in q) |
| 1855 |
self.assertTrue(['SCAN1','Frame3'] in q) |
| 1856 |
|
| 1857 |
def testPopulateFromFilter(self): |
| 1858 |
"""Test population of a category that has been filtered""" |
| 1859 |
start_data = self.unpullbacksetup() |
| 1860 |
q = start_data['_diffrn_detector.id'] |
| 1861 |
r = start_data['_diffrn_detector.number_of_elements'] |
| 1862 |
print('q,r = ' + repr(q) + ' , ' + repr(r)) |
| 1863 |
self.assertTrue(q==['ADSCQ210-SN457']) |
| 1864 |
self.assertTrue(r == [1]) |
| 1865 |
|
| 1866 |
def testPopulateFromMultiFilters(self): |
| 1867 |
"""Test population of a category that is filtered into multiple |
| 1868 |
streams""" |
| 1869 |
start_data = self.unpullbacksetup() |
| 1870 |
q = start_data['_axis.key'] |
| 1871 |
print('q ends up as:' + repr(q)) |
| 1872 |
self.assertTrue(['detector_x','detector'] in q) |
| 1873 |
self.assertTrue(['GONIOMETER_PHI','goniometer'] in q) |
| 1874 |
|
| 1875 |
def testPopulateNonIDFromFilter(self): |
| 1876 |
"""Test that duplicate datanames are populated""" |
| 1877 |
start_data = self.unpullbacksetup() |
| 1878 |
q = start_data['_diffrn_data_frame.binary_id'] |
| 1879 |
self.assertTrue('3' in q) |
| 1880 |
|
| 1881 |
class BlockOutputOrderTestCase(unittest.TestCase): |
| 1882 |
def tearDown(self): |
| 1883 |
try: |
| 1884 |
os.remove("tests/order_test.cif") |
| 1885 |
os.remove("tests/round_trip_test.cif") |
| 1886 |
except: |
| 1887 |
pass |
| 1888 |
|
| 1889 |
def testOutputOrder(self): |
| 1890 |
outstrg = r"""#\#CIF_2.0 |
| 1891 |
data_testa |
| 1892 |
_item1 1 |
| 1893 |
data_testb |
| 1894 |
_item2 2 |
| 1895 |
data_testc |
| 1896 |
_item3 3 |
| 1897 |
data_testd |
| 1898 |
_item4 4 |
| 1899 |
""" |
| 1900 |
f = open("tests/order_test.cif","w") |
| 1901 |
f.write(outstrg) |
| 1902 |
f.close() |
| 1903 |
q = CifFile.CifFile("tests/order_test.cif",grammar="auto") |
| 1904 |
print(repr(q.block_input_order)) |
| 1905 |
self.assertTrue(q.block_input_order[1] == "testb") |
| 1906 |
f = open("tests/round_trip_test.cif","w") |
| 1907 |
f.write(str(q)) |
| 1908 |
|
| 1909 |
if __name__=='__main__': |
| 1910 |
|
| 1911 |
|
| 1912 |
|
| 1913 |
|
| 1914 |
|
| 1915 |
|
| 1916 |
|
| 1917 |
|
| 1918 |
|
| 1919 |
|
| 1920 |
|
| 1921 |
|
| 1922 |
|
| 1923 |
|
| 1924 |
|
| 1925 |
|
| 1926 |
|
| 1927 |
|
| 1928 |
unittest.main() |