How to use realpath_with_context method in Behave

Best Python code snippet using behave

Run Behave automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

pathutil.py

Source: pathutil.py Github

copy
1"""
2Provides some command utility functions.
3"""
4
5import os.path
6import sys
7import codecs
8
9
10def realpath_with_context(path, context):
11    """
12    Convert a path into its realpath:
13
14      * For relative path: use :attr:`context.workdir` as root directory
15      * For absolute path: Pass-through without any changes.
16
17    :param path: Filepath to convert (as string).
18    :param context: Behave context object (with :attr:`context.workdir`)
19    :return: Converted path.
20    """
21    if not os.path.isabs(path):
22        assert context.workdir
23        path = os.path.join(context.workdir, os.path.normpath(path))
24    return path
25
26
27def posixpath_normpath(pathname):
28    """
29    Convert path into POSIX path:
30
31      * Normalize path
32      * Replace backslash with slash
33
34    :param pathname: Pathname (as string)
35    :return: Normalized POSIX path.
36    """
37    backslash = "\\"
38    pathname2 = os.path.normpath(pathname) or "."
39    if backslash in pathname2:
40        pathname2 = pathname2.replace(backslash, "/")
41    return pathname2
42
43
44def ensure_makedirs(directory, max_iterations=3):
45    # -- SPORADIC-ERRORS: WindowsError: [Error 5] Access denied: '...'
46    iteration = 0
47    exception_text = None
48    for iteration in range(max_iterations):
49        try:
50            os.makedirs(directory)
51        except OSError as e:
52            if iteration >= max_iterations:  # XXX-BAD: Never occurs
53                raise
54            else:
55                exception_text = "%s:%s" % (e.__class__.__name__, e)
56
57        if os.path.isdir(directory):
58            return
59
60    assert os.path.isdir(
61        directory
62    ), "FAILED: ensure_makedirs(%r) (after %s iterations):\n%s" % (
63        directory,
64        max_iterations,
65        exception_text,
66    )
67
68
69def read_file_contents(filename, context=None, encoding=None):
70    filename_ = realpath_with_context(filename, context)
71    assert os.path.exists(filename_)
72    with open(filename_, "r") as file_:
73        file_contents = file_.read()
74    return file_contents
75
76
77def create_textfile_with_contents(filename, contents, encoding="utf-8"):
78    """
79    Creates a textual file with the provided contents in the workdir.
80    Overwrites an existing file.
81    """
82    ensure_directory_exists(os.path.dirname(filename))
83    if os.path.exists(filename):
84        os.remove(filename)
85    outstream = codecs.open(filename, "w", encoding)
86    outstream.write(contents)
87    if contents and not contents.endswith("\n"):
88        outstream.write("\n")
89    outstream.flush()
90    outstream.close()
91    assert os.path.exists(filename), "ENSURE file exists: %s" % filename
92
93
94def ensure_file_exists(filename, context=None):
95    real_filename = filename
96    if context:
97        real_filename = realpath_with_context(filename, context)
98    if not os.path.exists(real_filename):
99        create_textfile_with_contents(real_filename, "")
100    assert os.path.exists(real_filename), "ENSURE file exists: %s" % filename
101
102
103def ensure_directory_exists(dirname, context=None):
104    """
105    Ensures that a directory exits.
106    If it does not exist, it is automatically created.
107    """
108    real_dirname = dirname
109    if context:
110        real_dirname = realpath_with_context(dirname, context)
111    if not os.path.exists(real_dirname):
112        mas_iterations = 2
113        if sys.platform.startswith("win"):
114            mas_iterations = 10
115        ensure_makedirs(real_dirname, mas_iterations)
116
117    assert os.path.exists(real_dirname), "ENSURE dir exists: %s" % dirname
118    assert os.path.isdir(real_dirname), "ENSURE is directory: %s" % dirname
119
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Behave on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)