def test_derive_adduct_from_name_parametrized(metadata,
                                              remove_adduct_from_name,
                                              expected_adduct, expected_name,
                                              removed_adduct):
    set_matchms_logger_level("INFO")
    spectrum_in = SpectrumBuilder().with_metadata(metadata).build()

    with LogCapture() as log:
        spectrum = derive_adduct_from_name(
            spectrum_in, remove_adduct_from_name=remove_adduct_from_name)

    assert spectrum.get(
        "adduct") == expected_adduct, "Expected different adduct."
    assert spectrum.get(
        "compound_name") == expected_name, "Expected different cleaned name."

    expected_log = []
    if spectrum.get("compound_name") != spectrum_in.get("compound_name"):
        expected_log.append(
            ('matchms', 'INFO',
             f'Removed adduct {removed_adduct} from compound name.'))
    if spectrum.get("adduct") != spectrum_in.get("adduct"):
        expected_log.append(('matchms', 'INFO',
                             f'Added adduct {expected_adduct} to metadata.'))

    log.check(*expected_log)
    reset_matchms_logger()
Exemple #2
0
def test_add_fingerprint_no_smiles_no_inchi():
    """Test if fingerprint it generated correctly."""
    set_matchms_logger_level("INFO")
    spectrum_in = SpectrumBuilder().with_metadata({"compound_name": "test name"}).build()

    with LogCapture() as log:
        spectrum = add_fingerprint(spectrum_in)
    assert spectrum.get("fingerprint", None) is None, "Expected None."
    log.check(
        ("matchms", "INFO", "No fingerprint was added (name: test name).")
    )
    reset_matchms_logger()
def test_add_precursor_mz_only_pepmass_present(caplog):
    """Test if precursor_mz is correctly derived if only pepmass is present."""
    set_matchms_logger_level("INFO")
    mz = numpy.array([], dtype='float')
    intensities = numpy.array([], dtype='float')
    metadata = {"pepmass": (444.0, 10)}
    spectrum_in = SpectrumBuilder().with_metadata(
        metadata).with_mz(mz).with_intensities(intensities).build()

    spectrum = add_precursor_mz(spectrum_in)

    assert spectrum.get("precursor_mz") == 444.0, "Expected different precursor_mz."
    assert "Added precursor_mz entry based on field 'pepmass'" in caplog.text, \
        "Expected different log message"
    reset_matchms_logger()
Exemple #4
0
def test_require_precursor_below_mz_max_50():
    """Set max_mz to 50."""
    set_matchms_logger_level("INFO")
    mz = numpy.array([10, 20, 30, 40], dtype="float")
    intensities = numpy.array([0, 1, 10, 100], dtype="float")
    spectrum_in = SpectrumBuilder().with_mz(mz).with_intensities(
        intensities).build()
    spectrum_in.set("precursor_mz", 60.)

    with LogCapture() as log:
        spectrum = require_precursor_below_mz(spectrum_in, max_mz=50)

    assert spectrum is None, "Expected spectrum to be None."
    log.check(('matchms', 'INFO',
               'Spectrum with precursor_mz 60.0 (>50) was set to None.'))
    reset_matchms_logger()
Exemple #5
0
def test_derive_smiles_from_inchi():
    """Test if conversion to smiles works when only inchi is given.
    """
    pytest.importorskip("rdkit")
    set_matchms_logger_level("INFO")
    spectrum_in = SpectrumBuilder().with_metadata({
        "inchi": '"InChI=1S/C6H12/c1-2-4-6-5-3-1/h1-6H2"',
        "smiles": ""
    }).build()

    with LogCapture() as log:
        spectrum = derive_smiles_from_inchi(spectrum_in)
    assert spectrum.get("smiles") == "C1CCCCC1", "Expected different smiles"
    log.check(('matchms', 'INFO',
               'Added smiles C1CCCCC1 to metadata (was converted from InChI)'))
    reset_matchms_logger()
def test_require_precursor_mz_fail_when_mz_too_small(precursor_mz):
    """Test if spectrum is None when precursor_mz <= minimum_accepted_mz"""
    set_matchms_logger_level("INFO")
    mz = numpy.array([10, 20, 30, 40], dtype="float")
    intensities = numpy.array([0, 1, 10, 100], dtype="float")
    spectrum_in = SpectrumBuilder().with_mz(mz).with_intensities(
        intensities).build()
    spectrum_in.set("precursor_mz", precursor_mz)

    with LogCapture() as log:
        spectrum = require_precursor_mz(spectrum_in)

    assert spectrum is None, "Expected spectrum to be None."
    log.check(
        ('matchms', 'INFO', 'Spectrum without precursor_mz was set to None.'))
    reset_matchms_logger()
Exemple #7
0
def test_reduce_to_number_of_peaks_set_to_none():
    """Test is spectrum is set to None if not enough peaks."""
    set_matchms_logger_level("INFO")
    mz = numpy.array([10, 20], dtype="float")
    intensities = numpy.array([0.5, 1], dtype="float")
    spectrum_in = SpectrumBuilder().with_mz(mz).with_intensities(
        intensities).with_metadata({
            "parent_mass": 50
        }).build()

    with LogCapture() as log:
        spectrum = reduce_to_number_of_peaks(spectrum_in, n_required=5)

    assert spectrum is None, "Expected spectrum to be set to None."
    log.check(
        ('matchms', 'INFO', "Spectrum with 2 (<5) peaks was set to None."))
    reset_matchms_logger()
Exemple #8
0
def test_set_and_reset_matchms_logger_level(caplog):
    """Test logging functionality."""
    logger = logging.getLogger("matchms")
    assert logger.getEffectiveLevel() == 30, "Expected different logging level"

    set_matchms_logger_level("INFO")
    logger.debug("debug test")
    logger.info("info test")

    assert logger.name == "matchms", "Expected different logger name"
    assert logger.getEffectiveLevel() == 20, "Expected different logging level"
    assert "debug test" not in caplog.text, "Debug log should not be shown."
    assert "info test" in caplog.text, "Info log should have been shown."

    reset_matchms_logger()
    assert logger.getEffectiveLevel() == 30, "Expected different logging level"
    reset_matchms_logger()
Exemple #9
0
def test_derive_inchikey_from_inchi():
    """Test if conversion from inchi and inchikey works."""
    pytest.importorskip("rdkit")
    set_matchms_logger_level("INFO")
    spectrum_in = SpectrumBuilder().with_metadata({
        "inchi": '"InChI=1S/C6H12/c1-2-4-6-5-3-1/h1-6H2"',
        "inchikey": 'n/a'
    }).build()

    with LogCapture() as log:
        spectrum = derive_inchikey_from_inchi(spectrum_in)
    assert spectrum.get(
        "inchikey")[:14] == 'XDTMQSROBMDMFD', "Expected different inchikey"
    log.check((
        'matchms', 'INFO',
        'Added InChIKey XDTMQSROBMDMFD-UHFFFAOYSA-N to metadata (was converted from inchi)'
    ))
    reset_matchms_logger()
Exemple #10
0
def test_add_logging_to_file_only_file(tmp_path, capsys):
    """Test writing logs to file."""
    reset_matchms_logger()
    set_matchms_logger_level("INFO")
    filename = os.path.join(tmp_path, "test.log")
    add_logging_to_file(filename, remove_stream_handlers=True)
    logger = logging.getLogger("matchms")
    logger.info("test message no.1")

    # Test streamed logs
    not_expected_log_entry = "test message no.1"
    assert len(logger.handlers) == 1, "Expected only one Handler"
    assert not_expected_log_entry not in capsys.readouterr(
    ).out, "Did not expect log message"

    # Test log file
    expected_log_entry = "INFO:matchms:test_logging:test message no.1"
    assert os.path.isfile(filename), "Log file not found."
    with open(filename, "r", encoding="utf-8") as file:
        logs = file.read()
    assert expected_log_entry in logs, "Expected different log file content"
    reset_matchms_logger()
Exemple #11
0
def test_add_logging_to_file(tmp_path, caplog, capsys):
    """Test writing logs to file."""
    reset_matchms_logger()
    set_matchms_logger_level("INFO")
    filename = os.path.join(tmp_path, "test.log")
    add_logging_to_file(filename)
    logger = logging.getLogger("matchms")
    logger.info("test message no.1")

    expected_log_entry = "test message no.1"
    # Test streamed logs
    assert expected_log_entry in caplog.text, "Expected different log message."
    assert expected_log_entry in capsys.readouterr().out, \
        "Expected different log message in output (stdout/stderr)."

    # Test log file
    expected_log_entry = "INFO:matchms:test_logging:test message no.1"
    assert len(logger.handlers) == 2, "Expected two Handler"
    assert os.path.isfile(filename), "Log file not found."
    with open(filename, "r", encoding="utf-8") as file:
        logs = file.read()
    assert expected_log_entry in logs, "Expected different log file content"
    reset_matchms_logger()