Don't leave cruft around in sys.modules when an import fails.

Closes: #214, #225

Squashed from a bunch of commits by @olasd
This commit is contained in:
Morten Linderud 2013-07-06 20:35:26 +02:00 committed by Nicolas Dandrimont
parent b78be9a594
commit e4ae9880f4
3 changed files with 26 additions and 5 deletions

View File

@ -70,10 +70,15 @@ def import_file_to_module(module_name, fpath):
"""Import content from fpath and puts it into a Python module.
Returns the module."""
_ast = import_file_to_ast(fpath, module_name)
mod = imp.new_module(module_name)
mod.__file__ = fpath
eval(ast_compile(_ast, fpath, "exec"), mod.__dict__)
try:
_ast = import_file_to_ast(fpath, module_name)
mod = imp.new_module(module_name)
mod.__file__ = fpath
eval(ast_compile(_ast, fpath, "exec"), mod.__dict__)
except Exception:
sys.modules.pop(module_name, None)
raise
return mod

View File

@ -1,4 +1,5 @@
from hy.importer import import_file_to_module, import_buffer_to_ast
from hy.importer import import_file_to_module, import_buffer_to_ast, MetaLoader
import os
import ast
@ -12,3 +13,17 @@ def test_stringer():
"Make sure the basics of the importer work"
_ast = import_buffer_to_ast("(defn square [x] (* x x))", '')
assert type(_ast.body[0]) == ast.FunctionDef
def test_imports():
path = os.getcwd() + "/tests/resources/importer/a.hy"
testLoader = MetaLoader(path)
def _import_test():
try:
return testLoader.load_module("tests.resources.importer.a")
except:
return "Error"
assert _import_test() == "Error"
assert _import_test() != None

View File

@ -0,0 +1 @@
(thisshouldnotwork)