From 04a43c88197256918ae33f505b72971072dc2930 Mon Sep 17 00:00:00 2001 From: Sandy Walsh Date: Mon, 26 May 2014 15:34:48 +0000 Subject: [PATCH] Added a few missing use cases --- README.md | 2 +- simport/__init__.py | 20 ++++++++++++++------ tests/test_simport.py | 7 +++++-- 3 files changed, 20 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 26be05c..3d6d048 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Using Simport # For modules not in the Python Path function = simport.load('/path/to/file.py|module_name:myfunction') - class_method = simport.load('/path/to/file.py|module_name:MyClasss.mymethod') + class_method = simport.load('/path/to/file.py|module_name:MyClass.mymethod') Running Tests ============= diff --git a/simport/__init__.py b/simport/__init__.py index aa0fac6..5bf54fe 100644 --- a/simport/__init__.py +++ b/simport/__init__.py @@ -16,6 +16,7 @@ import imp import logging import os +import os.path import sys @@ -52,16 +53,23 @@ def _get_module(target): the module loaded as normal. """ - directory, sep, namespace = target.rpartition('|') + filepath, sep, namespace = target.rpartition('|') + if sep and not filepath: + raise BadDirectory("Path to file not supplied.") + module, sep, class_or_function = namespace.rpartition(':') - if not module: + if (sep and not module) or (filepath and not module): raise MissingModule("Need a module path for %s (%s)" % (namespace, target)) - if directory and directory not in sys.path: - if not os.path.isdir(directory): - raise BadDirectory("No such directory: '%s'" % directory) - sys.path.append(directory) + path = "" + filename = "" + if filepath: + path, filename = os.path.split(filepath) + if path and path not in sys.path: + if not os.path.isdir(path): + raise BadDirectory("No such directory: '%s'" % path) + sys.path.append(path) if not class_or_function: raise MissingMethodOrFunction("No Method or Function specified") diff --git a/tests/test_simport.py b/tests/test_simport.py index 7771df1..07b6f00 100644 --- a/tests/test_simport.py +++ b/tests/test_simport.py @@ -16,8 +16,9 @@ class DummyClass(object): class TestSimport(unittest.TestCase): def test_bad_targets(self): - self.assertRaises(simport.MissingModule, simport._get_module, - "missing.py") + self.assertRaises(simport.BadDirectory, simport._get_module, + "|foo.Class") + self.assertRaises(simport.MissingModule, simport._get_module, "missing.py|") @@ -25,6 +26,8 @@ class TestSimport(unittest.TestCase): "simport_tests/localmodule.py|") self.assertRaises(simport.MissingModule, simport._get_module, "simport_tests/localmodule.py|Foo") + self.assertRaises(simport.BadDirectory, simport._get_module, + "/does/not/exist/foo.py|foo:Class") self.assertFalse("AnyModuleName" in sys.modules) self.assertRaises(simport.MissingMethodOrFunction, simport._get_module,