Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,9 @@ Other Changes and Additions
- Where appropriate, tests are now run both with and without the
``unicode_literals`` option to ensure that we support both cases. [#1962]

- Added support for numerical comparison of floating point values appearing in
the output of doctests using a ``+FLOAT_CMP`` doctest flag. [#2087]

- A monkey patch is performed to fix a bug in Numpy version 1.7 and
earlier where unicode fill values on masked arrays are not
supported. This may cause unintended side effects if your
Expand Down
4 changes: 2 additions & 2 deletions astropy/constants/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
>>> # ... define the mass of something you want the rest energy of as m ...
>>> m = m_e
>>> E = m * c**2
>>> E.to('MeV')
<Quantity 0.51099... MeV>
>>> E.to('MeV') # doctest: +FLOAT_CMP
<Quantity 0.510998927603161 MeV>

"""
from __future__ import (absolute_import, division, print_function,
Expand Down
4 changes: 2 additions & 2 deletions astropy/coordinates/sky_coordinate.py
Original file line number Diff line number Diff line change
Expand Up @@ -683,8 +683,8 @@ def position_angle(self, other):
>>> c1.position_angle(c2).degree
90.0
>>> c3 = SkyCoord(1*u.deg, 1*u.deg)
>>> c1.position_angle(c3).degree
44.9956...
>>> c1.position_angle(c3).degree # doctest: +FLOAT_CMP
44.995636455344844
"""
from . import angle_utilities

Expand Down
166 changes: 166 additions & 0 deletions astropy/tests/output_checker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
"""
Implements a replacement for `doctest.OutputChecker` that handles certain
normalizations of Python expression output. See the docstring on
`AstropyOutputChecker` for more details.
"""

from __future__ import (absolute_import, division, print_function,
unicode_literals)

import doctest
import re

# Much of this code, particularly the parts of floating point handling, is
# borrowed from the SymPy project with permission. See licenses/SYMPY.rst
# for the full SymPy license.

FIX = doctest.register_optionflag('FIX')
FLOAT_CMP = doctest.register_optionflag('FLOAT_CMP')


class AstropyOutputChecker(doctest.OutputChecker):
"""
- Removes u'' prefixes on string literals
- Ignores the 'L' suffix on long integers
- In Numpy dtype strings, removes the leading pipe, i.e. '|S9' ->
'S9'. Numpy 1.7 no longer includes it in display.
- Supports the FLOAT_CMP flag, which parses floating point values
out of the output and compares their numerical values rather than their
string representation. This naturally supports complex numbers as well
(simply by comparing their real and imaginary parts separately).
"""

_original_output_checker = doctest.OutputChecker

_str_literal_re = re.compile(
r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE)
_byteorder_re = re.compile(
r"([\'\"])[|<>]([biufcSaUV][0-9]+)([\'\"])", re.UNICODE)
_fix_32bit_re = re.compile(
r"([\'\"])([iu])[48]([\'\"])", re.UNICODE)
_long_int_re = re.compile(
r"([0-9]+)L", re.UNICODE)

def __init__(self):
# NOTE OutputChecker is an old-style class with no __init__ method,
# so we can't call the base class version of __init__ here

got_floats = r'(\d+\.\d*|\.\d+)'

# floats in the 'want' string may contain ellipses
want_floats = got_floats + r'(\.{3})?'

front_sep = r'\s|[+*,(<-]'
back_sep = front_sep + r'|[)>je]'

fbeg = r'^%s(?=%s|$)' % (got_floats, back_sep)
fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, got_floats, back_sep)
self.num_got_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend))

fbeg = r'^%s(?=%s|$)' % (want_floats, back_sep)
fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, want_floats, back_sep)
self.num_want_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend))

def do_fixes(self, want, got):
want = re.sub(self._str_literal_re, r'\1\2', want)
want = re.sub(self._byteorder_re, r'\1\2\3', want)
want = re.sub(self._fix_32bit_re, r'\1\2\3', want)
want = re.sub(self._long_int_re, r'\1', want)

got = re.sub(self._str_literal_re, r'\1\2', got)
got = re.sub(self._byteorder_re, r'\1\2\3', got)
got = re.sub(self._fix_32bit_re, r'\1\2\3', got)
got = re.sub(self._long_int_re, r'\1', got)

return want, got

def normalize_floats(self, want, got, flags):
"""
Alternative to the built-in check_output that also handles parsing
float values and comparing their numeric values rather than their
string representations.

This requires rewriting enough of the basic check_output that, when
FLOAT_CMP is enabled, it totally takes over for check_output.
"""

# Handle the common case first, for efficiency:
# if they're string-identical, always return true.
if got == want:
return True

# TODO parse integers as well ?
# Parse floats and compare them. If some of the parsed floats contain
# ellipses, skip the comparison.
matches = self.num_got_rgx.finditer(got)
numbers_got = [match.group(1) for match in matches] # list of strs
matches = self.num_want_rgx.finditer(want)
numbers_want = [match.group(1) for match in matches] # list of strs
if len(numbers_got) != len(numbers_want):
return False

if len(numbers_got) > 0:
nw_ = []
for ng, nw in zip(numbers_got, numbers_want):
if '...' in nw:
nw_.append(ng)
continue
else:
nw_.append(nw)

if abs(float(ng)-float(nw)) > 1e-5:
return False

got = self.num_got_rgx.sub(r'%s', got)
got = got % tuple(nw_)

# <BLANKLINE> can be used as a special sequence to signify a
# blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
if not (flags & doctest.DONT_ACCEPT_BLANKLINE):
# Replace <BLANKLINE> in want with a blank line.
want = re.sub('(?m)^%s\s*?$' % re.escape(doctest.BLANKLINE_MARKER),
'', want)
# If a line in got contains only spaces, then remove the
# spaces.
got = re.sub('(?m)^\s*?$', '', got)
if got == want:
return True

# This flag causes doctest to ignore any differences in the
# contents of whitespace strings. Note that this can be used
# in conjunction with the ELLIPSIS flag.
if flags & doctest.NORMALIZE_WHITESPACE:
got = ' '.join(got.split())
want = ' '.join(want.split())
if got == want:
return True

# The ELLIPSIS flag says to let the sequence "..." in `want`
# match any substring in `got`.
if flags & doctest.ELLIPSIS:
if doctest._ellipsis_match(want, got):
return True

# We didn't find any match; return false.
return False

def check_output(self, want, got, flags):
if flags & FIX:
want, got = self.do_fixes(want, got)

if flags & FLOAT_CMP:
return self.normalize_floats(want, got, flags)

# Can't use super here because doctest.OutputChecker is not a
# new-style class.
return self._original_output_checker.check_output(
self, want, got, flags)

def output_difference(self, want, got, flags):
if flags & FIX:
want, got = self.do_fixes(want, got)

# Can't use super here because doctest.OutputChecker is not a
# new-style class.
return self._original_output_checker.output_difference(
self, want, got, flags)
55 changes: 2 additions & 53 deletions astropy/tests/pytest_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from .helper import (
pytest, treat_deprecations_as_exceptions, enable_deprecations_as_exceptions)
from .disable_internet import turn_off_internet, turn_on_internet
from .output_checker import AstropyOutputChecker, FIX, FLOAT_CMP

# these pytest hooks allow us to mark tests and run the marked tests with
# specific command line options.
Expand Down Expand Up @@ -60,62 +61,10 @@ def pytest_addoption(parser):
default=False)


class OutputCheckerFix(doctest.OutputChecker):
"""
A special doctest OutputChecker that normalizes a number of things common
to astropy doctests.

- Removes u'' prefixes on string literals
- In Numpy dtype strings, removes the leading pipe, i.e. '|S9' ->
'S9'. Numpy 1.7 no longer includes it in display.
"""

_literal_re = re.compile(
r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE)
_remove_byteorder = re.compile(
r"([\'\"])[|<>]([biufcSaUV][0-9]+)([\'\"])", re.UNICODE)
_fix_32bit = re.compile(
r"([\'\"])([iu])[48]([\'\"])", re.UNICODE)
_ignore_long_int = re.compile(
r"([0-9]+)L", re.UNICODE)

_original_output_checker = doctest.OutputChecker

def do_fixes(self, want, got):
want = re.sub(self._literal_re, r'\1\2', want)
want = re.sub(self._remove_byteorder, r'\1\2\3', want)
want = re.sub(self._fix_32bit, r'\1\2\3', want)
want = re.sub(self._ignore_long_int, r'\1', want)

got = re.sub(self._literal_re, r'\1\2', got)
got = re.sub(self._remove_byteorder, r'\1\2\3', got)
got = re.sub(self._fix_32bit, r'\1\2\3', got)
got = re.sub(self._ignore_long_int, r'\1', got)

return want, got

def check_output(self, want, got, flags):
if flags & FIX:
want, got = self.do_fixes(want, got)
# Can't use super here because doctest.OutputChecker is not a
# new-style class.
return self._original_output_checker.check_output(
self, want, got, flags)

def output_difference(self, want, got, flags):
if flags & FIX:
want, got = self.do_fixes(want, got)
# Can't use super here because doctest.OutputChecker is not a
# new-style class.
return self._original_output_checker.output_difference(
self, want, got, flags)


# We monkey-patch in our replacement doctest OutputChecker. Not
# great, but there isn't really an API to replace the checker when
# using doctest.testfile, unfortunately.
FIX = doctest.register_optionflag('FIX')
doctest.OutputChecker = OutputCheckerFix
doctest.OutputChecker = AstropyOutputChecker


REMOTE_DATA = doctest.register_optionflag('REMOTE_DATA')
Expand Down
34 changes: 34 additions & 0 deletions astropy/tests/tests/test_run_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
from __future__ import (absolute_import, division, print_function,
unicode_literals)

import doctest

from textwrap import dedent

# test helper.run_tests function

from ... extern import six
Expand Down Expand Up @@ -44,3 +48,33 @@ def test_run_after_2to3():

def test_unicode_literal_conversion():
assert isinstance('ångström', six.text_type)


def test_doctest_float_replacement(tmpdir):
test1 = dedent("""
This will demonstrate a doctest that fails due to a few extra decimal
places::

>>> 1.0 / 3.0
0.333333333333333311
""")

test2 = dedent("""
This is the same test, but it should pass with use of
+FLOAT_CMP::

>>> 1.0 / 3.0 # doctest: +FLOAT_CMP
0.333333333333333311
""")

test1_rst = tmpdir.join('test1.rst')
test2_rst = tmpdir.join('test2.rst')
test1_rst.write(test1)
test2_rst.write(test2)

with pytest.raises(doctest.DocTestFailure):
doctest.testfile(str(test1_rst), module_relative=False,
raise_on_error=True, verbose=False, encoding='utf-8')

doctest.testfile(str(test2_rst), module_relative=False,
raise_on_error=True, verbose=False, encoding='utf-8')
4 changes: 2 additions & 2 deletions astropy/units/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -399,8 +399,8 @@ def set_enabled_equivalencies(equivalencies):
>>> from astropy import units as u
>>> with u.set_enabled_equivalencies(u.dimensionless_angles()):
... phase = 0.5 * u.cycle
... np.exp(1j*phase) # doctest: +ELLIPSIS
<Quantity (-1+...j)>
... np.exp(1j*phase) # doctest: +FLOAT_CMP
<Quantity (-1+1.2246063538223773e-16j)>
"""
# get a context with a new registry, using all units of the current one
context = _UnitContext(get_current_unit_registry().all_units)
Expand Down
34 changes: 18 additions & 16 deletions astropy/units/equivalencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,8 @@ def doppler_radio(rest):
>>> radio_CO_equiv = u.doppler_radio(CO_restfreq)
>>> measured_freq = 115.2832*u.GHz
>>> radio_velocity = measured_freq.to(u.km/u.s, equivalencies=radio_CO_equiv)
>>> radio_velocity
<Quantity -31.209092... km / s>
>>> radio_velocity # doctest: +FLOAT_CMP
<Quantity -31.209092088877583 km / s>
"""

ckms = _si.c.to('km/s').value
Expand Down Expand Up @@ -271,8 +271,8 @@ def doppler_optical(rest):
>>> optical_CO_equiv = u.doppler_optical(CO_restfreq)
>>> measured_freq = 115.2832*u.GHz
>>> optical_velocity = measured_freq.to(u.km/u.s, equivalencies=optical_CO_equiv)
>>> optical_velocity
<Quantity -31.205843... km / s>
>>> optical_velocity # doctest: +FLOAT_CMP
<Quantity -31.20584348799674 km / s>
"""

ckms = _si.c.to('km/s').value
Expand Down Expand Up @@ -337,15 +337,15 @@ def doppler_relativistic(rest):
>>> relativistic_CO_equiv = u.doppler_relativistic(CO_restfreq)
>>> measured_freq = 115.2832*u.GHz
>>> relativistic_velocity = measured_freq.to(u.km/u.s, equivalencies=relativistic_CO_equiv)
>>> relativistic_velocity
<Quantity -31.207467619...
>>> relativistic_velocity # doctest: +FLOAT_CMP
<Quantity -31.207467619351537 km / s>
>>> measured_velocity = 1250 * u.km/u.s
>>> relativistic_frequency = measured_velocity.to(u.GHz, equivalencies=relativistic_CO_equiv)
>>> relativistic_frequency
<Quantity 114.7915686...
>>> relativistic_frequency # doctest: +FLOAT_CMP
<Quantity 114.79156866993588 GHz>
>>> relativistic_wavelength = measured_velocity.to(u.mm, equivalencies=relativistic_CO_equiv)
>>> relativistic_wavelength
<Quantity 2.6116243681...
>>> relativistic_wavelength # doctest: +FLOAT_CMP
<Quantity 2.6116243681798923 mm>
"""

ckms = _si.c.to('km/s').value
Expand Down Expand Up @@ -433,17 +433,19 @@ def brightness_temperature(beam_area, disp):
>>> from astropy import units as u
>>> beam_area = np.pi*(50*u.arcsec)**2
>>> freq = 5*u.GHz
>>> u.Jy.to(u.K, equivalencies=u.brightness_temperature(beam_area,freq))
7.052588858...
>>> (1*u.Jy).to(u.K, equivalencies=u.brightness_temperature(beam_area,freq))
<Quantity 7.05258...
>>> equiv = u.brightness_temperature(beam_area, freq)
>>> u.Jy.to(u.K, equivalencies=equiv) # doctest: +FLOAT_CMP
7.052588858846446
>>> (1*u.Jy).to(u.K, equivalencies=equiv) # doctest: +FLOAT_CMP
<Quantity 7.052588858846446 K>

VLA synthetic beam::

>>> beam_area = np.pi*(15*u.arcsec)**2
>>> freq = 5*u.GHz
>>> u.Jy.to(u.K, equivalencies=u.brightness_temperature(beam_area,freq))
78.36209843...
>>> equiv = u.brightness_temperature(beam_area, freq)
>>> u.Jy.to(u.K, equivalencies=equiv) # doctest: +FLOAT_CMP
78.36209843162719
"""
beam = beam_area.to(si.sr).value
nu = disp.to(si.GHz, spectral())
Expand Down
Loading