Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure XML files are opened with UTF-8 encoding #580

Merged
merged 1 commit into from
Aug 30, 2024

Conversation

mattwthompson
Copy link
Member

PR Summary:

This PR ensures XML files are opened in UTF-8 mode while being processed. The background here is ... messy and hard to reproduce. What I'm fairly sure of is that my testing infrastructure writes some temporary files (including Foyer XML files) and something might be loaded under an assumption of ASCII encoding. This causes a crash similar to forcing that behavior:

>>> open('oplsaa.xml', encoding='ascii').read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mattthompson/micromamba/envs/new-models/lib/python3.11/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 56770: ordinal not in range(128)

This is because of the fancy (unicode) $\alpha$ here:

In [1]: alpha = '\u03b1'

In [2]: alpha
Out[2]: 'α'

In [3]: alpha.encode("utf-8")
Out[3]: b'\xce\xb1'

In [4]: alpha.encode("ascii")
---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
Cell In[4], line 1
----> 1 alpha.encode("ascii")

UnicodeEncodeError: 'ascii' codec can't encode character '\u03b1' in position 0: ordinal not in range(128)

AFAICT, Python 3 defaults to open()ing files in UTF-8 mode, so this change shouldn't impact anything but esoteric cases like I've run into. (Handwaving more, it's a fixture that crashes only at collection time and only when using pytest-xdist.) This would be tricky for me to write a unit test for, but I can take a stab at it if desired.

PR Checklist


  • Includes appropriate unit test(s)
  • Appropriate docstring(s) are added/updated
  • Code is (approximately) PEP8 compliant
  • Issue(s) raised/addressed?

foyer/forcefield.py Fixed Show resolved Hide resolved
@mattwthompson mattwthompson marked this pull request as ready for review August 22, 2024 18:53
@chrisjonesBSU
Copy link
Contributor

chrisjonesBSU commented Aug 23, 2024

I'm trying to rerun the tests, but they keep getting skipped..

If I run the tests locally I'm getting an error:

============================================= ERRORS =============================================
__________________________ ERROR collecting foyer/tests/test_trappe.py ___________________________
tests/test_trappe.py:13: in <module>
    TRAPPE_UA = Forcefield(name="trappe-ua")
forcefield.py:522: in __init__
    preprocessed_files = preprocess_forcefield_files(all_files_to_load)
forcefield.py:80: in preprocess_forcefield_files
    xml_contents = f.read()
E   ValueError: I/O operation on closed file.
======================================== warnings summary ========================================
../../../../miniconda3/envs/foyer-dev/lib/python3.12/site-packages/mdtraj/formats/__init__.py:13
  /home/chris/miniconda3/envs/foyer-dev/lib/python3.12/site-packages/mdtraj/formats/__init__.py:13: DeprecationWarning: 'xdrlib' is deprecated and slated for removal in Python 3.13
    from mdtraj.formats.trr import TRRTrajectoryFile

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
---------- generated Nunit xml file: /home/chris/cme/repos/foyer/foyer/test-output.xml -----------
==================================== short test summary info =====================================
ERROR tests/test_trappe.py - ValueError: I/O operation on closed file.

It looks like calling f.close() under the try/finally statements is causing an issue since a few lines later we call f.read() again.

  67     for xml_file in forcefield_files:
  68         if not hasattr(xml_file, "read"):
  69             try:
  70                 f = open(xml_file, encoding="utf-8")
  71             finally:
  72                 f.close()
  73
  74             _, suffix = os.path.split(xml_file)
  75         else:
  76             f = xml_file
  77             suffix = ""
  78
  79         # read and preprocess
  80         xml_contents = f.read()
  81         f.close()

@mattwthompson mattwthompson marked this pull request as draft August 23, 2024 16:47
@mattwthompson
Copy link
Member Author

Strange to see .NET stuff float in!

------------------------ generated Nunit xml file: /Users/mattthompson/software/foyer/test-output.xml -------------------------

@mattwthompson mattwthompson marked this pull request as ready for review August 23, 2024 17:38
@mattwthompson mattwthompson reopened this Aug 23, 2024
Copy link

codecov bot commented Aug 23, 2024

Codecov Report

Attention: Patch coverage is 80.00000% with 1 line in your changes missing coverage. Please review.

Project coverage is 62.04%. Comparing base (77ca8c0) to head (2707210).
Report is 8 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #580      +/-   ##
==========================================
+ Coverage   62.01%   62.04%   +0.02%     
==========================================
  Files          16       16              
  Lines        1664     1665       +1     
==========================================
+ Hits         1032     1033       +1     
  Misses        632      632              

Copy link
Contributor

@chrisjonesBSU chrisjonesBSU left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks!

environment-dev.yml Show resolved Hide resolved
Copy link
Contributor

@CalCraven CalCraven left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ran tests locally on my end as well here and it looks good, so I'm going to merge this one.

@CalCraven CalCraven merged commit 469712f into mosdef-hub:main Aug 30, 2024
16 checks passed
@mattwthompson
Copy link
Member Author

Thanks @CalCraven and @chrisjonesBSU!

@mattwthompson mattwthompson deleted the utf-8-xml branch August 30, 2024 13:41
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.

3 participants