mrrc 0.7.6

A Rust library for reading, writing, and manipulating MARC bibliographic records in ISO 2709 binary format
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
"""
Advanced unit tests for mrrc Python wrapper.
Tests for edge cases, format conversions, and comprehensive API coverage.
"""

import pytest
import mrrc
from mrrc import MARCReader, MARCWriter, Record, Field, Leader
import io


def create_field(tag, ind1='0', ind2='0', **subfields):
    """Helper to create a field with subfields."""
    field = Field(tag, ind1, ind2)
    for code, value in subfields.items():
        field.add_subfield(code, value)
    return field


class TestRecordEdgeCases:
    """Test edge cases for records."""

    def test_empty_record_serialization(self):
        """Test serializing an empty record."""
        record = Record()
        
        # Should serialize without error
        json_str = record.to_json()
        assert json_str is not None
        
        xml_str = record.to_xml()
        assert xml_str is not None
        
        marc_bytes = record.to_marc21()
        assert isinstance(marc_bytes, bytes)
        assert len(marc_bytes) >= 24  # At least leader


class TestRecordMultipleFields:
    """Test records with multiple fields."""

    def test_add_multiple_fields_same_tag(self):
        """Test adding multiple fields with the same tag."""
        record = Record()
        
        for i in range(5):
            field = Field('650', ' ', '0')
            field.add_subfield('a', f'Subject {i}')
            record.add_field(field)
        
        subjects = record.subjects
        assert len(subjects) >= 5


class TestFieldOperations:
    """Test field-level operations."""

    def test_field_subfields_iteration(self):
        """Test iterating over field subfields."""
        field = Field('245', '1', '0')
        field.add_subfield('a', 'Main title')
        field.add_subfield('b', 'Subtitle')
        field.add_subfield('c', 'Responsibility')
        
        subfields = field.subfields()
        assert len(subfields) == 3
        
        codes = [sf.code for sf in subfields]
        assert 'a' in codes
        assert 'b' in codes
        assert 'c' in codes


    def test_field_subfields_by_code(self):
        """Test getting subfields by code."""
        field = Field('300', ' ', ' ')
        field.add_subfield('a', 'Pages')
        field.add_subfield('c', 'Height')
        
        a_values = field.subfields_by_code('a')
        assert len(a_values) == 1
        assert a_values[0] == 'Pages'
        
        c_values = field.subfields_by_code('c')
        assert len(c_values) == 1
        assert c_values[0] == 'Height'


    def test_field_dict_like_access(self):
        """Test dictionary-like access to subfield values."""
        field = Field('245', '1', '0')
        field.add_subfield('a', 'Title Value')
        field.add_subfield('b', 'Subtitle Value')
        
        # Test __getitem__
        assert field['a'] == 'Title Value'
        assert field['b'] == 'Subtitle Value'
        
        # Test __contains__
        assert 'a' in field
        assert 'b' in field
        assert 'z' not in field
        
        # Test get with default
        assert field.get('a') == 'Title Value'
        assert field.get('missing', 'default') == 'default'


    def test_field_get_subfields(self):
        """Test getting multiple subfields at once."""
        field = Field('260', ' ', ' ')
        field.add_subfield('a', 'New York')
        field.add_subfield('b', 'Publisher')
        field.add_subfield('c', '2023')
        field.add_subfield('d', 'Distributor')
        
        # Get multiple codes at once
        values = field.get_subfields('a', 'b')
        assert 'New York' in values
        assert 'Publisher' in values


    def test_field_indicators_mutation(self):
        """Test modifying field indicators."""
        field = Field('245', '0', '0')
        assert field.indicator1 == '0'
        assert field.indicator2 == '0'
        
        # Modify indicators
        field.indicator1 = '1'
        field.indicator2 = '4'
        
        assert field.indicator1 == '1'
        assert field.indicator2 == '4'


class TestRecordRoundTrip:
    """Test round-trip serialization and deserialization."""

    def test_roundtrip_with_control_fields(self):
        """Test round-trip with control fields."""
        original = Record()
        original.add_control_field('001', 'control-123')
        original.add_control_field('003', 'ABC')
        original.add_control_field('005', '20231231120000.0')
        
        # Serialize
        marc_bytes = original.to_marc21()
        
        # Deserialize
        reader = MARCReader(io.BytesIO(marc_bytes))
        restored = reader.read_record()
        
        assert restored is not None
        assert restored.control_field('001') == 'control-123'
        assert restored.control_field('003') == 'ABC'


    def test_roundtrip_with_multiple_fields(self):
        """Test round-trip with multiple data fields."""
        original = Record()
        original.add_control_field('001', 'id-456')
        
        # Add various fields
        original.add_field(create_field('245', '1', '0', 
                                        a='Title', b='Subtitle'))
        original.add_field(create_field('100', '1', ' ', a='Author'))
        original.add_field(create_field('020', ' ', ' ', a='ISBN123'))
        original.add_field(create_field('650', ' ', '0', a='Subject 1'))
        original.add_field(create_field('650', ' ', '0', a='Subject 2'))
        
        # Serialize and deserialize
        marc_bytes = original.to_marc21()
        reader = MARCReader(io.BytesIO(marc_bytes))
        restored = reader.read_record()
        
        assert restored is not None
        assert restored.title is not None
        assert restored.author is not None
        assert restored.isbn is not None
        assert len(restored.subjects) >= 2


    def test_roundtrip_preserves_indicators(self):
        """Test that round-trip preserves field indicators."""
        original = Record()
        
        # Add field with specific indicators
        field = Field('245', '1', '4')
        field.add_subfield('a', 'The title')
        original.add_field(field)
        
        # Serialize and deserialize
        marc_bytes = original.to_marc21()
        reader = MARCReader(io.BytesIO(marc_bytes))
        restored = reader.read_record()
        
        restored_field = restored['245']
        assert restored_field is not None
        assert restored_field.indicator1 == '1'
        assert restored_field.indicator2 == '4'


class TestFormatConversions:
    """Test conversions to various formats."""

    def test_to_json_format(self):
        """Test JSON serialization produces valid output."""
        record = Record()
        record.add_field(create_field('245', '1', '0', a='Test Title'))
        
        json_str = record.to_json()
        assert isinstance(json_str, str)
        assert len(json_str) > 0
        
        # Should contain field data
        assert '245' in json_str or 'Test Title' in json_str


    def test_to_xml_format(self):
        """Test XML serialization produces valid output."""
        record = Record()
        record.add_field(create_field('245', '1', '0', a='Test Title'))
        
        xml_str = record.to_xml()
        assert isinstance(xml_str, str)
        assert len(xml_str) > 0
        assert '<' in xml_str


    def test_to_marcjson_format(self):
        """Test MARCJSON serialization."""
        record = Record()
        record.add_control_field('001', 'test-id')
        record.add_field(create_field('245', '1', '0', a='Title'))
        
        marcjson_str = record.to_marcjson()
        assert isinstance(marcjson_str, str)
        assert len(marcjson_str) > 0


    def test_dublin_core_conversion(self):
        """Test Dublin Core metadata conversion."""
        record = Record()
        record.add_field(create_field('245', '1', '0', a='Test Title'))
        record.add_field(create_field('100', '1', ' ', a='Test Author'))
        record.add_field(create_field('260', ' ', ' ', 
                                      b='Test Publisher', c='2023'))
        
        dc = record.to_dublin_core()
        
        assert isinstance(dc, dict)
        assert 'title' in dc
        assert 'creator' in dc
        assert 'publisher' in dc


class TestFormatConversionWrapping:
    """Test that format conversion functions return properly wrapped Python objects."""

    def _make_marcjson(self):
        """Create a MARCJSON string for testing."""
        import json
        return json.dumps([
            {"leader": "01826cam a2200421 a 4500"},
            {"001": "12345"},
            {"245": {"ind1": "1", "ind2": "0", "subfields": [{"a": "Test title /"}]}},
            {"650": {"ind1": " ", "ind2": "0", "subfields": [{"a": "Testing."}]}},
        ])

    def test_marcjson_to_record_returns_wrapped_record(self):
        """Test that marcjson_to_record returns a Python Record, not a raw Rust object."""
        from mrrc import marcjson_to_record
        record = marcjson_to_record(self._make_marcjson())
        assert type(record).__name__ == 'Record'
        assert type(record).__module__ == 'mrrc'

    def test_marcjson_to_record_fields_are_wrapped(self):
        """Test that fields from marcjson_to_record records support subscript access."""
        from mrrc import marcjson_to_record
        record = marcjson_to_record(self._make_marcjson())
        fields = record.get_fields('245')
        assert len(fields) == 1
        f = fields[0]
        assert type(f).__name__ == 'Field'
        assert type(f).__module__ == 'mrrc'
        # Subscript access should work
        assert f['a'] == 'Test title /'

    def test_marcjson_to_record_leader_is_wrapped(self):
        """Test that leader from marcjson_to_record records supports indexing."""
        from mrrc import marcjson_to_record
        record = marcjson_to_record(self._make_marcjson())
        ldr = record.leader()
        assert type(ldr).__name__ == 'Leader'
        assert type(ldr).__module__ == 'mrrc'
        assert ldr[9] is not None

    def test_marcjson_to_record_helper_methods_work(self):
        """Test that helper methods work on marcjson_to_record records."""
        from mrrc import marcjson_to_record
        record = marcjson_to_record(self._make_marcjson())
        assert record.title == 'Test title /'
        assert record.subjects == ['Testing.']

    def test_json_to_record_returns_wrapped_record(self):
        """Test that json_to_record returns a wrapped Python Record."""
        from mrrc import json_to_record
        record = Record()
        record.add_field(create_field('245', '1', '0', a='Test Title'))
        json_str = record.to_json()
        restored = json_to_record(json_str)
        assert type(restored).__name__ == 'Record'
        assert type(restored).__module__ == 'mrrc'
        assert restored.title == 'Test Title'
        fields = restored.get_fields('245')
        assert fields[0]['a'] == 'Test Title'

    def test_xml_to_record_returns_wrapped_record(self):
        """Test that xml_to_record returns a wrapped Python Record."""
        from mrrc import xml_to_record
        record = Record()
        record.add_field(create_field('245', '1', '0', a='Test Title'))
        xml_str = record.to_xml()
        restored = xml_to_record(xml_str)
        assert type(restored).__name__ == 'Record'
        assert type(restored).__module__ == 'mrrc'
        assert restored.title == 'Test Title'
        fields = restored.get_fields('245')
        assert fields[0]['a'] == 'Test Title'


class TestMarcxmlConformance:
    """MARCXML conformance tests against standard LOC format."""

    def test_output_has_xml_declaration(self):
        """Verify output starts with XML declaration."""
        record = Record()
        record.add_control_field('001', 'test')
        xml_str = record.to_xml()
        assert xml_str.startswith('<?xml version="1.0" encoding="UTF-8"?>')

    def test_output_has_xmlns(self):
        """Verify output contains xmlns namespace declaration."""
        record = Record()
        record.add_control_field('001', 'test')
        xml_str = record.to_xml()
        assert 'xmlns="http://www.loc.gov/MARC21/slim"' in xml_str

    def test_tag_ind_code_are_attributes(self):
        """Verify tag, ind1, ind2, code are XML attributes (not child elements)."""
        record = Record()
        record.add_control_field('001', '12345')
        record.add_field(create_field('245', '1', '0', a='Title'))
        xml_str = record.to_xml()
        assert '<controlfield tag="001">' in xml_str
        assert '<datafield tag="245" ind1="1" ind2="0">' in xml_str
        assert '<subfield code="a">' in xml_str

    def test_parse_standard_marcxml_no_namespace(self):
        """Parse MARCXML without namespace."""
        from mrrc import xml_to_record
        xml = '''<record>
            <leader>01234nam a2200289 a 4500</leader>
            <controlfield tag="001">12345</controlfield>
            <datafield tag="245" ind1="1" ind2="0">
                <subfield code="a">Test title</subfield>
            </datafield>
        </record>'''
        record = xml_to_record(xml)
        assert record.control_field('001') == '12345'
        assert record.title == 'Test title'

    def test_parse_marcxml_with_default_namespace(self):
        """Parse MARCXML with default xmlns."""
        from mrrc import xml_to_record
        xml = '''<record xmlns="http://www.loc.gov/MARC21/slim">
            <leader>01234nam a2200289 a 4500</leader>
            <controlfield tag="001">99999</controlfield>
            <datafield tag="245" ind1="0" ind2="0">
                <subfield code="a">Namespaced title</subfield>
            </datafield>
        </record>'''
        record = xml_to_record(xml)
        assert record.control_field('001') == '99999'
        assert record.title == 'Namespaced title'

    def test_parse_marcxml_with_prefix_namespace(self):
        """Parse MARCXML with marc: prefix namespace."""
        from mrrc import xml_to_record
        xml = '''<marc:record xmlns:marc="http://www.loc.gov/MARC21/slim">
            <marc:leader>01234nam a2200289 a 4500</marc:leader>
            <marc:controlfield tag="001">88888</marc:controlfield>
            <marc:datafield tag="245" ind1="1" ind2="0">
                <marc:subfield code="a">Prefixed title</marc:subfield>
            </marc:datafield>
        </marc:record>'''
        record = xml_to_record(xml)
        assert record.control_field('001') == '88888'
        assert record.title == 'Prefixed title'

    def test_parse_collection_with_default_namespace(self):
        """Parse <collection> wrapper with default namespace."""
        from mrrc import xml_to_records
        xml = '''<collection xmlns="http://www.loc.gov/MARC21/slim">
            <record>
                <leader>01234nam a2200289 a 4500</leader>
                <controlfield tag="001">rec1</controlfield>
            </record>
            <record>
                <leader>01234nam a2200289 a 4500</leader>
                <controlfield tag="001">rec2</controlfield>
            </record>
        </collection>'''
        records = xml_to_records(xml)
        assert len(records) == 2
        assert records[0].control_field('001') == 'rec1'
        assert records[1].control_field('001') == 'rec2'

    def test_parse_collection_with_prefix_namespace(self):
        """Parse <marc:collection> wrapper with prefix namespace."""
        from mrrc import xml_to_records
        xml = '''<marc:collection xmlns:marc="http://www.loc.gov/MARC21/slim">
            <marc:record>
                <marc:leader>01234nam a2200289 a 4500</marc:leader>
                <marc:controlfield tag="001">pfx1</marc:controlfield>
            </marc:record>
            <marc:record>
                <marc:leader>01234nam a2200289 a 4500</marc:leader>
                <marc:controlfield tag="001">pfx2</marc:controlfield>
            </marc:record>
        </marc:collection>'''
        records = xml_to_records(xml)
        assert len(records) == 2
        assert records[0].control_field('001') == 'pfx1'
        assert records[1].control_field('001') == 'pfx2'

    def test_parse_loc_collection_fixture(self):
        """Parse the LOC collection.xml fixture (marc: prefix, 2 records)."""
        import os
        from mrrc import xml_to_records
        fixture = os.path.join(os.path.dirname(__file__), '..', 'data', 'loc_collection.marcxml')
        with open(fixture, 'r', encoding='utf-8') as f:
            xml = f.read()
        records = xml_to_records(xml)
        assert len(records) == 2
        # First record: "The Great Ray Charles"
        assert records[0].control_field('001') == '5637241'
        assert 'The Great Ray Charles' in (records[0].title or '')
        # Second record: "The White House"
        assert records[1].control_field('001') == '12149120'
        assert 'The White House' in (records[1].title or '')

    def test_marcxml_roundtrip_preserves_data(self):
        """Roundtrip: record → MARCXML → record preserves all data."""
        from mrrc import xml_to_record
        record = Record()
        record.add_control_field('001', 'roundtrip-001')
        record.add_control_field('008', '230601s2023    xxu||||||||||||eng d')
        record.add_field(create_field('245', '1', '0', a='Roundtrip Title /', c='Author.'))
        record.add_field(create_field('650', ' ', '0', a='Testing.'))
        record.add_field(create_field('650', ' ', '0', a='Software.'))
        xml_str = record.to_xml()
        restored = xml_to_record(xml_str)
        assert restored.control_field('001') == 'roundtrip-001'
        assert restored.title == 'Roundtrip Title /'
        fields = restored.get_fields('245')
        assert fields[0]['c'] == 'Author.'
        subjects = restored.get_fields('650')
        assert len(subjects) == 2

    def test_parse_issue_15_example(self):
        """Parse the exact MARCXML from issue #15 (Introduction to Algorithms)."""
        from mrrc import xml_to_record
        xml = '''<?xml version="1.0" encoding="UTF-8"?>
        <record xmlns="http://www.loc.gov/MARC21/slim">
            <leader>01142cam  2200301 a 4500</leader>
            <controlfield tag="001">92005291</controlfield>
            <controlfield tag="008">920219s1990    mau           001 0 eng  </controlfield>
            <datafield tag="020" ind1=" " ind2=" ">
                <subfield code="a">0262031418</subfield>
            </datafield>
            <datafield tag="245" ind1="1" ind2="0">
                <subfield code="a">Introduction to algorithms /</subfield>
                <subfield code="c">Thomas H. Cormen ... [et al.].</subfield>
            </datafield>
            <datafield tag="650" ind1=" " ind2="0">
                <subfield code="a">Computer programming.</subfield>
            </datafield>
            <datafield tag="650" ind1=" " ind2="0">
                <subfield code="a">Computer algorithms.</subfield>
            </datafield>
        </record>'''
        record = xml_to_record(xml)
        assert record.control_field('001') == '92005291'
        assert record.title == 'Introduction to algorithms /'
        fields = record.get_fields('245')
        assert fields[0]['c'] == 'Thomas H. Cormen ... [et al.].'
        isbn = record.isbn
        assert isbn == '0262031418'
        subjects = record.get_fields('650')
        assert len(subjects) == 2

    def test_xml_to_records_returns_wrapped_records(self):
        """Verify xml_to_records returns properly wrapped Python Records."""
        from mrrc import xml_to_records
        xml = '''<collection>
            <record>
                <leader>01234nam a2200289 a 4500</leader>
                <controlfield tag="001">wrap1</controlfield>
                <datafield tag="245" ind1="1" ind2="0">
                    <subfield code="a">Title One</subfield>
                </datafield>
            </record>
        </collection>'''
        records = xml_to_records(xml)
        assert len(records) == 1
        assert type(records[0]).__name__ == 'Record'
        assert type(records[0]).__module__ == 'mrrc'
        assert records[0].title == 'Title One'


class TestControlFields:
    """Test control field operations."""

    def test_control_field_roundtrip(self):
        """Test control field preservation in round-trip."""
        record = Record()
        
        test_fields = {
            '001': '12345',
            '003': 'DLC',
            '005': '20231201',
            '006': 'fixed006value',
            '007': 'fixed007value',
            '008': '230601s2023    xxu||||||||||||eng d'
        }
        
        for tag, value in test_fields.items():
            record.add_control_field(tag, value)
        
        # Verify they're there
        for tag, expected_value in test_fields.items():
            actual = record.control_field(tag)
            assert actual == expected_value


    def test_multiple_control_fields(self):
        """Test getting all control fields."""
        record = Record()
        record.add_control_field('001', 'id1')
        record.add_control_field('003', 'source1')
        
        cfs = record.control_fields()
        assert len(cfs) >= 2


class TestRecordTypeDetection:
    """Test record type detection methods."""

    def test_is_book_detection(self):
        """Test book detection."""
        leader = Leader()
        leader.record_type = 'a'
        leader.bibliographic_level = 'm'
        record = Record(leader)
        
        assert record.is_book() is True


    def test_is_serial_detection(self):
        """Test serial detection."""
        leader = Leader()
        leader.record_type = 'a'
        leader.bibliographic_level = 's'
        record = Record(leader)
        
        assert record.is_serial() is True


    def test_is_music_detection(self):
        """Test music detection."""
        leader = Leader()
        leader.record_type = 'c'
        record = Record(leader)
        
        assert record.is_music() is True


    def test_is_audiovisual_detection(self):
        """Test audiovisual detection."""
        leader = Leader()
        leader.record_type = 'g'
        record = Record(leader)
        
        assert record.is_audiovisual() is True


class TestRecordRemoval:
    """Test field removal operations."""

    def test_remove_field_by_tag(self):
        """Test removing a field by tag."""
        record = Record()
        field = Field('245', '1', '0')
        field.add_subfield('a', 'Test')
        record.add_field(field)
        
        assert record['245'] is not None
        
        # Remove the field
        record.remove_field('245')
        
        # Verify it's gone (pymarc raises KeyError for missing tags)
        with pytest.raises(KeyError):
            record['245']


class TestFieldSerialization:
    """Test field-level serialization."""

    def test_field_with_repeated_subfields(self):
        """Test field with repeated subfield codes."""
        field = Field('300', ' ', ' ')
        field.add_subfield('a', 'Part 1')
        field.add_subfield('a', 'Part 2')
        field.add_subfield('c', 'Size')
        
        # Get all 'a' values
        a_values = field.subfields_by_code('a')
        assert len(a_values) == 2
        assert 'Part 1' in a_values
        assert 'Part 2' in a_values


class TestLeaderProperties:
    """Test Leader property access and modification."""

    def test_leader_defaults(self):
        """Test default leader values."""
        leader = Leader()
        
        assert leader.record_type == 'a'
        assert leader.bibliographic_level == 'm'
        assert leader.record_status == 'n'
        assert leader.character_coding == ' '


    def test_leader_modification(self):
        """Test modifying leader properties."""
        leader = Leader()
        
        leader.record_type = 'c'
        assert leader.record_type == 'c'
        
        leader.bibliographic_level = 'd'
        assert leader.bibliographic_level == 'd'
        
        leader.record_status = 'a'
        assert leader.record_status == 'a'


    def test_leader_encoding_level(self):
        """Test leader encoding level setting."""
        leader = Leader()
        leader.encoding_level = '4'
        assert leader.encoding_level == '4'


    def test_leader_cataloging_form(self):
        """Test leader cataloging form (descriptor_cataloging_form)."""
        leader = Leader()
        
        # Test via descriptor_cataloging_form property
        leader.descriptive_cataloging_form = 'a'
        assert leader.descriptive_cataloging_form == 'a'


class TestUnicodeAndEncoding:
    """Test unicode and special character handling."""

    def test_field_with_unicode_subfields(self):
        """Test fields with unicode characters."""
        field = Field('245', '1', '0')
        field.add_subfield('a', 'Tïtlé wíth üñíçödé')
        
        subfields = field.subfields_by_code('a')
        assert 'üñíçödé' in subfields[0]


    def test_record_with_unicode_fields(self):
        """Test record with unicode content."""
        record = Record()
        
        field = Field('245', '1', '0')
        field.add_subfield('a', '日本語タイトル')
        record.add_field(field)
        
        title = record.title
        assert title is not None
        assert '日本語' in title


    def test_roundtrip_preserves_unicode(self):
        """Test that round-trip preserves unicode characters."""
        original = Record()
        
        field = Field('245', '1', '0')
        field.add_subfield('a', 'Titel in Français')
        original.add_field(field)
        
        # Serialize and deserialize
        marc_bytes = original.to_marc21()
        reader = MARCReader(io.BytesIO(marc_bytes))
        restored = reader.read_record()
        
        restored_field = restored['245']
        assert restored_field is not None
        a_values = restored_field.subfields_by_code('a')
        assert 'Français' in a_values[0]


class TestMARCWriterIntegration:
    """Test MARCWriter integration."""

    def test_write_multiple_records(self):
        """Test writing multiple records to a stream."""
        buffer = io.BytesIO()
        writer = MARCWriter(buffer)
        
        # Write 3 records
        for i in range(3):
            record = Record()
            record.add_control_field('001', f'id-{i}')
            field = Field('245', '1', '0')
            field.add_subfield('a', f'Title {i}')
            record.add_field(field)
            writer.write(record)
        
        # Read them back
        buffer.seek(0)
        reader = MARCReader(buffer)
        
        count = 0
        for record in reader:
            assert record is not None
            count += 1
        
        assert count == 3


class TestFieldConveniences:
    """Test convenience methods for common fields."""

    def test_get_multiple_fields_by_tags(self):
        """Test getting multiple fields by multiple tags."""
        record = Record()
        
        record.add_field(create_field('245', '1', '0', a='Title'))
        record.add_field(create_field('100', '1', ' ', a='Author'))
        record.add_field(create_field('260', ' ', ' ', b='Publisher'))
        record.add_field(create_field('300', ' ', ' ', a='Pages'))
        
        # Get multiple tags at once
        fields = record.get_fields('245', '100', '260')
        assert len(fields) >= 3


    def test_all_fields_access(self):
        """Test getting all fields at once."""
        record = Record()
        
        record.add_field(create_field('245', '1', '0', a='Title'))
        record.add_field(create_field('100', '1', ' ', a='Author'))
        record.add_field(create_field('650', ' ', '0', a='Subject'))
        
        all_fields = record.get_fields()
        assert len(all_fields) >= 3


class TestLinkedFields:
    """Test 880 alternate graphic representation field linkage."""

    def _build_record_with_880(self, tag, ind1, ind2, occurrence,
                                romanized_subfields, script_subfields,
                                script_code=None):
        """Helper: build a record with one original field and one linked 880.

        Args:
            tag: Original field tag (e.g., '245')
            ind1, ind2: Indicators for both original and 880
            occurrence: Two-digit occurrence string (e.g., '01')
            romanized_subfields: dict of code->value for the original field
            script_subfields: dict of code->value for the 880 field
            script_code: Optional MARC script code (e.g., '(2/r' for Hebrew RTL)
        """
        record = Record()
        record.add_control_field('001', 'test-linked')

        # Build $6 values
        orig_6 = f'880-{occurrence}'
        if script_code:
            linked_6 = f'{tag}-{occurrence}/{script_code}'
        else:
            linked_6 = f'{tag}-{occurrence}'

        # Original field with $6 linkage
        orig = Field(tag, ind1, ind2)
        orig.add_subfield('6', orig_6)
        for code, value in romanized_subfields.items():
            orig.add_subfield(code, value)
        record.add_field(orig)

        # Linked 880 field
        linked = Field('880', ind1, ind2)
        linked.add_subfield('6', linked_6)
        for code, value in script_subfields.items():
            linked.add_subfield(code, value)
        record.add_field(linked)

        return record

    # ------------------------------------------------------------------
    # Hebrew (RTL) – Soncino Mishneh Torah example from the issue
    # ------------------------------------------------------------------

    def test_hebrew_title_linkage(self):
        """Test 880 linkage for Hebrew title (RTL script)."""
        record = self._build_record_with_880(
            '245', '1', '0', '01',
            romanized_subfields={'a': 'Mishneh Torah.'},
            script_subfields={'a': 'משנה תורה.'},
            script_code='(2/r',
        )
        f245 = record.get_fields('245')[0]
        linked = record.get_linked_fields(f245)
        assert len(linked) == 1
        assert linked[0].tag == '880'
        assert linked[0]['a'] == 'משנה תורה.'

    def test_hebrew_publisher_linkage(self):
        """Test 880 linkage for Hebrew publisher (RTL script)."""
        record = self._build_record_with_880(
            '260', ' ', ' ', '03',
            romanized_subfields={
                'a': 'Śontsino :',
                'b': 'Gershom ben Mosheh ish Śontsino,',
            },
            script_subfields={
                'a': 'שונצינו :',
                'b': 'גרשם בן משה איש שונצינו,',
            },
            script_code='(2/r',
        )
        f260 = record.get_fields('260')[0]
        linked = record.get_linked_fields(f260)
        assert len(linked) == 1
        assert 'שונצינו' in linked[0]['a']

    # ------------------------------------------------------------------
    # Arabic (RTL) – An Arabic novel
    # ------------------------------------------------------------------

    def test_arabic_title_linkage(self):
        """Test 880 linkage for Arabic title (RTL script)."""
        record = self._build_record_with_880(
            '245', '1', '0', '01',
            romanized_subfields={'a': 'Awlād ḥāratinā /'},
            script_subfields={'a': 'أولاد حارتنا /'},
            script_code='(3/r',
        )
        f245 = record.get_fields('245')[0]
        linked = record.get_linked_fields(f245)
        assert len(linked) == 1
        assert linked[0]['a'] == 'أولاد حارتنا /'

    def test_arabic_author_linkage(self):
        """Test 880 linkage for Arabic author (RTL script)."""
        record = self._build_record_with_880(
            '100', '1', ' ', '02',
            romanized_subfields={'a': 'Maḥfūẓ, Najīb,'},
            script_subfields={'a': 'محفوظ، نجيب،'},
            script_code='(3/r',
        )
        f100 = record.get_fields('100')[0]
        linked = record.get_linked_fields(f100)
        assert len(linked) == 1
        assert 'محفوظ' in linked[0]['a']

    # ------------------------------------------------------------------
    # CJK – Chinese book
    # ------------------------------------------------------------------

    def test_cjk_title_linkage(self):
        """Test 880 linkage for CJK (Chinese) title."""
        record = self._build_record_with_880(
            '245', '1', '0', '01',
            romanized_subfields={'a': 'Hong lou meng /'},
            script_subfields={'a': '紅樓夢 /'},
            script_code='$1',
        )
        f245 = record.get_fields('245')[0]
        linked = record.get_linked_fields(f245)
        assert len(linked) == 1
        assert linked[0]['a'] == '紅樓夢 /'

    def test_cjk_author_linkage(self):
        """Test 880 linkage for CJK (Chinese) author."""
        record = self._build_record_with_880(
            '100', '1', ' ', '02',
            romanized_subfields={'a': 'Cao, Xueqin,'},
            script_subfields={'a': '曹雪芹,'},
            script_code='$1',
        )
        f100 = record.get_fields('100')[0]
        linked = record.get_linked_fields(f100)
        assert len(linked) == 1
        assert '曹雪芹' in linked[0]['a']

    # ------------------------------------------------------------------
    # Cyrillic – Russian novel
    # ------------------------------------------------------------------

    def test_cyrillic_title_linkage(self):
        """Test 880 linkage for Cyrillic (Russian) title."""
        record = self._build_record_with_880(
            '245', '1', '0', '01',
            romanized_subfields={'a': 'Voĭna i mir /'},
            script_subfields={'a': 'Война и мир /'},
            script_code='(N',
        )
        f245 = record.get_fields('245')[0]
        linked = record.get_linked_fields(f245)
        assert len(linked) == 1
        assert linked[0]['a'] == 'Война и мир /'

    def test_cyrillic_author_linkage(self):
        """Test 880 linkage for Cyrillic (Russian) author."""
        record = self._build_record_with_880(
            '100', '1', ' ', '02',
            romanized_subfields={'a': 'Tolstoĭ, Lev Nikolaevich,'},
            script_subfields={'a': 'Толстой, Лев Николаевич,'},
            script_code='(N',
        )
        f100 = record.get_fields('100')[0]
        linked = record.get_linked_fields(f100)
        assert len(linked) == 1
        assert 'Толстой' in linked[0]['a']

    # ------------------------------------------------------------------
    # Linkage WITHOUT script identification code
    # (valid MARC — just occurrence number, no script/direction)
    # ------------------------------------------------------------------

    def test_linkage_without_script_code(self):
        """Test 880 linkage using bare occurrence numbers (no script code)."""
        record = self._build_record_with_880(
            '245', '1', '0', '01',
            romanized_subfields={'a': 'Romanized title'},
            script_subfields={'a': 'Vernacular title'},
            script_code=None,  # No script identification
        )
        f245 = record.get_fields('245')[0]
        linked = record.get_linked_fields(f245)
        assert len(linked) == 1
        assert linked[0]['a'] == 'Vernacular title'

    # ------------------------------------------------------------------
    # Subject field linkage (650)
    # ------------------------------------------------------------------

    def test_subject_field_linkage(self):
        """Test 880 linkage for subject headings (650)."""
        record = self._build_record_with_880(
            '650', ' ', '0', '04',
            romanized_subfields={'a': 'Filosofiyah Yehudit'},
            script_subfields={'a': 'פילוסופיה יהודית'},
            script_code='(2/r',
        )
        f650 = record.get_fields('650')[0]
        linked = record.get_linked_fields(f650)
        assert len(linked) == 1
        assert 'פילוסופיה' in linked[0]['a']

    # ------------------------------------------------------------------
    # Series field linkage (490)
    # ------------------------------------------------------------------

    def test_series_field_linkage(self):
        """Test 880 linkage for series statement (490)."""
        record = self._build_record_with_880(
            '490', '1', ' ', '05',
            romanized_subfields={'a': 'Mif ha-sifrut ha-ʻIvrit'},
            script_subfields={'a': 'מיף הספרות העברית'},
            script_code='(2/r',
        )
        f490 = record.get_fields('490')[0]
        linked = record.get_linked_fields(f490)
        assert len(linked) == 1

    # ------------------------------------------------------------------
    # Notes field linkage (500)
    # ------------------------------------------------------------------

    def test_notes_field_linkage(self):
        """Test 880 linkage for general note (500)."""
        record = self._build_record_with_880(
            '500', ' ', ' ', '06',
            romanized_subfields={'a': 'Includes index.'},
            script_subfields={'a': 'כולל מפתח.'},
            script_code='(2/r',
        )
        f500 = record.get_fields('500')[0]
        linked = record.get_linked_fields(f500)
        assert len(linked) == 1
        assert linked[0]['a'] == 'כולל מפתח.'

    # ------------------------------------------------------------------
    # Multiple linked pairs in one record
    # ------------------------------------------------------------------

    def test_multiple_linked_pairs(self):
        """Test record with multiple 880-linked field pairs."""
        record = Record()
        record.add_control_field('001', 'multi-link')

        # Pair 1: Title (245 <-> 880, occurrence 01)
        f245 = Field('245', '1', '0')
        f245.add_subfield('6', '880-01')
        f245.add_subfield('a', 'Mishneh Torah.')
        record.add_field(f245)

        f880_title = Field('880', '1', '0')
        f880_title.add_subfield('6', '245-01/(2/r')
        f880_title.add_subfield('a', 'משנה תורה.')
        record.add_field(f880_title)

        # Pair 2: Author (100 <-> 880, occurrence 02)
        f100 = Field('100', '1', ' ')
        f100.add_subfield('6', '880-02')
        f100.add_subfield('a', 'Maimonides,')
        record.add_field(f100)

        f880_author = Field('880', '1', ' ')
        f880_author.add_subfield('6', '100-02/(2/r')
        f880_author.add_subfield('a', 'רמב״ם,')
        record.add_field(f880_author)

        # Pair 3: Publisher (260 <-> 880, occurrence 03)
        f260 = Field('260', ' ', ' ')
        f260.add_subfield('6', '880-03')
        f260.add_subfield('a', 'Śontsino :')
        record.add_field(f260)

        f880_pub = Field('880', ' ', ' ')
        f880_pub.add_subfield('6', '260-03/(2/r')
        f880_pub.add_subfield('a', 'שונצינו :')
        record.add_field(f880_pub)

        # Verify each pair resolves correctly
        title_fields = record.get_fields('245')
        linked_title = record.get_linked_fields(title_fields[0])
        assert len(linked_title) == 1
        assert 'משנה' in linked_title[0]['a']

        author_fields = record.get_fields('100')
        linked_author = record.get_linked_fields(author_fields[0])
        assert len(linked_author) == 1
        assert 'רמב' in linked_author[0]['a']

        pub_fields = record.get_fields('260')
        linked_pub = record.get_linked_fields(pub_fields[0])
        assert len(linked_pub) == 1
        assert 'שונצינו' in linked_pub[0]['a']

    # ------------------------------------------------------------------
    # Edge cases
    # ------------------------------------------------------------------

    def test_field_without_subfield_6_returns_empty(self):
        """Field with no $6 linkage should return empty list."""
        record = Record()
        f245 = Field('245', '1', '0')
        f245.add_subfield('a', 'A plain title.')
        record.add_field(f245)

        result = record.get_linked_fields(record.get_fields('245')[0])
        assert result == []

    def test_subfield_6_with_no_matching_880_returns_empty(self):
        """Field with $6 but no matching 880 should return empty list."""
        record = Record()
        f245 = Field('245', '1', '0')
        f245.add_subfield('6', '880-01')
        f245.add_subfield('a', 'Orphan title.')
        record.add_field(f245)
        # No 880 field added

        result = record.get_linked_fields(record.get_fields('245')[0])
        assert result == []

    def test_linked_field_is_wrapped_python_field(self):
        """Returned linked fields should be wrapped Python Field objects."""
        record = self._build_record_with_880(
            '245', '1', '0', '01',
            romanized_subfields={'a': 'Romanized'},
            script_subfields={'a': 'Vernacular'},
        )
        f245 = record.get_fields('245')[0]
        linked = record.get_linked_fields(f245)

        assert len(linked) == 1
        # Must be a wrapped Field (supports subscript access)
        assert linked[0]['a'] == 'Vernacular'
        assert linked[0].tag == '880'
        assert hasattr(linked[0], 'subfields')

    def test_get_linked_fields_returns_list(self):
        """get_linked_fields always returns a list, even for single match."""
        record = self._build_record_with_880(
            '245', '1', '0', '01',
            romanized_subfields={'a': 'Title'},
            script_subfields={'a': 'כותרת'},
            script_code='(2/r',
        )
        f245 = record.get_fields('245')[0]
        result = record.get_linked_fields(f245)
        assert isinstance(result, list)

    # ------------------------------------------------------------------
    # Added-entry name linkage (700) — e.g., translator in original script
    # ------------------------------------------------------------------

    def test_added_entry_linkage(self):
        """Test 880 linkage for 700 added entry (translator)."""
        record = self._build_record_with_880(
            '700', '1', ' ', '07',
            romanized_subfields={'a': 'Ibn Tibbon, Shemuel,', 'e': 'translator.'},
            script_subfields={'a': 'אבן תבון, שמואל,', 'e': 'מתרגם.'},
            script_code='(2/r',
        )
        f700 = record.get_fields('700')[0]
        linked = record.get_linked_fields(f700)
        assert len(linked) == 1
        assert 'אבן תבון' in linked[0]['a']

    # ------------------------------------------------------------------
    # Greek script
    # ------------------------------------------------------------------

    def test_greek_title_linkage(self):
        """Test 880 linkage for Greek script."""
        record = self._build_record_with_880(
            '245', '1', '0', '01',
            romanized_subfields={'a': 'Politeia /'},
            script_subfields={'a': 'Πολιτεία /'},
            script_code='(S',
        )
        f245 = record.get_fields('245')[0]
        linked = record.get_linked_fields(f245)
        assert len(linked) == 1
        assert linked[0]['a'] == 'Πολιτεία /'


class TestLinkedFieldMARCJSON:
    """Test get_linked_fields with records loaded via marcjson_to_record."""

    def test_soncino_mishneh_torah(self):
        """Full Soncino Mishneh Torah example from issue #19."""
        import json
        from mrrc import marcjson_to_record

        marcjson = json.dumps([
            {"leader": "05723cam a22006251a 4500"},
            {"001": "2018751272"},
            {"245": {"ind1": "1", "ind2": "0", "subfields": [
                {"6": "880-01"}, {"a": "Mishneh Torah."}
            ]}},
            {"260": {"ind1": " ", "ind2": " ", "subfields": [
                {"6": "880-03"},
                {"a": "Śontsino :"},
                {"b": "Gershom ben Mosheh ish Śontsino,"},
                {"c": "r.ḥ. Nisan shenat 250 [March 23, 1490]"}
            ]}},
            {"880": {"ind1": "1", "ind2": "0", "subfields": [
                {"6": "245-01/(2/r"}, {"a": "משנה תורה."}
            ]}},
            {"880": {"ind1": " ", "ind2": " ", "subfields": [
                {"6": "260-03/(2/r"},
                {"a": "שונצינו :"},
                {"b": "גרשם בן משה איש שונצינו,"},
                {"c": "ר\"ח ניסן שנת נ\"ר"}
            ]}}
        ])
        record = marcjson_to_record(marcjson)

        # Look up linked 880 for title
        f245 = record.get_fields('245')[0]
        linked_title = record.get_linked_fields(f245)
        assert len(linked_title) == 1
        assert linked_title[0]['a'] == 'משנה תורה.'

        # Look up linked 880 for publisher
        f260 = record.get_fields('260')[0]
        linked_pub = record.get_linked_fields(f260)
        assert len(linked_pub) == 1
        assert 'שונצינו' in linked_pub[0]['a']


class TestSerializationRoundTrip:
    """Test that records from deserialization functions can be re-serialized.

    Regression tests for GitHub issue #57: record_to_json/xml fail on records
    returned by xml_to_record() with 'Record' object is not an instance of 'Record'.
    """

    def test_xml_to_record_then_record_to_json(self):
        """xml_to_record() result can be passed to record_to_json()."""
        xml = '''<record xmlns="http://www.loc.gov/MARC21/slim">
          <leader>00000cam a2200000 a 4500</leader>
          <controlfield tag="001">test123</controlfield>
          <datafield tag="245" ind1="1" ind2="0">
            <subfield code="a">Test title</subfield>
          </datafield>
        </record>'''
        rec = mrrc.xml_to_record(xml)
        json_str = mrrc.record_to_json(rec)
        assert '"245"' in json_str
        assert 'Test title' in json_str

    def test_xml_to_record_then_record_to_xml(self):
        """xml_to_record() result can be passed to record_to_xml()."""
        xml = '''<record xmlns="http://www.loc.gov/MARC21/slim">
          <leader>00000cam a2200000 a 4500</leader>
          <controlfield tag="001">test123</controlfield>
          <datafield tag="245" ind1="1" ind2="0">
            <subfield code="a">Test title</subfield>
          </datafield>
        </record>'''
        rec = mrrc.xml_to_record(xml)
        xml_out = mrrc.record_to_xml(rec)
        assert 'Test title' in xml_out

    def test_xml_to_record_then_record_to_marcjson(self):
        """xml_to_record() result can be passed to record_to_marcjson()."""
        xml = '''<record xmlns="http://www.loc.gov/MARC21/slim">
          <leader>00000cam a2200000 a 4500</leader>
          <controlfield tag="001">test123</controlfield>
          <datafield tag="245" ind1="1" ind2="0">
            <subfield code="a">Test title</subfield>
          </datafield>
        </record>'''
        rec = mrrc.xml_to_record(xml)
        mj = mrrc.record_to_marcjson(rec)
        assert 'Test title' in mj

    def test_xml_to_record_then_record_to_mods(self):
        """xml_to_record() result can be passed to record_to_mods()."""
        xml = '''<record xmlns="http://www.loc.gov/MARC21/slim">
          <leader>00000cam a2200000 a 4500</leader>
          <controlfield tag="001">test123</controlfield>
          <datafield tag="245" ind1="1" ind2="0">
            <subfield code="a">Test title</subfield>
          </datafield>
        </record>'''
        rec = mrrc.xml_to_record(xml)
        mods = mrrc.record_to_mods(rec)
        assert 'Test title' in mods

    def test_xml_to_record_then_record_to_dublin_core(self):
        """xml_to_record() result can be passed to record_to_dublin_core()."""
        xml = '''<record xmlns="http://www.loc.gov/MARC21/slim">
          <leader>00000cam a2200000 a 4500</leader>
          <controlfield tag="001">test123</controlfield>
          <datafield tag="245" ind1="1" ind2="0">
            <subfield code="a">Test title</subfield>
          </datafield>
        </record>'''
        rec = mrrc.xml_to_record(xml)
        dc = mrrc.record_to_dublin_core(rec)
        assert 'Test title' in dc['title'][0]

    def test_xml_to_record_then_record_to_dublin_core_xml(self):
        """xml_to_record() result can be passed to _mrrc.record_to_dublin_core_xml()."""
        from mrrc._mrrc import record_to_dublin_core_xml
        xml = '''<record xmlns="http://www.loc.gov/MARC21/slim">
          <leader>00000cam a2200000 a 4500</leader>
          <controlfield tag="001">test123</controlfield>
          <datafield tag="245" ind1="1" ind2="0">
            <subfield code="a">Test title</subfield>
          </datafield>
        </record>'''
        rec = mrrc.xml_to_record(xml)
        dc_xml = record_to_dublin_core_xml(rec)
        assert 'Test title' in dc_xml

    def test_json_to_record_then_record_to_xml(self):
        """json_to_record() result can be passed to record_to_xml()."""
        record = Record()
        record.add_field(create_field('245', '1', '0', a='JSON Test'))
        json_str = mrrc.record_to_json(record)
        restored = mrrc.json_to_record(json_str)
        xml_out = mrrc.record_to_xml(restored)
        assert 'JSON Test' in xml_out

    def test_raw_record_still_works(self):
        """Direct _mrrc.Record (unwrapped) still works with serialization."""
        from mrrc._mrrc import Record as _Record, Leader as _Leader
        raw = _Record(_Leader())
        # Should not raise
        mrrc.record_to_json(raw)


if __name__ == '__main__':
    pytest.main([__file__, '-v'])