Skip to content

Commit

Permalink
Merge pull request #1789 from AndreMiras/feature/filter_python2_impor…
Browse files Browse the repository at this point in the history
…t_recipe_warnings

Ignores Python 2 import_recipe() warnings
  • Loading branch information
inclement authored Apr 7, 2019
2 parents 6b12281 + 7b21c46 commit 1b36096
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 14 deletions.
30 changes: 17 additions & 13 deletions pythonforandroid/recipe.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from os.path import basename, dirname, exists, isdir, isfile, join, realpath, split
import importlib
import glob
from shutil import rmtree
from six import PY2, with_metaclass
Expand All @@ -21,22 +20,27 @@
from pythonforandroid.util import (urlretrieve, current_directory, ensure_dir,
BuildInterruptingException)

# this import is necessary to keep imp.load_source from complaining :)
if PY2:
import imp
import_recipe = imp.load_source
else:
import importlib.util
if hasattr(importlib.util, 'module_from_spec'):
def import_recipe(module, filename):

def import_recipe(module, filename):
if PY2:
import imp
import warnings
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'):
spec = importlib.util.spec_from_file_location(module, filename)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
else:
from importlib.machinery import SourceFileLoader

def import_recipe(module, filename):
else:
# Python 3.3 and 3.4:
from importlib.machinery import SourceFileLoader
return SourceFileLoader(module, filename).load_module()


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 1b36096

Please sign in to comment.