Skip to content

Commit

Permalink
Ignores Python 2 import_recipe() warnings
Browse files Browse the repository at this point in the history
Python 2 raises warnings on `imp.load_source()` when the module name
contains dots. Ignoring this warning makes p4a output/logs more
readable.
Note that for some reason the regression test will only catch the
regression if ran isolated, e.g. via:
```sh
tox -e py27 -- tests/test_recipe.py::TestRecipe::test_import_recipe
```
  • Loading branch information
AndreMiras committed Apr 6, 2019
1 parent 6b12281 commit 91a22ee
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
11 changes: 10 additions & 1 deletion pythonforandroid/recipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,16 @@
# this import is necessary to keep imp.load_source from complaining :)
if PY2:
import imp
import_recipe = imp.load_source
import warnings

def import_recipe(module, filename):
with warnings.catch_warnings():
# ignores warnings raised by hierarchical module names
# (names containing dots) on Python 2
warnings.simplefilter("ignore", RuntimeWarning)
return imp.load_source(module, filename)
else:
# Python 3.5+
import importlib.util
if hasattr(importlib.util, 'module_from_spec'):
def import_recipe(module, filename):
Expand All @@ -34,6 +42,7 @@ def import_recipe(module, filename):
spec.loader.exec_module(mod)
return mod
else:
# Python 3.3 and 3.4:
from importlib.machinery import SourceFileLoader

def import_recipe(module, filename):
Expand Down
19 changes: 18 additions & 1 deletion tests/test_recipe.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import os
import types
import unittest
import warnings
from pythonforandroid.build import Context
from pythonforandroid.recipe import Recipe
from pythonforandroid.recipe import Recipe, import_recipe


class TestRecipe(unittest.TestCase):
Expand Down Expand Up @@ -41,3 +43,18 @@ def test_get_recipe(self):
Recipe.get_recipe(recipe_name, ctx)
self.assertEqual(
e.exception.args[0], 'Recipe does not exist: {}'.format(recipe_name))

def test_import_recipe(self):
"""
Verifies we can dynamically import a recipe without warnings.
"""
p4a_root_dir = os.path.dirname(os.path.dirname(__file__))
name = 'pythonforandroid.recipes.python3'
pathname = os.path.join(
*([p4a_root_dir] + name.split('.') + ['__init__.py'])
)
with warnings.catch_warnings(record=True) as recorded_warnings:
warnings.simplefilter("always")
module = import_recipe(name, pathname)
assert module is not None
assert recorded_warnings == []

0 comments on commit 91a22ee

Please sign in to comment.