-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathTestPyCIFRW.py
1927 lines (1695 loc) · 77.1 KB
/
TestPyCIFRW.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Testing of the PyCif module using the PyUnit framework
#
# To maximize python3/python2 compatibility
# Note that all tests should pass with and without
# unicode literals.
from __future__ import print_function
#from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
import sys,os
#sys.path[0] = '.'
import unittest
import CifFile
from CifFile import StarFile
from CifFile.StarFile import StarDict, StarList, StarLengthError
import re
try:
from StringIO import StringIO
except:
from io import StringIO
# Test general string and number manipulation functions
class BasicUtilitiesTestCase(unittest.TestCase):
def testPlainLineFolding(self):
"""Test that we can fold a line correctly"""
test_string = "1234567890123456789012"
outstring = CifFile.apply_line_folding(test_string,5,10)
out_lines = outstring.split('\n')
#print(outstring)
self.assertTrue(out_lines[0]=="\\")
self.assertTrue(len(out_lines[1])==10)
def testPreWrappedFolding(self):
"""Test that pre-wrapped lines are untouched"""
test_string = "123456789\n012345678\n9012"
outstring = CifFile.apply_line_folding(test_string,5,10)
self.assertTrue(outstring == test_string)
def testManyLineEndings(self):
"""Test that empty lines are handled OK"""
test_string = "123456789\n\n012345678\n\n9012\n\n"
outstring = CifFile.apply_line_folding(test_string,5,10)
self.assertTrue(outstring == test_string)
def testOptionalBreak(self):
"""Test that internal whitespace is used to break"""
test_string = "123456 7890123 45678\n90 12\n\n"
outstring = CifFile.apply_line_folding(test_string,5,10)
#print("\n;" + outstring + "\n;")
out_lines = outstring.split('\n')
self.assertTrue(len(out_lines[1]) == 7)
def testCorrectEnding(self):
"""Make sure that no line feeds are added/removed"""
test_string = "123456 7890123 45678\n90 12\n\n"
outstring = CifFile.apply_line_folding(test_string,5,10)
self.assertTrue(outstring[-4:] == "12\n\n")
def testFoldingRemoval(self):
"""Test that we round-trip correctly"""
test_string = "123456 7890123 45678\n90 12\n\n"
outstring = CifFile.apply_line_folding(test_string,5,10)
old_string = CifFile.remove_line_folding(outstring)
#print("Test:" + repr(test_string))
#print("Fold:" + repr(outstring))
#print("UnFo:" + repr(old_string))
self.assertTrue(old_string == test_string)
def testTrickyFoldingRemoval(self):
"""Try to produce a tough string for unfolding"""
test_string = "\n1234567890\\\n r t s 345 19\n\nlife don't talk to me about life"
outstring = CifFile.apply_line_folding(test_string,5,10)
old_string = CifFile.remove_line_folding(outstring)
#print("Test:" + repr(test_string))
#print("Fold:" + repr(outstring))
#print("UnFo:" + repr(old_string))
self.assertTrue(old_string == test_string)
def testTrailingBackslash(self):
"""Make sure that a trailing backslash is not removed"""
test_string = "\n123\\\n 456\\n\n"
outstring = CifFile.apply_line_folding(test_string,5,10)
old_string = CifFile.remove_line_folding(outstring)
#print("Test:" + repr(test_string))
#print("Fold:" + repr(outstring))
#print("UnFo:" + repr(old_string))
self.assertTrue(old_string == test_string)
def testFinalBackslash(self):
"""Make sure that a single final backslash is removed when unfolding"""
test_string = "\n1234567890\\\n r t s 345 19\n\nlife don't talk to me about life"
folded_string = CifFile.apply_line_folding(test_string,5,10)
folded_string = folded_string + r"\ "
old_string = CifFile.remove_line_folding(folded_string)
self.assertTrue(old_string == test_string)
def testAddIndent(self):
"""Test insertion of a line prefix"""
test_string = "\n12345\n678910\n\n"
outstring = CifFile.apply_line_prefix(test_string,"abc>")
print("Converted %s to %s " %(test_string,outstring))
self.assertTrue(outstring == "abc>\\\nabc>\nabc>12345\nabc>678910\nabc>\nabc>")
def testRemoveIndent(self):
"""Test removal of a line prefix"""
test_string = "abc>\\\nabc>12345\nabc>678910\nabc>\nabc>"
outstring = CifFile.remove_line_prefix(test_string)
print("Removed indent: " + repr(outstring))
self.assertTrue(outstring == "12345\n678910\n\n")
def testReverseIndent(self):
"""Test reversible indentation of line"""
test_string = "12345\n678910\n\n"
outstring = CifFile.apply_line_prefix(test_string,"cif><")
newtest = CifFile.remove_line_prefix(outstring)
print('Before indenting: ' + repr(test_string))
print('After indenting: ' + repr(outstring))
print('After unindent: ' + repr(newtest))
self.assertTrue(newtest == test_string)
def testPrefixAndFold(self):
"""Test reversible folding and indenting"""
test_string = "\n1234567890\\\n r t s 345 19\n\nlife don't talk to me about life"
outstring = CifFile.apply_line_folding(test_string,5,10)
indoutstring = CifFile.apply_line_prefix(outstring,"CIF>")
newoutstring = CifFile.remove_line_prefix(indoutstring)
newtest_string = CifFile.remove_line_folding(newoutstring)
print("%s -> %s -> %s -> %s -> %s" % (repr(test_string),repr(outstring),repr(indoutstring),repr(newoutstring),repr(newtest_string)))
self.assertTrue(newtest_string == test_string)
def testStringiness(self):
"""Check that we can detect string-valued items correctly"""
import numpy
self.assertEqual(CifFile.check_stringiness(['1','2','3']),True)
self.assertEqual(CifFile.check_stringiness([1,2,'3']),False)
self.assertEqual(CifFile.check_stringiness(['1',['2',['3',4,'5'],'6','7'],'8']),False)
self.assertEqual(CifFile.check_stringiness(['1',['2',['3','4','5'],'6','7'],'8']),True)
p = numpy.array([[1,2,3],[4,5,6]])
self.assertEqual(CifFile.check_stringiness(p),False)
def testStarList(self):
"""Test that starlists allow comma-based access"""
p = StarList([StarList([1,2,3]),StarList([4,5,6])])
self.assertTrue(p[1,0]==4)
# Test basic setting and reading of the CifBlock
class BlockRWTestCase(unittest.TestCase):
def setUp(self):
# we want to get a datablock ready so that the test
# case will be able to write a single item
# self.cf_old = CifFile.CifBlock(compat_mode=True)
self.cf = CifFile.CifBlock()
def tearDown(self):
# get rid of our test object
del self.cf
def testTupleNumberSet(self):
"""Test tuple setting with numbers"""
self.cf['_test_tuple'] = (11,13.5,-5.6)
self.assertTrue([float(a) for a in self.cf['_test_tuple']]== [11,13.5,-5.6])
def testStringSet(self):
"""test string setting"""
self.cf['_test_string_'] = 'A short string'
self.assertTrue(self.cf['_test_string_'] == 'A short string')
def testTooLongSet(self):
"""test setting overlong data names"""
dataname = '_a_long_long_'*7
try:
self.cf[dataname] = 1.0
except (CifFile.StarError,CifFile.CifError): pass
else: self.fail()
def testTooLongLoopSet(self):
"""test setting overlong data names in a loop"""
dataname = '_a_long_long_'*7
try:
self.cf[dataname] = (1.0,2.0,3.0)
except (CifFile.StarError,CifFile.CifError): pass
else: self.fail()
def testBadStringSet(self):
"""test setting values with bad characters"""
dataname = '_name_is_ok'
try:
self.cf[dataname] = "eca234\f\vaqkadlf"
except CifFile.StarError: pass
else: self.fail()
def testBadNameSet(self):
"""test setting names with bad characters"""
dataname = "_this_is_not ok"
try:
self.cf[dataname] = "nnn"
except CifFile.StarError: pass
else: self.fail()
def testMoreBadStrings(self):
dataname = "_name_is_ok"
val = (b"so far, ok, but now we have a " + bytearray([128])).decode('latin_1')
try:
self.cf[dataname] = val
except CifFile.StarError: pass
else: self.fail()
def testEmptyString(self):
"""An empty string is, in fact, legal"""
self.cf['_an_empty_string'] = ''
# Now test operations which require a preexisting block
#
class BlockChangeTestCase(unittest.TestCase):
def setUp(self):
self.cf = CifFile.CifBlock()
self.names = ('_item_name_1','_item_name#2','_item_%$#3')
self.values = ((1,2,3,4),('hello','good_bye','a space','# 4'),
(15.462, -99.34,10804,0.0001))
for n,v in zip(self.names, self.values):
self.cf.AddItem(n, v)
self.cf.CreateLoop(self.names)
self.cf['_non_loop_item'] = 'Non loop string item'
self.cf['_number_item'] = 15.65
self.cf['_planet'] = 'Saturn'
self.cf['_satellite'] = 'Titan'
self.cf['_rings'] = 'True'
def tearDown(self):
del self.cf
def testFromBlockSet(self):
"""Test that we can use a CifBlock to set a CifBlock"""
df = CifFile.CifFile()
df.NewBlock('testname',self.cf)
self.assertEqual(df['testname']['_planet'],'Saturn')
self.assertEqual(df['testname']['_item_name#2'],list(self.values[1]))
def testSimpleRemove(self):
"""Check item deletion outside loop"""
self.cf.RemoveCifItem('_non_loop_item')
try:
a = self.cf['_non_loop_item']
except KeyError: pass
else: self.fail()
def testLoopRemove(self):
"""Check item deletion inside loop"""
print("Before:\n")
print(self.cf.printsection())
self.cf.RemoveCifItem(self.names[1])
print("After:\n")
print(self.cf.printsection())
try:
a = self.cf[self.names[1]]
except KeyError: pass
else: self.fail()
def testFullLoopRemove(self):
"""Check removal of all loop items"""
for name in self.names: self.cf.RemoveCifItem(name)
self.assertTrue(len(self.cf.loops)==0, repr(self.cf.loops))
def testChangeLoop(self):
"""Test changing pre-existing item in loop"""
# Items should be silently replaced
self.cf["_item_name_1"] = (5,6,7,8)
#
# Test the mapping type implementation
#
def testGetOperation(self):
"""Test the get mapping call"""
self.cf.get("_item_name_1")
self.cf.get("_item_name_nonexist")
#
# Test case insensitivity
#
def testDataNameCase(self):
"""Test same name, different case causes error"""
self.assertEqual(self.cf["_Item_Name_1"],self.cf["_item_name_1"])
self.cf["_Item_NaMe_1"] = "the quick pewse fox"
self.assertEqual(self.cf["_Item_NaMe_1"],self.cf["_item_name_1"])
class SyntaxErrorTestCase(unittest.TestCase):
"""Check that files with syntax errors are found"""
def tearDown(self):
try:
os.remove("tests/syntax_check.cif")
except:
pass
def testTripleApostropheCase(self):
teststrg = "#\\#CIF_2.0\ndata_testblock\n _item_1 ''' ''' '''\n"
f = open("tests/syntax_check.cif","w")
f.write(teststrg)
f.close()
self.assertRaises(CifFile.StarError, CifFile.ReadCif,"tests/syntax_check.cif",grammar="2.0")
def testTripleQuoteCase(self):
teststrg = '#\\#CIF_2.0\ndata_testblock\n _item_1 """ """ """\n'
f = open("tests/syntax_check.cif","w")
f.write(teststrg)
f.close()
self.assertRaises(CifFile.StarError, CifFile.ReadCif,"tests/syntax_check.cif",grammar="2.0")
class LoopBlockTestCase(unittest.TestCase):
"""Check operations on loop blocks"""
def setUp(self):
self.cf = CifFile.CifBlock()
self.names = ('_Item_Name_1','_item_name#2','_item_%$#3')
self.values = ((1,2,3,4),('hello','good_bye','a space','# 4'),
(15.462, -99.34,10804,0.0001))
for n,v in zip(self.names, self.values):
self.cf.AddItem(n, v)
self.cf.CreateLoop(self.names)
self.cf['_non_loop_item'] = 'Non loop string item'
self.cf['_number_item'] = 15.65
self.cf['_planet'] = 'Saturn'
self.cf['_satellite'] = 'Titan'
self.cf['_rings'] = 'True'
# A loop with compound keys
self.cf['_ck_1'] = ['1','1','1','2','2','2','3','3','3']
self.cf['_Ck_2'] = ['r','g','b','r','g','b','r','g','b']
self.cf['_stuff'] = ['Q','W','E','R','T','Y','U','I','O']
self.cf.CreateLoop(['_ck_1','_ck_2','_stuff'])
def tearDown(self):
del self.cf
def testLoop(self):
"""Check GetLoop returns values and names in matching order"""
results = self.cf.GetLoop(self.names[2])
lowernames = [a.lower() for a in self.names]
for key in results.keys():
self.assertTrue(key.lower() in lowernames)
self.assertTrue(tuple(results[key]) == self.values[lowernames.index(key.lower())])
def testLoopCharCase(self):
"""Test that upper/lower case names in loops works correctly"""
# Note the wildly varying case for these two names
self.cf['_item_name_20'] = ['a','b','c','q']
self.cf.AddLoopName('_item_Name_1','_Item_name_20')
self.assertTrue(self.cf.FindLoop('_Item_name_1')==self.cf.FindLoop('_Item_Name_20'))
def testGetLoopCase(self):
"""Check that getloop works for any case"""
results = self.cf.GetLoop('_Item_Name_1')
self.assertEqual(results['_item_name_1'][1],2)
def testLoopOutputOrder(self):
"""Check that an item placed in a loop no longer appears in the output order"""
self.cf['_item_name_20'] = ['a','b','c','q']
self.cf.AddLoopName('_item_Name_1','_Item_name_20')
self.assertTrue('_item_name_20' not in self.cf.GetItemOrder())
def testLoopify(self):
"""Test changing unlooped data to looped data"""
self.cf.CreateLoop(["_planet","_satellite","_rings"])
newloop = self.cf.GetLoop("_rings")
self.assertFalse(newloop.has_key("_number_item"))
def testLoopifyCif(self):
"""Test changing unlooped data to looped data does
not touch already looped data for a CIF file"""
self.cf.CreateLoop(["_planet","_satellite","_rings"])
newloop = self.cf.GetLoop("_rings")
self.assertTrue(newloop.has_key('_planet'))
self.assertTrue(isinstance(self.cf["_planet"],list))
# Test iteration
#
def testIteration(self):
"""We create an iterator and iterate"""
testloop = self.cf.GetLoop("_item_name_1")
i = 0
for test_pack in testloop:
self.assertEqual(test_pack._item_name_1,self.values[0][i])
self.assertEqual(getattr(test_pack,"_item_name#2"),self.values[1][i])
i += 1
def testPacketContents(self):
"""Test that body of packet is filled in as well"""
testloop = self.cf.GetLoop("_item_name_1")
it_order = testloop.GetItemOrder()
itn_pos = it_order.index("_item_name_1")
for test_pack in testloop:
print('Test pack: ' + repr(test_pack))
self.assertEqual(test_pack._item_name_1,test_pack[itn_pos])
def testPacketAttr(self):
"""Test that packets have attributes"""
testloop = self.cf.GetLoop("_item_name_1")
self.assertEqual(testloop[1]._item_name_1,2)
def testKeyPacket(self):
"""Test that a packet can be returned by key value"""
testpack = self.cf.GetKeyedPacket("_item_name_1",2)
self.assertEqual("good_bye",getattr(testpack,"_item_name#2"))
def testCompoundKeyPacket(self):
"""Test that a compound key can also be used"""
testpack = self.cf.GetCompoundKeyedPacket({"_ck_1":('2',False),"_ck_2":('b',False)})
self.assertEqual("Y",getattr(testpack,"_stuff"))
def testPacketMerge(self):
"""Test that a packet can be merged with another packet"""
bigcf = CifFile.CifFile("tests/C13H22O3.cif")
bigcf = bigcf["II"]
testpack = bigcf.GetKeyedPacket("_atom_site_label","C4A")
newpack = bigcf.GetKeyedPacket("_atom_site_aniso_label","C4A")
testpack.merge_packet(newpack)
self.assertEqual(getattr(testpack,'_atom_site_aniso_U_22'),'0.0312(15)')
self.assertEqual(getattr(testpack,'_atom_site_fract_x'),'0.7192(3)')
def testRemovePacket(self):
"""Test that removing a packet works properly"""
print('Before packet removal')
print(str(self.cf))
testloop = self.cf.GetLoop("_item_name_1")
testloop.RemoveKeyedPacket("_item_name_1",3)
print('After packet 3 removal:')
jj = testloop.GetKeyedPacket("_item_name_1",2)
kk = testloop.GetKeyedPacket("_item_name_1",4)
self.assertEqual(getattr(jj,"_item_name#2"),"good_bye")
self.assertEqual(getattr(kk,"_item_name#2"),"# 4")
self.assertRaises(ValueError,testloop.GetKeyedPacket,"_item_name_1",3)
print('After packet removal:')
print(str(self.cf))
def testAddPacket(self):
"""Test that we can add a packet"""
import copy
testloop = self.cf.GetLoop("_item_name_1")
workingpacket = copy.copy(testloop.GetPacket(0))
workingpacket._item_name_1 = '5'
workingpacket.__setattr__("_item_name#2", 'new' )
testloop.AddPacket(workingpacket)
# note we assume that this adds on to the end, which is not
# a CIF requirement
self.assertEqual(testloop["_item_name_1"][4],'5')
self.assertEqual(testloop["_item_name#2"][4],'new')
#
# Test changing item order
#
def testChangeOrder(self):
"""We move some stuff around"""
testloop = self.cf.GetLoop("_item_name_1")
self.cf.ChangeItemOrder("_Number_Item",0)
testloop.ChangeItemOrder("_Item_Name_1",2)
self.assertEqual(testloop.GetItemOrder()[2],"_Item_Name_1".lower())
self.assertEqual(self.cf.GetItemOrder()[0],"_Number_Item".lower())
def testGetOrder(self):
"""Test that the correct order value is returned"""
self.assertEqual(self.cf.GetItemPosition("_Number_Item"),(-1,2))
def testReplaceOrder(self):
"""Test that a replaced item is at the same position it
previously held"""
testloop = self.cf.GetLoop("_item_name_1")
oldpos = testloop.GetItemPosition('_item_name#2')
testloop['_item_name#2'] = ("I'm",' a ','little','teapot')
self.assertEqual(testloop.GetItemPosition('_item_name#2'),oldpos)
#
# Test setting of block names
#
class BlockNameTestCase(unittest.TestCase):
def testBlockName(self):
"""Make sure long block names cause errors"""
df = CifFile.CifBlock()
cf = CifFile.CifFile()
try:
cf['a_very_long_block_name_which_should_be_rejected_out_of_hand123456789012345678']=df
except CifFile.StarError: pass
else: self.fail()
def testBlockOverwrite(self):
"""Upper/lower case should be seen as identical"""
df = CifFile.CifBlock()
ef = CifFile.CifBlock()
cf = CifFile.CifFile(standard=None)
df['_random_1'] = 'oldval'
ef['_random_1'] = 'newval'
print('cf.standard is ' + repr(cf.standard))
cf['_lowercaseblock'] = df
cf['_LowerCaseBlock'] = ef
assert(cf['_Lowercaseblock']['_random_1'] == 'newval')
assert(len(cf) == 1)
def testEmptyBlock(self):
"""Test that empty blocks are not the same object"""
cf = CifFile.CifFile()
cf.NewBlock('first_block')
cf.NewBlock('second_block')
cf['first_block']['_test1'] = 'abc'
cf['second_block']['_test1'] = 'def'
self.assertEqual(cf['first_block']['_test1'],'abc')
#
# Test reading cases
#
class FileWriteTestCase(unittest.TestCase):
def setUp(self):
"""Write out a file, then read it in again. Non alphabetic ordering to
check order preservation and mixed case."""
# fill up the block with stuff
items = (('_item_1','Some data'),
('_item_3','34.2332'),
('_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'),
('_item_2','Some_underline_data'),
('_item_empty',''),
('_item_quote',"'ABC"),
('_item_apost','"def'),
('_item_sws'," \n "),
('_item_bad_beg',"data_journal"),
(('_item_5','_item_7','_item_6'),
([1,2,3,4],
['a','b','c','d'],
[5,6,7,8])),
(('_string_1','_string_2'),
([';this string begins with a semicolon',
'this string is way way too long and should overflow onto the next line eventually if I keep typing for long enough',
';just_any_old_semicolon-starting-string'],
['a string with a final quote"',
'a string with a " and a safe\';',
'a string with a final \''])))
# save block items as well
s_items = (('_sitem_1','Some save data'),
('_sitem_2','Some_underline_data'),
('_sitem_3','34.2332'),
('_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'),
(('_sitem_5','_sitem_6','_sitem_7'),
([1,2,3,4],
[5,6,7,8],
['a','b','c','d'])),
(('_string_1','_string_2'),
([';this string begins with a semicolon',
'this string is way way too long and should overflow onto the next line eventually if I keep typing for long enough',
';just_any_old_semicolon-starting-string'],
['a string with a final quote"',
'a string with a " and a safe\';',
'a string with a final \''])))
self.cf = CifFile.CifBlock(items)
cif = CifFile.CifFile(scoping='dictionary',maxoutlength=80)
cif['Testblock'] = self.cf
# Add some comments
self.save_block = CifFile.CifBlock(s_items)
cif.NewBlock("test_Save_frame",self.save_block,parent='testblock')
self.cfs = cif["test_save_frame"]
outfile = open('tests/test.cif','w')
outfile.write(str(cif))
outfile.close()
self.ef = CifFile.CifFile('tests/test.cif',scoping='dictionary')
self.df = self.ef['testblock']
self.dfs = self.ef["test_save_frame"]
flfile = CifFile.ReadCif('tests/test.cif',scantype="flex",scoping='dictionary')
# test passing a stream directly
tstream = open('tests/test.cif')
CifFile.CifFile(tstream,scantype="flex")
CifFile.ReadCif(tstream,scantype="flex") #different code path
self.flf = flfile['testblock']
self.flfs = flfile["Test_save_frame"]
def tearDown(self):
try:
os.remove('tests/test.cif')
os.remove('tests/test2.cif')
except:
pass
del self.dfs
del self.df
del self.cf
del self.ef
del self.flf
del self.flfs
def testStringInOut(self):
"""Test writing short strings in and out"""
self.assertTrue(self.cf['_item_1']==self.df['_item_1'])
self.assertTrue(self.cf['_item_2']==self.df['_item_2'])
self.assertTrue(self.cfs['_sitem_1']==self.dfs['_sitem_1'])
self.assertTrue(self.cfs['_sitem_2']==self.dfs['_sitem_2'])
self.assertTrue(self.cfs['_sitem_1']==self.flfs['_sitem_1'])
self.assertTrue(self.cfs['_sitem_2']==self.flfs['_sitem_2'])
def testApostropheInOut(self):
"""Test correct behaviour for values starting with apostrophes
or quotation marks"""
self.assertTrue(self.cf['_item_quote']==self.df['_item_quote'])
self.assertTrue(self.cf['_item_apost']==self.df['_item_apost'])
self.assertTrue(self.cf['_item_quote']==self.flf['_item_quote'])
self.assertTrue(self.cf['_item_apost']==self.flf['_item_apost'])
def testNumberInOut(self):
"""Test writing number in and out"""
self.assertTrue(self.cf['_item_3']==(self.df['_item_3']))
self.assertTrue(self.cfs['_sitem_3']==(self.dfs['_sitem_3']))
self.assertTrue(self.cf['_item_3']==(self.flf['_item_3']))
self.assertTrue(self.cfs['_sitem_3']==(self.flfs['_sitem_3']))
def testLongStringInOut(self):
"""Test writing long string in and out
Note that whitespace may vary due to carriage returns,
so we remove all returns before comparing"""
import re
compstring = re.sub('\n','',self.df['_item_4'])
self.assertTrue(compstring == self.cf['_item_4'])
compstring = re.sub('\n','',self.dfs['_sitem_4'])
self.assertTrue(compstring == self.cfs['_sitem_4'])
compstring = re.sub('\n','',self.flf['_item_4'])
self.assertTrue(compstring == self.cf['_item_4'])
compstring = re.sub('\n','',self.flfs['_sitem_4'])
self.assertTrue(compstring == self.cfs['_sitem_4'])
def testEmptyStringInOut(self):
"""An empty string is in fact kosher"""
self.assertTrue(self.cf['_item_empty']=='')
self.assertTrue(self.flf['_item_empty']=='')
def testSemiWhiteSpace(self):
"""Test that white space in a semicolon string is preserved"""
self.assertTrue(self.cf['_item_sws']==self.df['_item_sws'])
self.assertTrue(self.cf['_item_sws']==self.flf['_item_sws'])
def testLoopDataInOut(self):
"""Test writing in and out loop data"""
olditems = self.cf.GetLoop('_item_5')
for key,value in olditems.items():
self.assertTrue(tuple(map(str,value))==tuple(self.df[key]))
self.assertTrue(tuple(map(str,value))==tuple(self.flf[key]))
# save frame test
olditems = self.cfs.GetLoop('_sitem_5').items()
for key,value in olditems:
self.assertTrue(tuple(map(str,value))==tuple(self.dfs[key]))
self.assertTrue(tuple(map(str,value))==tuple(self.flfs[key]))
def testLoopStringInOut(self):
"""Test writing in and out string loop data"""
olditems = self.cf.GetLoop('_string_1')
newitems = self.df.GetLoop('_string_1')
flexnewitems = self.flf.GetLoop('_string_1')
for key,value in olditems.items():
compstringa = [re.sub('\n','',a) for a in value]
compstringb = [re.sub('\n','',a) for a in self.df[key]]
compstringc = [re.sub('\n','',a) for a in self.flf[key]]
self.assertTrue(compstringa==compstringb and compstringa==compstringc)
def testGetLoopData(self):
"""Test the get method for looped data"""
newvals = self.df.get('_string_1')
self.assertTrue(len(newvals)==3)
def testCopySaveFrame(self):
"""Early implementations didn't copy the save frame properly"""
jj = CifFile.CifFile(self.ef,scoping='dictionary') #this will trigger a copy
self.assertTrue(len(jj["test_save_frame"])>0)
def testFirstBlock(self):
"""Test that first_block returns a block"""
self.ef.scoping = 'instance' #otherwise all blocks are available
jj = self.ef.first_block()
self.assertTrue(jj==self.df)
def testWrongLoop(self):
"""Test derived from error observed during dREL testing"""
teststrg = """data_test
loop_
_atom_type.symbol
_atom_type.oxidation_number
_atom_type.atomic_mass
_atom_type.number_in_cell
O ? 15.999 12
C ? 12.011 28
H ? 1.008 24
"""
q = open("tests/test2.cif","w")
q.write(teststrg)
q.close()
testcif = CifFile.CifFile("tests/test2.cif").first_block()
self.assertTrue(testcif['_atom_type.symbol']==['O','C','H'])
def testDupName(self):
"""Test that duplicate blocknames are allowed in non-standard mode"""
outstr = """data_block1 _data_1 b save_ab1 _data_2 c
save_
save_ab1 _data_3 d save_"""
b = open("tests/test2.cif","w")
b.write(outstr)
b.close()
testin = CifFile.CifFile("tests/test2.cif",standard=None)
def testPrefixProtocol(self):
"""Test that pathological strings round-trip correctly"""
cif_as_text = open('tests/test.cif','r').read()
bf = CifFile.CifFile(maxoutlength=80)
bb = CifFile.CifBlock()
bb['_data_embedded'] = cif_as_text
bf['tough_one'] = bb
out_f = open('tests/embedded.cif','w')
out_f.write(str(bf))
out_f.close()
in_emb = CifFile.CifFile('tests/embedded.cif',grammar='2.0')
self.assertEqual(in_emb['tough_one']['_data_embedded'],cif_as_text)
def testBadBeginning(self):
"""Test that strings with forbidden beginnings round-trip OK"""
self.assertTrue(self.cf['_item_bad_beg']==self.df['_item_bad_beg'])
def testStrayCharacter(self):
"""Test that CIF1 fails with non-ASCII characters"""
outstr = b"""data_block1 _normal_str 'hello sunshine'
_latin1_str abc\xB0efgh"""
b = open("tests/test3_latin1.cif","wb")
b.write(outstr)
b.close()
try:
testin = CifFile.CifFile("tests/test3_latin1.cif",grammar="1.0",permissive=False)
except CifFile.StarError:
pass
def testPermissiveRead(self):
"""Test that stray latin-1 characters are accepted in permissive mode"""
outstr = b"""data_block1 _normal_str 'hello sunshine'
_latin1_str abc\xB0efgh"""
b = open("tests/test3_latin1.cif","wb")
b.write(outstr)
b.close()
testin = CifFile.CifFile("tests/test3_latin1.cif",grammar="1.0",permissive=True)
def testItemChange(self):
"""Test that an item from in input file can be changed"""
self.flf['_item_quote']= '2.3'
self.assertTrue(self.flf['_item_quote']=='2.3')
def testEmptyDict(self):
"""Test that a dictionary is processed correctly"""
outstr = b"""#\\#CIF_2.0\ndata_block1 _a_dict {"a":2}\n"""
b = open("tests/test4_dict.cif","wb")
b.write(outstr)
b.close()
testin = CifFile.CifFile("tests/test4_dict.cif",grammar="2.0")
self.assertTrue(testin["block1"]["_a_dict"] == {"a":"2"})
class SimpleWriteTestCase(unittest.TestCase):
def setUp(self):
self.bf = CifFile.CifBlock()
self.cf = CifFile.CifFile()
self.cf['testblock'] = self.bf
self.testfile = "tests/test_3.cif"
def tearDown(self):
try:
os.remove(self.testfile)
except:
pass
def testNumpyArray(self):
"""Check that an array can be output properly"""
import numpy
vector = numpy.array([1,2,3])
self.bf['_a_vector'] = vector
open(self.testfile,"w").write(self.cf.WriteOut())
df = CifFile.CifFile(self.testfile,grammar="auto").first_block()
print('vector is ' + repr(df['_a_vector']))
self.assertTrue(df['_a_vector'] == ['1','2','3'])
def testNumpyLoop(self):
"""Check that an array in a loop can be output properly"""
import numpy
vector_list = [numpy.array([1,2,3]),numpy.array([11,12,13]),numpy.array([-1.0,1.0,0.0])]
self.bf['_a_vector'] = vector_list
self.bf.CreateLoop(["_a_vector"])
open(self.testfile,"w").write(self.cf.WriteOut())
df = CifFile.CifFile(self.testfile,grammar="auto").first_block()
print('vector is ' + repr(df['_a_vector']))
self.assertTrue(df['_a_vector'][2] == ['-1.0','1.0','0.0'])
def testNDString(self):
"""Check that a string containing square brackets is properly quoted for CIF2.0"""
self.bf['_tst'] = '3[4^6].8^5[3]'
self.cf.set_grammar("2.0")
open(self.testfile,"w").write(self.cf.WriteOut())
df = CifFile.CifFile(self.testfile,grammar="2.0").first_block()
result = df['_tst']
self.assertTrue(df['_tst']== self.bf['_tst'])
def testLong(self):
"""Check that a long integer is acceptable in Python 2"""
if sys.version_info < (3,):
self.bf['_tst'] = long(12)
else:
self.bf['_tst'] = 12
q = str(self.bf) #this will fail if longs are unacceptable
class TemplateTestCase(unittest.TestCase):
def setUp(self):
"""Create a template"""
template_string = r"""#\#CIF_2.0
# Template
#
data_TEST_DIC
_dictionary.title DDL_DIC
_definition.update 2011-07-27
_description.text
;
This dictionary specifies through its layout how we desire to
format datanames. It is not a valid dictionary, but it must
be a valid CIF file.
;
_name.category_id blahblah
_name.object_id ALIAS
_category.key_id '_alias.definition_id'
_category.key_list ['_alias.definition_id']
_type.purpose Key
_type.dimension [*]
_import.get [{"file":'templ_enum.cif' "save":'units_code'}]
loop_
_enumeration_set.state
_enumeration_set.detail
Dictionary "applies to all defined items in the dictionary"
Category "applies to all defined items in the category"
Item "applies to a single item definition"
_enumeration.default Item
"""
f = open("tests/cif_template.cif","w")
f.write(template_string)
f.close()
def tearDown(self):
try:
os.remove("tests/cif_template.cif")
os.remove("tests/temp_test_file.cif")
os.remove("tests/temp_test_file_new.cif")
except:
pass
def testTemplateInput(self):
"""Test that an output template is successfully input"""
p = CifFile.CifFile()
p.SetTemplate("tests/cif_template.cif")
#print(p.master_template)
self.assertTrue(p.master_template[0]['dataname']=='_dictionary.title')
self.assertTrue(p.master_template[5]['column']==31)
self.assertTrue(p.master_template[2]['delimiter']=='\n;')
self.assertTrue(p.master_template[11]['column']==11)
self.assertTrue(p.master_template[12]['delimiter']=='"')
self.assertTrue(p.master_template[2]['reformat']==True)
self.assertTrue(p.master_template[2]['reformat_indent']==5)
def testTemplateOutputOrder(self):
"""Test that items are output in the correct order"""
test_file = """##
data_test
_enumeration.default Item
_name.object_id ALIAS
_crazy_dummy_dataname 'whahey look at me'
loop_
_enumeration_set.detail
_enumeration_set.state
_enumeration_set.dummy
'applies to all' dictionary 0
'cat only' category 1
'whatever' item 2
_name.category_id blahblah
_description.text
;a nice long string that we would like
to be formatted really nicely with an appropriate indent and so forth. Note
that the template specifies an indent of 5 characters for this particular
data item, and we shouldn't have more than two spaces in a row if we want it
to work properly.
;
"""
f = open("tests/temp_test_file.cif","w")
f.write(test_file)
f.close()
p = CifFile.CifFile("tests/temp_test_file.cif")
p.SetTemplate("tests/cif_template.cif")
f = open("tests/temp_test_file_new.cif","w")
f.write(str(p))
f.close()
# now read as new file
g = CifFile.CifFile("tests/temp_test_file_new.cif").first_block()
self.assertEqual(g.item_order[1],'_name.category_id')
self.assertEqual(g.loops[1][-1],'_enumeration_set.dummy')
self.assertEqual(g.loops[1][0],'_enumeration_set.state')
self.assertEqual(g.item_order[-1],'_crazy_dummy_dataname')
def testStringInput(self):
"""Test that it works when passed a stringIO object"""
s = open("tests/cif_template.cif","r").read()
ss = StringIO(s)
p = CifFile.CifFile()
p.SetTemplate(ss)
self.assertTrue(p.master_template[12]['delimiter']=='"')
# TODO: check position in loop packets
# TODO: check delimiters
###### template tests #####
##############################################################
#
# Test alternative grammars (1.0, 2.0, STAR2)
#
##############################################################
class GrammarTestCase(unittest.TestCase):
def setUp(self):
"""Write out a file, then read it in again."""
teststr1_0 = """
#A test CIF file, grammar version 1.0 conformant
data_Test
_item_1 'A simple item'
_item_2 '(Bracket always ok in quotes)'
_item_3 [can_have_bracket_here_if_1.0]
"""
f = open("tests/test_1.0","w")
f.write(teststr1_0)
f.close()
teststr2_0 = r"""#\#CIF_2.0
data_Test
_item_1 ['a' 'b' 'c' 'd']
_item_2 'ordinary string'
_item_3 {'a':2 'b':3}
"""
f = open("tests/test_2.0","w")
f.write(teststr2_0)
f.close()
teststr_st = """
data_Test
_item_1 ['a' , 'b' , 'c' , 'd']
_item_2 'ordinary string'
_item_3 {'a':2 , 'b':3}
"""
f = open("tests/test_star","w")
f.write(teststr_st)
f.close()
def tearDown(self):
try:
os.remove("tests/test_star")
os.remove("tests/test_2.0")
os.remove("tests/test_1.0")
except:
pass
def testold(self):
"""Read in 1.0 conformant file; should not fail"""
f = CifFile.ReadCif("tests/test_1.0",grammar="1.0")
self.assertEqual(f["test"]["_item_3"],'[can_have_bracket_here_if_1.0]')
self.assertEqual(f.grammar, "1.0")
def testNew(self):
"""Read in a 1.0 conformant file with 1.1 grammar; should fail"""
try:
f = CifFile.ReadCif("tests/test_1.0",grammar="1.1")
except CifFile.StarError:
pass
def testCIF2(self):
"""Read in a 2.0 conformant file"""
f = CifFile.ReadCif("tests/test_2.0",grammar="2.0")
self.assertEqual(f["test"]["_item_3"]['b'],'3')
self.assertEqual(f.grammar, "2.0")
def testSTAR2(self):
"""Read in a STAR2 conformant file"""
f = CifFile.ReadCif("tests/test_star",grammar="STAR2")
self.assertEqual(f["test"]["_item_3"]['b'],'3')
self.assertEqual(f.grammar, "STAR2")
def testAuto(self):
"""Test that grammar is auto-detected"""
f = CifFile.CifFile("tests/test_1.0",grammar="auto")
self.assertEqual(f["test"]["_item_3"],'[can_have_bracket_here_if_1.0]')
self.assertEqual(f.grammar, "1.0")
h = CifFile.CifFile("tests/test_2.0",grammar="auto")
self.assertEqual(h["test"]["_item_1"],StarList(['a','b','c','d']))
self.assertEqual(h.grammar, "2.0")
def testFlexCIF2(self):
"""Test that CIF2 grammar is detected with flex tokenizer"""
f = CifFile.CifFile("tests/test_2.0",grammar="2.0",scantype="flex")
self.assertEqual(f["test"]["_item_3"]['b'],'3')
def testFlexSTAR2(self):
"""Read in a STAR2 conformant file with flex scanner"""
f = CifFile.ReadCif("tests/test_star",grammar="STAR2",scantype="flex")
self.assertEqual(f["test"]["_item_3"]['b'],'3')
def testRoundTrip(self):