Example #1
0
def test_dbbuddy_hash():
    dbbuddy = Db.DbBuddy(", ".join(ACCNS))
    db_hash = hash(dbbuddy)
    assert hash(dbbuddy) == db_hash

    dbbuddy = Db.DbBuddy(", ".join(ACCNS))
    assert hash(dbbuddy) != db_hash
def test_ncbiclient_fetch_sequences(hf, monkeypatch, capsys):
    def patch_entrez_fetch_seq(*args, **kwargs):
        print("patch_entrez_fetch_seq\nargs: %s\nkwargs: %s" % (args, kwargs))
        test_file = "{0}mock_resources{1}test_databasebuddy_clients" \
                    "{1}Entrez_efetch_seq.gb".format(hf.resource_path, os.path.sep)
        with open(test_file, "r") as ifile:
            client.results_file.write(ifile.read())

    # Empty DbBuddy
    dbbuddy = Db.DbBuddy()
    client = Db.NCBIClient(dbbuddy)
    client.fetch_sequences("ncbi_prot")
    assert hf.string2hash(str(dbbuddy)) == "016d020dd926f64ac1431f15c5683678"

    # With records
    monkeypatch.setattr(Db.NCBIClient, "_mc_query", patch_entrez_fetch_seq)
    dbbuddy = Db.DbBuddy("XP_010103297.1,XP_010103298.1,XM_010104998.1")
    client = Db.NCBIClient(dbbuddy)
    client.fetch_sequences("ncbi_prot")
    dbbuddy.out_format = "gb"
    assert hf.string2hash(str(dbbuddy)) == "9bd8017da009696c1b6ebe5d4e3c0a89"
    capsys.readouterr()  # Clean up the buffer
    dbbuddy.print()
    out, err = capsys.readouterr()
    out = re.sub(".*?sec.*?\n", "", out)
    assert hf.string2hash(out) == "40b60e455df6ba092dbf96dc028ca82f"
def test_ncbiclient_fetch_summaries(hf, monkeypatch, capsys):
    def patch_entrez_fetch_summaries(*args, **kwargs):
        print("patch_entrez_fetch_summaries\nargs: %s\nkwargs: %s" % (args, kwargs))
        if "esummary_seq" in kwargs["func_args"]:
            test_file = "%s/mock_resources/test_databasebuddy_clients/Entrez_esummary_seq.xml" % hf.resource_path
            with open(test_file, "r") as ifile:
                client.results_file.write(ifile.read().strip())
                client.results_file.write('\n### END ###\n')
        elif "esummary_taxa" in kwargs["func_args"]:
            test_file = "%s/mock_resources/test_databasebuddy_clients/Entrez_esummary_taxa.xml" % hf.resource_path
            with open(test_file, "r") as ifile:
                client.results_file.write(ifile.read().strip())
                client.results_file.write('\n### END ###\n')
        return

    # No records to fetch
    dbbuddy = Db.DbBuddy()
    client = Db.NCBIClient(dbbuddy)
    client.fetch_summaries("ncbi_prot")
    assert not client.dbbuddy.records

    monkeypatch.setattr(Db.NCBIClient, "_mc_query", patch_entrez_fetch_summaries)
    dbbuddy = Db.DbBuddy("XP_010103297,XP_010103298.1,AAY72386.1")
    client = Db.NCBIClient(dbbuddy)
    capsys.readouterr()
    client.fetch_summaries("ncbi_prot")

    assert dbbuddy.records["AAY72386.1"].summary["organism"] == "Unclassified"
    assert hf.string2hash(str(dbbuddy)) == "3a5e3379b12afe4044d2ece852ab2556"
Example #4
0
def test_dbbuddy_equivalent():
    dbbuddy1 = Db.DbBuddy(", ".join(ACCNS))
    dbbuddy2 = Db.DbBuddy(", ".join(ACCNS))
    assert dbbuddy1 == dbbuddy2

    dbbuddy2 = Db.DbBuddy(", ".join(ACCNS[1:]))
    assert dbbuddy1 != dbbuddy2
Example #5
0
def test_instantiate_dbbuddy_from_list():
    dbbuddy = Db.DbBuddy(", ".join(ACCNS))
    dbbuddy = Db.DbBuddy([dbbuddy, dbbuddy])
    for accn in ACCNS:
        assert accn in dbbuddy.records

    with pytest.raises(TypeError) as err:
        Db.DbBuddy(["foo", "bar"])
    assert "List of non-DbBuddy objects passed into DbBuddy as _input." in str(err)
Example #6
0
def test_error(monkeypatch, capsys):
    monkeypatch.setattr(Db, "LiveShell", mock_systemexit)

    test_in_args = deepcopy(in_args)
    test_in_args.live_shell = True

    assert Db.command_line_ui(test_in_args, Db.DbBuddy(), skip_exit=True) is None

    monkeypatch.setattr(Db, "LiveShell", mock_fileexistserror)
    monkeypatch.setattr(br.TempFile, "save", lambda *_: True)
    monkeypatch.setattr(br, "send_traceback", lambda *_: True)
    capsys.readouterr()
    assert Db.command_line_ui(test_in_args, Db.DbBuddy(), skip_exit=True) is None
    out, err = capsys.readouterr()
    assert "can be loaded by launching DatabaseBuddy and using the 'load' command." in err
Example #7
0
def test_guess_db(capsys, hf):
    test_in_args = deepcopy(in_args)
    test_in_args.guess_database = True

    with pytest.raises(SystemExit):
        Db.command_line_ui(test_in_args, Db.DbBuddy(), skip_exit=True)

    out, err = capsys.readouterr()
    assert 'Nothing to return' in out

    with pytest.raises(SystemExit):
        Db.command_line_ui(test_in_args, Db.DbBuddy(",".join(ACCNS) + ",Casp9"), skip_exit=True)

    out, err = capsys.readouterr()
    assert hf.string2hash(out) == "4b3edb0272b02d8e18ce591304fdea1d"
Example #8
0
def test_liveshell_do_load(monkeypatch, capsys, hf):
    monkeypatch.setattr(Db.LiveShell, "cmdloop", mock_cmdloop)
    monkeypatch.setattr(Db.LiveShell, "dump_session", lambda _: True)
    dbbuddy = Db.DbBuddy()
    crash_file = br.TempFile(byte_mode=True)
    liveshell = Db.LiveShell(dbbuddy, crash_file)
    dbbuddy.server_clients["uniprot"] = Db.UniProtRestClient(dbbuddy)
    dbbuddy.server_clients["uniprot"].http_errors_file.write("Hello!")

    db_session = "%s/mock_resources/test_databasebuddy_clients/dbbuddy_save.db" % hf.resource_path
    monkeypatch.setattr("builtins.input", lambda _: db_session)
    liveshell.do_load(None)
    out, err = capsys.readouterr()
    assert "Session loaded from file.\n\n" in out

    assert dbbuddy.server_clients["uniprot"].http_errors_file.read() == ""
    headings = liveshell.get_headings()
    for heading in ['ACCN', 'DB', 'Type', 'record', 'entry_name', 'length', 'organism-id', 'organism',
                    'protein_names', 'comments', 'gi_num', 'TaxId', 'status', 'name', 'biotype',
                    'object_type', 'strand', 'assembly_name', 'name']:
        assert heading in headings

    for heading in headings:
        assert heading in ['ACCN', 'DB', 'Type', 'record', 'entry_name', 'length', 'organism-id', 'organism',
                           'protein_names', 'comments', 'gi_num', 'TaxId', 'status', 'name', 'biotype',
                           'object_type', 'strand', 'assembly_name', 'name']

    monkeypatch.setattr("builtins.input", lambda _: "/no/file/here")
    liveshell.do_load(None)
    out, err = capsys.readouterr()
    assert "Error: Unable to read the provided file. Are you sure it's a saved DbBuddy live session?\n\n" in out
Example #9
0
def test_print_trash(capsys):
    dbbuddy = Db.DbBuddy(", ".join(ACCNS[:4]))
    dbbuddy.filter_records("00", "remove")
    dbbuddy.print(group="trash_bin")
    out, err = capsys.readouterr()
    out = re.sub(" +\n", "\n", out)
    assert out == '''ACCN            DB         Type  record
Example #10
0
def test_retrieve_sequences(monkeypatch, capsys):
    def print_ncbi(_, database):
        print(database)
        return

    def print_unitpro(_):
        print("uniprot")
        return

    def print_ensembl(_):
        print("ensembl")
        return

    monkeypatch.setattr(Db.UniProtRestClient, "fetch_proteins", print_unitpro)
    monkeypatch.setattr(Db.NCBIClient, "fetch_sequences", print_ncbi)
    monkeypatch.setattr(Db.EnsemblRestClient, "fetch_nucleotide",
                        print_ensembl)

    dbbuddy = Db.DbBuddy()
    dbbuddy.databases = ["ensembl"]
    dbbuddy_hash = hash(dbbuddy)
    returned_db = Db.retrieve_sequences(dbbuddy)
    out, err = capsys.readouterr()
    assert "ensembl" in out
    assert "ncbi" not in out
    assert dbbuddy_hash == hash(dbbuddy)
    assert dbbuddy_hash == hash(returned_db)

    dbbuddy.databases = []
    Db.retrieve_sequences(dbbuddy)
    out, err = capsys.readouterr()
    assert "uniprot" in out
    assert "nucleotide" in out
    assert "protein" in out
    assert "ensembl" in out
Example #11
0
def test_print_simple(capsys):
    dbbuddy = Db.DbBuddy(", ".join(ACCNS[:4]))
    dbbuddy.print()
    out, err = capsys.readouterr()
    out = re.sub(" +\n", "\n", out)
    assert out == '''ACCN            DB         Type  record
NP_001287575.1  ncbi_prot  prot  summary
ADH10263.1      ncbi_prot  prot  summary
XP_005165403.2  ncbi_prot  prot  summary
A0A087WX72      uniprot    prot  summary
'''

    dbbuddy.print(-2)
    out, err = capsys.readouterr()
    out = re.sub(" +\n", "\n", out)
    assert out == '''ACCN            DB         Type  record
XP_005165403.2  ncbi_prot  prot  summary
A0A087WX72      uniprot    prot  summary
'''

    dbbuddy.out_format = "ids"
    dbbuddy.print()
    out, err = capsys.readouterr()
    out = re.sub(" +\n", "\n", out)
    assert out == '''NP_001287575.1
ADH10263.1
XP_005165403.2
A0A087WX72
'''

    dbbuddy.out_format = "accessions"
    dbbuddy.print()
    out, err = capsys.readouterr()
    out = re.sub(" +\n", "\n", out)
    assert out == '''NP_001287575.1
Example #12
0
def test_print_failure(capsys):
    dbbuddy = Db.DbBuddy(", ".join(ACCNS))
    failure = Db.Failure("foobar", "You just foo'd a bar")
    dbbuddy.failures[failure.hash] = failure
    dbbuddy.print()
    out, err = capsys.readouterr()
    assert err == '''# ########################## Failures ########################### #
Example #13
0
def test_ncbiclient_search_ncbi(hf, monkeypatch, capsys):
    def patch_entrez_esearch(*args, **kwargs):
        print("patch_entrez_esearch\nargs: %s\nkwargs: %s" % (args, kwargs))
        if "rettype" in kwargs:
            test_file = br.TempFile()
            test_file.write("""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE eSearchResult PUBLIC "-//NLM//DTD esearch 20060628//EN" \
"http://eutils.ncbi.nlm.nih.gov/eutils/dtd/20060628/esearch.dtd">
<eSearchResult>
    <Count>5</Count>
</eSearchResult>
""")
            handle = test_file.get_handle(mode="r")
        else:
            handle = open("%s/mock_resources/test_databasebuddy_clients/Entrez_esearch.xml" % hf.resource_path,
                          "r")
        return handle

    monkeypatch.setattr(Db.Entrez, "esearch", patch_entrez_esearch)
    monkeypatch.setattr(Db.NCBIClient, "fetch_summaries", lambda _: True)
    monkeypatch.setattr(Db, "sleep", lambda _: True)
    dbbuddy = Db.DbBuddy("XP_012618499.1")
    client = Db.NCBIClient(dbbuddy)
    dbbuddy.search_terms = []
    client.search_ncbi("protein")
    assert len(dbbuddy.records) == 1

    dbbuddy.search_terms = ["casp9"]
    client.search_ncbi("protein")
    for accn in ["XP_012618499.1", "O88738.2", "O88879.3", "Q9NR09.2", "Q13075.3"]:
        assert accn in dbbuddy.records
Example #14
0
def test_server(monkeypatch):
    dbbuddy = Db.DbBuddy(", ".join(ACCNS))
    assert type(dbbuddy.server("uniprot")) == Db.UniProtRestClient
    assert type(dbbuddy.server_clients["uniprot"]) == Db.UniProtRestClient

    assert type(dbbuddy.server("ncbi")) == Db.NCBIClient
    assert type(dbbuddy.server_clients["ncbi"]) == Db.NCBIClient

    def patch_ensembl_rest_action(*args, **kwargs):
        print("patch_ensembl_rest_action\nargs: %s\nkwargs: %s" %
              (args, kwargs))
        return {
            'species': [{
                'display_name': 'Saccharomyces cerevisiae'
            }, {
                'display_name': 'C.savignyi'
            }, {
                'display_name': 'Microbat'
            }]
        }

    monkeypatch.setattr(Db.EnsemblRestClient, "perform_rest_action",
                        patch_ensembl_rest_action)  # No internet needed
    assert type(dbbuddy.server("ensembl")) == Db.EnsemblRestClient
    assert type(dbbuddy.server_clients["ensembl"]) == Db.EnsemblRestClient

    assert type(
        dbbuddy.server("ensembl")
    ) == Db.EnsemblRestClient  # Repeat to grab previously stored client

    with pytest.raises(ValueError) as err:
        dbbuddy.server("foo")
    assert '"uniprot", "ncbi", and "ensembl" are the only valid options, not foo' in str(
        err)
Example #15
0
def test_instantiate_dbbuddy_from_handle():
    tmp_file = br.TempFile()
    tmp_file.write(", ".join(ACCNS))
    tmp_file.open("r")
    dbbuddy = Db.DbBuddy(tmp_file.handle)
    for accn in ACCNS:
        assert accn in dbbuddy.records
Example #16
0
def test_search_ensembl(monkeypatch, capsys, hf):
    def patch_ensembl_perform_rest_action(*args, **kwargs):
        print("patch_ensembl_perform_rest_action\nargs: %s\nkwargs: %s" % (args, kwargs))
        with open("%s/ensembl_species.json" % test_files, "r") as ifile:
            return json.load(ifile)

    def patch_search_ensembl_empty(*args, **kwargs):
        print("patch_search_ensembl_empty\nargs: %s\nkwargs: %s" % (args, kwargs))
        return

    def patch_search_ensembl_results(*args, **kwargs):
        print("patch_search_ensembl_empty\nargs: %s\nkwargs: %s" % (args, kwargs))
        with open("%s/ensembl_search_results.txt" % test_files, "r") as ifile:
            client.results_file.write(ifile.read())
        return

    test_files = "%s/mock_resources/test_databasebuddy_clients/" % hf.resource_path
    monkeypatch.setattr(Db.EnsemblRestClient, "perform_rest_action", patch_ensembl_perform_rest_action)
    monkeypatch.setattr(br, "run_multicore_function", patch_search_ensembl_empty)

    dbbuddy = Db.DbBuddy(", ".join(ACCNS[7:]))
    client = Db.EnsemblRestClient(dbbuddy)
    client.dbbuddy.search_terms = ["Panx3"]
    client.dbbuddy.records["ENSLAFG00000006034"] = Db.Record("ENSLAFG00000006034")
    client.search_ensembl()
    out, err = capsys.readouterr()
    assert err == "Searching Ensembl for Panx3...\nEnsembl returned no results\n"
    assert not client.dbbuddy.records["ENSLAFG00000006034"].record

    monkeypatch.setattr(br, "run_multicore_function", patch_search_ensembl_results)
    client.search_ensembl()
    assert hf.string2hash(str(client.dbbuddy)) == "95dc1ecce077bef84cdf2d85ce154eef"
    assert len(client.dbbuddy.records) == 44
    assert client.dbbuddy.records["ENSLAFG00000006034"].database == "ensembl"
Example #17
0
def test_liveshell_complete_format(monkeypatch):
    monkeypatch.setattr(Db.LiveShell, "cmdloop", mock_cmdloop)
    dbbuddy = Db.DbBuddy()
    crash_file = br.TempFile(byte_mode=True)
    liveshell = Db.LiveShell(dbbuddy, crash_file)
    assert liveshell.complete_format("f") == ['full-summary', 'fasta', 'fastq', 'fastq-sanger',
                                              'fastq-solexa', 'fastq-illumina']
Example #18
0
def test_ensembl_fetch_nucleotide(monkeypatch, capsys, hf):
    def patch_ensembl_perform_rest_action(*args, **kwargs):
        print("patch_ensembl_perform_rest_action\nargs: %s\nkwargs: %s" %
              (args, kwargs))
        if "info/species" in args:
            with open("%s/ensembl_species.json" % test_files, "r") as ifile:
                return json.load(ifile)
        elif "sequence/id" in args:
            with open("%s/ensembl_sequence.seqxml" % test_files, "r") as ifile:
                tmp_file = br.TempFile(byte_mode=True)
                tmp_file.write(ifile.read().encode())
                return Db.SeqIO.parse(tmp_file.get_handle("r"), "seqxml")

    test_files = "%s/mock_resources/test_databasebuddy_clients/" % hf.resource_path
    monkeypatch.setattr(Db.EnsemblRestClient, "perform_rest_action",
                        patch_ensembl_perform_rest_action)
    dbbuddy = Db.DbBuddy(", ".join(ACCNS[7:]))
    dbbuddy.records['ENSAMEG00000011912'] = Db.Record('ENSAMEG00000011912')
    summary = OrderedDict([('organism', 'macropus_eugenii'),
                           ('comments', 'Blahh blahh blahh'),
                           ('name', 'Foo1')])
    dbbuddy.records['ENSCJAG00000008732'].summary = summary

    client = Db.EnsemblRestClient(dbbuddy)
    client.fetch_nucleotide()

    capsys.readouterr()
    client.dbbuddy.print()
    out, err = capsys.readouterr()
    assert hf.string2hash(out + err) == "bc7610d5373db0b0fd9835410a182f10"
Example #19
0
def test_ensembl_mc_search(monkeypatch, hf):
    def patch_ensembl_perform_rest_action(*args, **kwargs):
        print("patch_ensembl_perform_rest_action\nargs: %s\nkwargs: %s" %
              (args, kwargs))
        test_files = "%s/mock_resources/test_databasebuddy_clients/" % hf.resource_path
        if "info/species" in args:
            with open("%s/ensembl_species.json" % test_files, "r") as ifile:
                return json.load(ifile)
        elif "lookup/symbol/Mouse/Panx1" in args:
            return json.loads(
                '{"id": "ENSMUSG00000031934", "end": 15045478, "seq_region_name": "9", "description": '
                '"pannexin 1 [Source:MGI Symbol;Acc:MGI:1860055]", "logic_name": "ensembl_havana_gene", '
                '"species": "Mouse", "strand": -1, "start": 15005161, "db_type": "core", "assembly_name":'
                ' "GRCm38", "biotype": "protein_coding", "version": 13, "display_name": "Panx1", '
                '"source": "ensembl_havana", "object_type": "Gene"}')

    monkeypatch.setattr(Db.EnsemblRestClient, "perform_rest_action",
                        patch_ensembl_perform_rest_action)
    dbbuddy = Db.DbBuddy(", ".join(ACCNS[7:]))
    client = Db.EnsemblRestClient(dbbuddy)
    client._mc_search('Mouse', ['Panx1'])
    assert "'description': 'pannexin 1 [Source:MGI Symbol;Acc:MGI:1860055]'" in client.results_file.read(
    )

    monkeypatch.undo()
    monkeypatch.setattr(Db, "Request", mock_raise_httperror)
    client._mc_search('Mouse', ['Panx1'])
    assert "HTTP Error 101: Fake HTTPError from Mock" in client.http_errors_file.read(
    )
Example #20
0
def test_ensembl_init(monkeypatch, hf):
    def patch_ensembl_perform_rest_action(*args, **kwargs):
        print("patch_ensembl_perform_rest_action\nargs: %s\nkwargs: %s" %
              (args, kwargs))
        test_files = "%s/mock_resources/test_databasebuddy_clients/" % hf.resource_path
        if "info/species" in args:
            with open("%s/ensembl_species.json" % test_files, "r") as ifile:
                return json.load(ifile)

    def patch_ensembl_perform_rest_action_empty(*args, **kwargs):
        print("patch_ensembl_perform_rest_action\nargs: %s\nkwargs: %s" %
              (args, kwargs))
        return {}

    monkeypatch.setattr(Db.EnsemblRestClient, "perform_rest_action",
                        patch_ensembl_perform_rest_action)
    dbbuddy = Db.DbBuddy(", ".join(ACCNS[7:]))
    client = Db.EnsemblRestClient(dbbuddy)
    assert hash(dbbuddy) == hash(client.dbbuddy)
    assert type(client.http_errors_file) == br.TempFile
    assert type(client.results_file) == br.TempFile
    assert client.max_url == 1000
    assert 'vicugnapacos' in client.species['Alpaca']['aliases']

    monkeypatch.setattr(Db.EnsemblRestClient, "perform_rest_action",
                        patch_ensembl_perform_rest_action_empty)
    client = Db.EnsemblRestClient(dbbuddy)
    assert client.species == {}
Example #21
0
def test_client_parse_error_file():
    dbbuddy = Db.DbBuddy()
    client = Db.GenericClient(dbbuddy)

    assert not client.parse_error_file()
    assert not dbbuddy.failures
    client.http_errors_file.write("Casp9\n%s\n//\n" % HTTPError(
        "101", "Fake HTTPError from Mock", "Foo", "Bar", StringIO("Baz")))
    client.http_errors_file.write("Inx1\n%s\n//\n" %
                                  URLError("Fake URLError from Mock"))

    assert client.parse_error_file() == '''Casp9
HTTP Error Fake HTTPError from Mock: Foo

Inx1
<urlopen error Fake URLError from Mock>

'''
    assert len(dbbuddy.failures) == 2

    # Repeat to make sure that the same error is not added again
    client.http_errors_file.write("Inx1\n%s\n//\n" %
                                  URLError("Fake URLError from Mock"))
    assert not client.parse_error_file()
    assert len(dbbuddy.failures) == 2
Example #22
0
def test_liveshell_do_bash(monkeypatch, capsys):
    monkeypatch.setattr(Db.LiveShell, "cmdloop", mock_cmdloop)
    dbbuddy = Db.DbBuddy()
    crash_file = br.TempFile(byte_mode=True)
    liveshell = Db.LiveShell(dbbuddy, crash_file)
    capsys.readouterr()
    tmp_file = br.TempFile()
    liveshell.do_bash("echo 'hello from bash' > %s" % tmp_file.path)
    assert "hello from bash" in tmp_file.read()

    monkeypatch.setattr(
        "builtins.input",
        lambda _: "echo 'Line from input' > %s" % tmp_file.path)
    liveshell.do_bash(None)
    assert "Line from input" in tmp_file.read()

    liveshell.do_bash("cd /this/path/doesnt/exist")
    out, err = capsys.readouterr()
    assert "-sh: cd: /this/path/doesnt/exist: No such file or directory\n" in out

    tmp_dir = br.TempDir()
    tmp_dir.subfile("foo.txt")
    cwd = os.getcwd()
    liveshell.do_bash("cd %s" % tmp_dir.path)
    out, err = capsys.readouterr()
    assert tmp_dir.path in out
    assert os.path.isfile("foo.txt")
    os.chdir(cwd)
Example #23
0
def test_uniprotrestclient_query_uniprot(capsys, monkeypatch):
    dbbuddy = Db.DbBuddy()
    client = Db.UniProtRestClient(dbbuddy)
    monkeypatch.setattr(Db, 'urlopen', mock_urlopen_handle_uniprot_ids)
    client.query_uniprot("inx15", {"format": "list"})

    assert client.results_file.read() == '''# Search: inx15
A8XEF9
O61786
A0A0H5SBJ0
//
'''
    # Also make sure request_params can come in as a list
    monkeypatch.setattr(Db, 'urlopen', mock_urlopen_handle_uniprot_ids)
    client.query_uniprot("inx15", [{"format": "list"}])

    # Errors
    monkeypatch.setattr(Db, 'urlopen', mock_raise_httperror)
    client.query_uniprot("inx15", [{"format": "list"}])
    assert client.http_errors_file.read() == "Uniprot search failed for 'inx15'\nHTTP Error 101: " \
                                             "Fake HTTPError from Mock\n//\n"

    monkeypatch.setattr(Db, 'urlopen', mock_raise_urlerror_8)
    client.query_uniprot("inx15", [{"format": "list"}])
    assert "Uniprot request failed, are you connected to the internet?" in client.http_errors_file.read()

    monkeypatch.setattr(Db, 'urlopen', mock_raise_urlerror)
    client.query_uniprot("inx15", [{"format": "list"}])
    assert "<urlopen error Fake URLError from Mock>" in client.http_errors_file.read()

    params = {"format": "tab", "columns": "id,entry name,length,organism-id,organism,protein names,comments"}
    client.query_uniprot("ABXEF9", params)
Example #24
0
def test_liveshell_complete_load_save_write(monkeypatch):
    monkeypatch.setattr(Db.LiveShell, "cmdloop", mock_cmdloop)
    dbbuddy = Db.DbBuddy()
    crash_file = br.TempFile(byte_mode=True)
    liveshell = Db.LiveShell(dbbuddy, crash_file)
    tmpdir = br.TempDir()
    os.chdir(tmpdir.path)
    tmpdir.subfile("file.txt")
    tmpdir.subdir("extra_dir")

    # Load
    assert liveshell.complete_load("load fi ", "load fi ", 5,
                                   7) == ['file.txt']
    assert liveshell.complete_load(
        "load ", "load ", 5, 5) == ['extra_dir%s' % os.path.sep, 'file.txt']
    assert not liveshell.complete_load("load ", "load ", 4, 5)

    # Save
    assert liveshell.complete_save("save fi ", "save fi ", 5,
                                   7) == ['file.txt']
    assert liveshell.complete_save(
        "save ", "save ", 5, 5) == ['extra_dir%s' % os.path.sep, 'file.txt']
    assert not liveshell.complete_save("save ", "save ", 4, 5)

    # Save
    assert liveshell.complete_write("write fi ", "write fi ", 6,
                                    8) == ['file.txt']
    assert liveshell.complete_write(
        "write ", "write ", 6, 6) == ['extra_dir%s' % os.path.sep, 'file.txt']
    assert not liveshell.complete_write("write ", "write ", 4, 5)
Example #25
0
def test_liveshell_postcmd(monkeypatch):
    monkeypatch.setattr(Db.LiveShell, "cmdloop", mock_cmdloop)
    dbbuddy = Db.DbBuddy()
    crash_file = br.TempFile(byte_mode=True)
    liveshell = Db.LiveShell(dbbuddy, crash_file)
    assert liveshell.postcmd("STOP!", "foo bar line") == "STOP!"
    assert liveshell.usage.stats['LiveShell'][Db.VERSION.short()]['foo'] == 1
Example #26
0
def test_liveshell_complete_delete(monkeypatch):
    monkeypatch.setattr(Db.LiveShell, "cmdloop", mock_cmdloop)
    dbbuddy = Db.DbBuddy()
    crash_file = br.TempFile(byte_mode=True)
    liveshell = Db.LiveShell(dbbuddy, crash_file)
    assert liveshell.complete_delete("") == [
        "all", "failures", "search", "trash", "records"
    ]