Skip to content

Commit

Permalink
Merge pull request sympy#23754 from oscarbenjamin/pr_warnings_cleanup
Browse files Browse the repository at this point in the history
Cleanup of warnings from the test suite
  • Loading branch information
oscarbenjamin authored Jul 12, 2022
2 parents de24949 + b724ba0 commit b0badca
Show file tree
Hide file tree
Showing 20 changed files with 115 additions and 99 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/runtests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ jobs:

# Install the non-Python dependencies
- run: sudo apt install antlr4 libgfortran5 gfortran libmpfr-dev libmpc-dev libopenblas-dev
- run: python -m pip install --upgrade pip wheel
- run: python -m pip install --upgrade pip wheel setuptools

# Use various libs from git for Python 3.11
- if: ${{ contains(matrix.python-version, '3.11') }}
Expand Down
6 changes: 3 additions & 3 deletions bin/test_optional_dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ class TestsFailedError(Exception):
'*aesara*',

# gmpy
'polys',
'sympy/polys',

# autowrap
'*autowrap*',
Expand Down Expand Up @@ -132,8 +132,8 @@ class TestsFailedError(Exception):
from sympy import test, doctest


tests_passed = test(*test_list, blacklist=blacklist)
doctests_passed = doctest(*doctest_list)
tests_passed = test(*test_list, blacklist=blacklist, force_colors=True)
doctests_passed = doctest(*doctest_list, force_colors=True)


if not tests_passed and not doctests_passed:
Expand Down
2 changes: 1 addition & 1 deletion doc/src/explanation/active-deprecations.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ specify this conversion was:

```py
>>> from sympy.parsing.mathematica import mathematica
>>> mathematica('F[7,5,3]', {'F[*x]': 'Max(*x)*Min(*x)'})
>>> mathematica('F[7,5,3]', {'F[*x]': 'Max(*x)*Min(*x)'}) # doctest: +SKIP
21
```

Expand Down
35 changes: 5 additions & 30 deletions examples/all.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
Obviously, we want to achieve the first result.
"""

import imp
import optparse
import os
import sys
Expand Down Expand Up @@ -86,37 +85,13 @@
EXAMPLE_DIR = os.path.dirname(__file__)


def __import__(name, globals=None, locals=None, fromlist=None):
"""An alternative to the import function so that we can import
modules defined as strings.
This code was taken from: http://docs.python.org/lib/examples-imp.html
"""
# Fast path: see if the module has already been imported.
try:
return sys.modules[name]
except KeyError:
pass

# If any of the following calls raises an exception,
# there's a problem we can't handle -- let the caller handle it.
module_name = name.split('.')[-1]
module_path = os.path.join(EXAMPLE_DIR, *name.split('.')[:-1])

fp, pathname, description = imp.find_module(module_name, [module_path])

try:
return imp.load_module(module_name, fp, pathname, description)
finally:
# Since we may exit via an exception, close fp explicitly.
if fp:
fp.close()


def load_example_module(example):
"""Loads modules based upon the given package name"""
mod = __import__(example)
return mod
from importlib import import_module

exmod = os.path.split(EXAMPLE_DIR)[1]
modname = exmod + '.' + example
return import_module(modname)


def run_examples(*, windowed=False, quiet=False, summary=True):
Expand Down
6 changes: 4 additions & 2 deletions sympy/external/tests/test_autowrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,10 @@ def runtest_issue_10274(language, backend):
assert f(1, 1, 1) == 1

for file in os.listdir(tmp):
if file.startswith("wrapped_code_") and file.endswith(".c"):
fil = open(tmp + '/' + file)
if not (file.startswith("wrapped_code_") and file.endswith(".c")):
continue

with open(tmp + '/' + file) as fil:
lines = fil.readlines()
assert lines[0] == "/******************************************************************************\n"
assert "Code generated with SymPy " + sympy.__version__ in lines[1]
Expand Down
12 changes: 6 additions & 6 deletions sympy/external/tests/test_codegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,12 +120,12 @@ def try_run(commands):
"""Run a series of commands and only return True if all ran fine."""
if pyodide_js:
return False
null = open(os.devnull, 'w')
for command in commands:
retcode = subprocess.call(command, stdout=null, shell=True,
stderr=subprocess.STDOUT)
if retcode != 0:
return False
with open(os.devnull, 'w') as null:
for command in commands:
retcode = subprocess.call(command, stdout=null, shell=True,
stderr=subprocess.STDOUT)
if retcode != 0:
return False
return True


Expand Down
19 changes: 13 additions & 6 deletions sympy/external/tests/test_numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import mpmath
from sympy.abc import x, y, z
from sympy.utilities.decorator import conserve_mpmath_dps
from sympy.utilities.exceptions import ignore_warnings
from sympy.testing.pytest import raises


Expand Down Expand Up @@ -138,9 +139,11 @@ def test_Matrix1():

def test_Matrix2():
m = Matrix([[x, x**2], [5, 2/x]])
assert (matrix(m.subs(x, 2)) == matrix([[2, 4], [5, 1]])).all()
with ignore_warnings(PendingDeprecationWarning):
assert (matrix(m.subs(x, 2)) == matrix([[2, 4], [5, 1]])).all()
m = Matrix([[sin(x), x**2], [5, 2/x]])
assert (matrix(m.subs(x, 2)) == matrix([[sin(2), 4], [5, 1]])).all()
with ignore_warnings(PendingDeprecationWarning):
assert (matrix(m.subs(x, 2)) == matrix([[sin(2), 4], [5, 1]])).all()


def test_Matrix3():
Expand All @@ -153,25 +156,29 @@ def test_Matrix3():


def test_Matrix4():
a = matrix([[2, 4], [5, 1]])
with ignore_warnings(PendingDeprecationWarning):
a = matrix([[2, 4], [5, 1]])
assert Matrix(a) == Matrix([[2, 4], [5, 1]])
assert Matrix(a) != Matrix([[2, 4], [5, 2]])
a = matrix([[sin(2), 4], [5, 1]])
with ignore_warnings(PendingDeprecationWarning):
a = matrix([[sin(2), 4], [5, 1]])
assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]])
assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]])


def test_Matrix_sum():
M = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
m = matrix([[2, 3, 4], [x, 5, 6], [x, y, z**2]])
with ignore_warnings(PendingDeprecationWarning):
m = matrix([[2, 3, 4], [x, 5, 6], [x, y, z**2]])
assert M + m == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]])
assert m + M == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]])
assert M + m == M.add(m)


def test_Matrix_mul():
M = Matrix([[1, 2, 3], [x, y, x]])
m = matrix([[2, 4], [x, 6], [x, z**2]])
with ignore_warnings(PendingDeprecationWarning):
m = matrix([[2, 4], [x, 6], [x, z**2]])
assert M*m == Matrix([
[ 2 + 5*x, 16 + 3*z**2],
[2*x + x*y + x**2, 4*x + 6*y + x*z**2],
Expand Down
5 changes: 3 additions & 2 deletions sympy/matrices/tests/test_matrices.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
from sympy.core import Tuple, Wild
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.utilities.iterables import flatten, capture, iterable
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.utilities.exceptions import ignore_warnings, SymPyDeprecationWarning
from sympy.testing.pytest import (raises, XFAIL, slow, skip,
warns_deprecated_sympy, warns)
from sympy.assumptions import Q
Expand Down Expand Up @@ -2702,7 +2702,8 @@ def test_17522_numpy():
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]

m = _matrixify(matrix([[1, 2], [3, 4]]))
with ignore_warnings(PendingDeprecationWarning):
m = _matrixify(matrix([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]

Expand Down
25 changes: 21 additions & 4 deletions sympy/plotting/tests/test_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
TextBackend, BaseBackend)
from sympy.testing.pytest import skip, raises, warns, warns_deprecated_sympy
from sympy.utilities import lambdify as lambdify_
from sympy.utilities.exceptions import ignore_warnings


unset_show()
Expand Down Expand Up @@ -383,7 +384,17 @@ def test_plot_and_save_5():
p[0].only_integers = True
p[0].steps = True
filename = 'test_advanced_fin_sum.png'
p.save(os.path.join(tmpdir, filename))

# XXX: This should be fixed in experimental_lambdify or by using
# ordinary lambdify so that it doesn't warn. The error results from
# passing an array of values as the integration limit.
#
# UserWarning: The evaluation of the expression is problematic. We are
# trying a failback method that may still work. Please report this as a
# bug.
with ignore_warnings(UserWarning):
p.save(os.path.join(tmpdir, filename))

p._backend.close()


Expand All @@ -401,8 +412,11 @@ def test_plot_and_save_6():
###
p = plot(sin(x) + I*cos(x))
p.save(os.path.join(tmpdir, filename))
p = plot(sqrt(sqrt(-x)))
p.save(os.path.join(tmpdir, filename))

with ignore_warnings(RuntimeWarning):
p = plot(sqrt(sqrt(-x)))
p.save(os.path.join(tmpdir, filename))

p = plot(LambertW(x))
p.save(os.path.join(tmpdir, filename))
p = plot(sqrt(LambertW(x)))
Expand Down Expand Up @@ -527,7 +541,10 @@ def test_issue_17405():
p = plot(f, (x, -10, 10), show=False)
# Random number of segments, probably more than 100, but we want to see
# that there are segments generated, as opposed to when the bug was present
assert len(p[0].get_data()[0]) >= 30

# RuntimeWarning: invalid value encountered in double_scalars
with ignore_warnings(RuntimeWarning):
assert len(p[0].get_data()[0]) >= 30


def test_logplot_PR_16796():
Expand Down
14 changes: 11 additions & 3 deletions sympy/plotting/tests/test_textplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from sympy.functions.elementary.trigonometric import sin
from sympy.plotting.textplot import textplot_str

from sympy.utilities.exceptions import ignore_warnings


def test_axes_alignment():
x = Symbol('x')
Expand Down Expand Up @@ -108,7 +110,9 @@ def test_singularity():
' -4 |_______________________________________________________',
' 0 0.5 1'
]
assert lines == list(textplot_str(log(x), 0, 1))
# RuntimeWarning: divide by zero encountered in log
with ignore_warnings(RuntimeWarning):
assert lines == list(textplot_str(log(x), 0, 1))


def test_sinc():
Expand Down Expand Up @@ -137,7 +141,9 @@ def test_sinc():
' -0.2 |_______________________________________________________',
' -10 0 10'
]
assert lines == list(textplot_str(sin(x)/x, -10, 10))
# RuntimeWarning: invalid value encountered in double_scalars
with ignore_warnings(RuntimeWarning):
assert lines == list(textplot_str(sin(x)/x, -10, 10))


def test_imaginary():
Expand Down Expand Up @@ -166,7 +172,9 @@ def test_imaginary():
' 0 |_______________________________________________________',
' -1 0 1'
]
assert list(textplot_str(sqrt(x), -1, 1)) == lines
# RuntimeWarning: invalid value encountered in sqrt
with ignore_warnings(RuntimeWarning):
assert list(textplot_str(sqrt(x), -1, 1)) == lines

lines = [
' 1 | ',
Expand Down
12 changes: 12 additions & 0 deletions sympy/printing/lambdarepr.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,20 @@ def _print_Piecewise(self, expr):
ans.append('where(%s, %s, ' % (cond, expr))
parenthesis_count += 1
if not is_last_cond_True:
# See https://github.com/pydata/numexpr/issues/298
#
# simplest way to put a nan but raises
# 'RuntimeWarning: invalid value encountered in log'
#
# There are other ways to do this such as
#
# >>> import numexpr as ne
# >>> nan = float('nan')
# >>> ne.evaluate('where(x < 0, -1, nan)', {'x': [-1, 2, 3], 'nan':nan})
# array([-1., nan, nan])
#
# That needs to be handled in the lambdified function though rather
# than here in the printer.
ans.append('log(-1)')
return ''.join(ans) + ')' * parenthesis_count

Expand Down
10 changes: 7 additions & 3 deletions sympy/printing/tests/test_aesaracode.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
from sympy.external import import_module
from sympy.testing.pytest import raises, SKIP

from sympy.utilities.exceptions import ignore_warnings


aesaralogger = logging.getLogger('aesara.configdefaults')
aesaralogger.setLevel(logging.CRITICAL)
aesara = import_module('aesara')
Expand Down Expand Up @@ -272,9 +275,10 @@ def test_factorial():
assert aesara_code_(sy.factorial(n))

def test_Derivative():
simp = lambda expr: aesara_simplify(fgraph_of(expr))
assert theq(simp(aesara_code_(sy.Derivative(sy.sin(x), x, evaluate=False))),
simp(aesara.grad(aet.sin(xt), xt)))
with ignore_warnings(UserWarning):
simp = lambda expr: aesara_simplify(fgraph_of(expr))
assert theq(simp(aesara_code_(sy.Derivative(sy.sin(x), x, evaluate=False))),
simp(aesara.grad(aet.sin(xt), xt)))


def test_aesara_function_simple():
Expand Down
4 changes: 1 addition & 3 deletions sympy/printing/tests/test_lambdarepr.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,14 +210,12 @@ def test_numexpr():

from sympy.codegen.ast import Return, FunctionDefinition, Variable, Assignment
func_def = FunctionDefinition(None, 'foo', [Variable(x)], [Assignment(y,x), Return(y**2)])
print("")
print(NumExprPrinter().doprint(func_def))
expected = "def foo(x):\n"\
" y = numexpr.evaluate('x', truediv=True)\n"\
" return numexpr.evaluate('y**2', truediv=True)"
print(expected)
assert NumExprPrinter().doprint(func_def) == expected


class CustomPrintedObject(Expr):
def _lambdacode(self, printer):
return 'lambda'
Expand Down
2 changes: 1 addition & 1 deletion sympy/testing/runtests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2030,7 +2030,7 @@ def findout_terminal_width():
process = subprocess.Popen(['stty', '-a'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout = process.stdout.read()
stdout, stderr = process.communicate()
stdout = stdout.decode("utf-8")
except OSError:
pass
Expand Down
6 changes: 4 additions & 2 deletions sympy/utilities/_compilation/compilation.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,15 +535,17 @@ def _write_sources_to_build_dir(sources, build_dir):
sha256_in_mem = sha256_of_string(src.encode('utf-8')).hexdigest()
if os.path.exists(dest):
if os.path.exists(dest + '.sha256'):
sha256_on_disk = open(dest + '.sha256').read()
with open(dest + '.sha256') as fh:
sha256_on_disk = fh.read()
else:
sha256_on_disk = sha256_of_file(dest).hexdigest()

differs = sha256_on_disk != sha256_in_mem
if differs:
with open(dest, 'wt') as fh:
fh.write(src)
open(dest + '.sha256', 'wt').write(sha256_in_mem)
with open(dest + '.sha256', 'wt') as fh:
fh.write(sha256_in_mem)
source_files.append(dest)
return source_files, build_dir

Expand Down
Loading

0 comments on commit b0badca

Please sign in to comment.