Ejemplo n.º 1
0
def record2marcxml(record):
    """Convert a JSON record to a MARCXML string.

    Deduces which set of rules to use by parsing the ``$schema`` key, as
    it unequivocally determines which kind of record we have.

    Args:
        record(dict): a JSON record.

    Returns:
        str: a MARCXML string converted from the record.

    """
    schema_name = _get_schema_name(record)

    if schema_name == 'hep':
        marcjson = hep2marc.do(record)
    elif schema_name == 'authors':
        marcjson = hepnames2marc.do(record)
    else:
        raise NotImplementedError(
            u'JSON -> MARC rules missing for "{}"'.format(schema_name))

    record = RECORD()

    for key, values in sorted(iteritems(marcjson)):
        tag, ind1, ind2 = _parse_key(key)
        if _is_controlfield(tag, ind1, ind2):
            value = force_single_element(values)
            if not isinstance(value, text_type):
                value = text_type(value)
            record.append(
                CONTROLFIELD(_strip_invalid_chars_for_xml(value),
                             {'tag': tag}))
        else:
            for value in force_list(values):
                datafield = DATAFIELD({'tag': tag, 'ind1': ind1, 'ind2': ind2})
                for code, els in sorted(iteritems(value)):
                    for el in force_list(els):
                        if not isinstance(el, text_type):
                            el = text_type(el)
                        datafield.append(
                            SUBFIELD(_strip_invalid_chars_for_xml(el),
                                     {'code': code}))
                record.append(datafield)

    return tostring(record, encoding='utf8', pretty_print=True)
Ejemplo n.º 2
0
def test_force_single_element_returns_element_when_not_a_list():
    expected = 'foo'
    result = force_single_element('foo')

    assert expected == result
Ejemplo n.º 3
0
def test_force_single_element_returns_none_on_empty_list():
    assert force_single_element([]) is None
Ejemplo n.º 4
0
def test_force_single_element_returns_first_element_on_a_list():
    expected = 'foo'
    result = force_single_element(['foo', 'bar', 'baz'])

    assert expected == result