Skip to content

Adding SimpleFastaParser and FastaTwoLineParser unit tests - #1810

Merged
peterjc merged 4 commits into
biopython:masterfrom
chris-rands:simpleFasterTests
Oct 1, 2018
Merged

peterjc merged 4 commits into
biopython:masterfrom
chris-rands:simpleFasterTests

Conversation

@chris-rands

Copy link
Copy Markdown
Contributor

Apologies Peter for giving you so many reviewing tasks, but I just wanted to tie up the lose end from PR #1808 while it is fresh in my mind, the extra unit tests. SimpleFastaParser and FastaTwoLineParser were previously not tested directly anywhere in the Biopython test suite, this addresses that and includes some non-intuitive edge-cases. Hopefully, it is fairly straightforward.

  • I hereby agree to dual licence this and any previous contributions under both
    the Biopython License Agreement AND the BSD 3-Clause License.

  • I have read the CONTRIBUTING.rst file and understand that AppVeyor and
    TravisCI will be used to confirm the Biopython unit tests and flake8 style
    checks pass with these changes.

  • I have added my name to the alphabetical contributors listings in the files
    NEWS.rst and CONTRIB.rst as part of this pull request, am listed
    already, or do not wish to be listed. (This acknowledgement is optional.)

@codecov

codecov Bot commented Sep 29, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #1810 into master will increase coverage by <.01%.
The diff coverage is 100%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #1810      +/-   ##
==========================================
+ Coverage   85.33%   85.34%   +<.01%     
==========================================
  Files         301      301              
  Lines       49197    49195       -2     
==========================================
+ Hits        41984    41987       +3     
+ Misses       7213     7208       -5
Impacted Files Coverage Δ
Bio/SeqIO/FastaIO.py 73.17% <100%> (+2.77%) ⬆️
Bio/Blast/NCBIWWW.py 13.09% <0%> (+1.19%) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 8ef1e35...3937119. Read the comment docs.

@chris-rands

Copy link
Copy Markdown
Contributor Author

Changed and simplified FastaTwoLineParser to correctly handle the case of where a new-line character is the only thing on the sequence line (it still throws an exception in the absence of a sequence line, unlike SimpleFastaParser). Also improved the unit tests. Note that although the code coverage isn't really changing, some of these edge cases were not tested before, not even indirectly. Hopefully this is okay now?

@peterjc

peterjc commented Oct 1, 2018

Copy link
Copy Markdown
Member

What happened to the exceptions for a two-line-per-record FASTA file ending after the > line without a sequence line? i.e. Why does the last commit remove these exceptions?

@peterjc

peterjc commented Oct 1, 2018

Copy link
Copy Markdown
Member

I should have started with: The additional explicit tests are very welcome, thank you.

@chris-rands

Copy link
Copy Markdown
Contributor Author

Thanks Peter, if I understand you correctly, then I think this case still raises an exception. When the file ends on a title/header line starting with >, then I think this should be caught by the final index check:

if idx % 2 == 0:  # on a header line
    raise ValueError("Should be at end of file, but line= '{}'".format(line))

For example:

>>> from Bio._py3k import StringIO
>>> from Bio.SeqIO.FastaIO import FastaTwoLineParser
>>> handle = StringIO(">1")
>>> list(FastaTwoLineParser(handle))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/path/.local/lib/python3.6/site-packages/Bio/SeqIO/FastaIO.py", line 117, in FastaTwoLineParser
    raise ValueError("Should be at end of file, but line= '{}'".format(line))
ValueError: Should be at end of file, but line= '>1'

This is tested in the new tests I added for test_exceptions_FastaTwoLineParser.

Would it be clearer and more explicit to replace the final index check with this?

if idx == -1:
    pass  # empty file
elif idx % 2 == 0:  # on a title line
    assert line[0] == '>', "line[0] != '>' ; this should be impossible!"
    raise ValueError("Missing sequence line at end of file "
                     "if this is strict two-line-per-record FASTA format. "
                     "Have title line '{}'".format(line))
else:
    assert line[0] != '>', "line[0] == '>' ; this should be impossible!"

Or did I make a mistake in my logic?

@peterjc

peterjc commented Oct 1, 2018

Copy link
Copy Markdown
Member

That looks clearer I think (although remove the first assert, just do the raise).

@peterjc

peterjc commented Oct 1, 2018

Copy link
Copy Markdown
Member

I must have missed this in the original PR, but I focused on the multi-line FASTA parser.

Looking at this test case:

    ins_two_line_edges = [">\nACGT", ">1\n\n",
                          ">1>1\n\n>1\n\n", ""]
    outs_two_line_edges = [[("", "ACGT")], [("1", "")],
                           [("1>1", ""), ("1", "")], []]
...

     def test_regular_FastaTwoLineParser(self):
         """Test regular FastaTwoLineParser cases."""
         for inp, out in zip(self.ins_two_line, self.outs_two_line):
             handle1 = StringIO(inp)
             handle2 = StringIO(inp + '\n')
             self.assertEqual(list(FastaTwoLineParser(handle1)), out)
             self.assertEqual(list(FastaTwoLineParser(handle2)), out)

The result of parsing inp and inp + '\n' should not in general be the same, but it seems the original parser was also tolerant of a missing new line at the end of the file, or trailing blank line at the end of the file.

Looking at this now:

  • ">\nACGT" <-- missing tailing new line, I expect a warning or error
  • ">\nACGT\n" <-- good
  • ">1\n\n" <- good (zero length sequence)
  • ">1\n\n\n" <- bad, extra blank line, expect an error
  • ">1>1\n\n>1\n\n" <-- good (two zero length seqs)
  • ">1>1\n\n>1\n\n\n" <-- bad, extra blank line, expect an error
  • "" <-- good (empty file, no sequences)
  • "\n" <-- bad, single blank line, expect an error

Given I've accidentally set a tolerant precedent (which you have sensibly followed), perhaps we should leave it as is, or at most add warnings for these?

@chris-rands

Copy link
Copy Markdown
Contributor Author

Thanks, sorry if my tests added some confusion; you quoted the ins_two_line_edges list but the tests you quoted are for the regular ins_two_line. Note the test_edgecases_FastaTwoLineParser does not include inp + '\n'. So apart from the first bullet point ">\nACGT", all those tests do perform as you expect (see below).

For this case where the last line is a valid sequence line but lacks a new-line \n character (which also is tested in test_regular_FastaTwoLineParser as you said), maybe we should add a warning then, but it's your call of course, what kind of warning would it be?

>>> from Bio._py3k import StringIO
>>> from Bio.SeqIO.FastaIO import FastaTwoLineParser
>>> 
>>> #">\nACGT" <-- missing tailing new line, I expect a warning or error
... list(FastaTwoLineParser(StringIO(">\nACGT")))
[('', 'ACGT')]
>>> 
>>> #">\nACGT\n" <-- good
... list(FastaTwoLineParser(StringIO(">\nACGT\n")))
[('', 'ACGT')]
>>> 
>>> #">1\n\n" <- good (zero length sequence)
... list(FastaTwoLineParser(StringIO(">1\n\n")))
[('1', '')]
>>> 
>>> #">1\n\n\n" <- bad, extra blank line, expect an error
... list(FastaTwoLineParser(StringIO(">1\n\n\n")))
ValueError: Expected FASTA record starting with '>' character. Perhaps this file is using FASTA line wrapping? Got: '
'
>>> 
>>> #">1>1\n\n>1\n\n" <-- good (two zero length seqs)
... list(FastaTwoLineParser(StringIO(">1>1\n\n>1\n\n")))
[('1>1', ''), ('1', '')]
>>> 
>>> #">1>1\n\n>1\n\n\n" <-- bad, extra blank line, expect an error
... list(FastaTwoLineParser(StringIO(">1>1\n\n>1\n\n\n")))
ValueError: Expected FASTA record starting with '>' character. Perhaps this file is using FASTA line wrapping? Got: '
'
>>> 
>>> #"" <-- good (empty file, no sequences)
... list(FastaTwoLineParser(StringIO("")))
[]
>>> 
>>> #"\n" <-- bad, single blank line, expect an error
... list(FastaTwoLineParser(StringIO("\n")))
ValueError: Expected FASTA record starting with '>' character. Perhaps this file is using FASTA line wrapping? Got: '
'

@chris-rands

Copy link
Copy Markdown
Contributor Author

Also, just to be sure, this is only for the FastaTwoLineParser yes? The SimpleFastaParser (multi-line) currently never raises an error or warning for any inputs and will always treat inp and inp + '\n' the same I think.

@peterjc

peterjc commented Oct 1, 2018

Copy link
Copy Markdown
Member

Yes, the multi-line SimpleFastaParser shouldn't care about blank lines (although failing to end the file with a new line character is perhaps still worth warning about - it causes trouble if you were to concatenate files at the command line for example - but this applies to most of the text file formats)

@peterjc

peterjc commented Oct 1, 2018

Copy link
Copy Markdown
Member

Thanks, sorry if my tests added some confusion; you quoted the ins_two_line_edges list but the tests you quoted are for the regular ins_two_line. Note the test_edgecases_FastaTwoLineParser does not include inp + '\n'. So apart from the first bullet point ">\nACGT", all those tests do perform as you expect (see below).

Ah yes, you're quite right. My mistake:

    ins_two_line = [">1\nACGT", ">1\nACGT",
                    ">1\nACGT\n>2\nACGT"]

Yes, what I've picked up on is a pre-existing ambiguity about missing the final new line.

@peterjc

peterjc commented Oct 1, 2018

Copy link
Copy Markdown
Member

I'll let AppVeyor finish its tests, but this looks OK to merge. The new release will be more rigorous than the current 2-line FASTA parser 👍

@chris-rands

Copy link
Copy Markdown
Contributor Author

One last thing, should we add a note to these unit test lines like this?

handle2 = StringIO(inp + '\n')  #  This could raise a warning in future? see PR #1810

@peterjc

peterjc commented Oct 1, 2018

Copy link
Copy Markdown
Member

Maybe just open a new issue for a new warning when parsing plain text files without a final new line character? e.g. FASTA, FASTQ, EMBL, GenBank, Swiss, ....

The rational here is files in all those file formats can in principle be concatenated to make a larger multi-record file, but that breaks if a child file's final \n is missing.

@peterjc
peterjc merged commit d7dc453 into biopython:master Oct 1, 2018
@peterjc

peterjc commented Oct 1, 2018

Copy link
Copy Markdown
Member

Merged, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants