[Tutor] Why does os.path.realpath('test_main.py') give different results for unittest than for testing statement in interpreter?
Alan Gauld
alan.gauld at yahoo.co.uk
Sun Jan 7 09:32:38 EST 2018
On 07/01/18 09:07, boB Stepp wrote:
> clarify this? What is the methodology that os.path.realpath(path) is
> actually following to yield a particular path name? And why does it
> not care if path refers to a real file or not?
The os.path module is mostly a string manipulation toolkit.
It checks that a string looks like a path and it de/constructs
paths from strings. But it does not pay muchy(any?) attention
to the filesystem. It doesn't care if the paths it deals
with are real paths or not, its purely manipulating the
strings according to the syntax rules for paths.
The exceptions are the test functions like isfile(), isdir() etc.
> What I *really* want to do is locate and open a file "test_data.dat"
> that is in the same directory as the file with the tests,
For that you need to do some work with listdir or glob.
You might need to do a os.getcwd() but I suspect it will
return the folder where you started te program rather than
the folder the file lives in. For that you may need to
use the __file__ attribute of the test module. So
something like:
dir = os.path.dirname(__file__) # assuming this is in the test module
fn = os.path.join(dir,fname)
if os.path.isfile(fn) # check the file actually exists
f = open(fn)
> class TestOpenFileStrIntsToList(unittest.TestCase):
> """Tests for the function open_file_str_ints_to_list."""
>
> def test_open_file_str_ints_to_list(self):
> """Ensure expected list of string integers is returned."""
>
> path = os.path.dirname(
> os.path.realpath(__file__)) + '/test_data.dat'
> print('realpath =', os.path.realpath(__file__))
Yes, thats it although you could test using isfile() or
better still use a try/except around the open.
Also you should strictly use os.path.join() to create the path
> BTW, I am having trouble coming up with a good name for a string that
> looks like an integer that I plan on using int() later to convert the
> string to an integer. "String integer" is my best thought at this
> time.
What's it for? Where did it come from?
type based names are rarely good, better to describe why/where.
input_Id, read_Id, stored_Id etc....
Or substitute Ref, or Count or whatever for Id.
Then the real int var name becomes the second part:
Id = int(input_Id)
or
count = int(stored_count)
> Is this way of determining the directory which
> test_main.py is running from bullet proof?
If its really in the same folder then I believe
so - or as bullet proof as it gets. Maybe if you
create a shortcut to the real folder etc you might
need to revert to realpath.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list