Best Python code snippet using behave
pathutil.py
Source:pathutil.py  
...3"""4import os.path5import sys6import codecs7def realpath_with_context(path, context):8    """9    Convert a path into its realpath:10      * For relative path: use :attr:`context.workdir` as root directory11      * For absolute path: Pass-through without any changes.12    :param path: Filepath to convert (as string).13    :param context: Behave context object (with :attr:`context.workdir`)14    :return: Converted path.15    """16    if not os.path.isabs(path):17        assert context.workdir18        path = os.path.join(context.workdir, os.path.normpath(path))19    return path20def posixpath_normpath(pathname):21    """22    Convert path into POSIX path:23      * Normalize path24      * Replace backslash with slash25    :param pathname: Pathname (as string)26    :return: Normalized POSIX path.27    """28    backslash = "\\"29    pathname2 = os.path.normpath(pathname) or "."30    if backslash in pathname2:31        pathname2 = pathname2.replace(backslash, "/")32    return pathname233def ensure_makedirs(directory, max_iterations=3):34    # -- SPORADIC-ERRORS: WindowsError: [Error 5] Access denied: '...'35    iteration = 036    exception_text = None37    for iteration in range(max_iterations):38        try:39            os.makedirs(directory)40        except OSError as e:41            if iteration >= max_iterations:  # XXX-BAD: Never occurs42                raise43            else:44                exception_text = "%s:%s" % (e.__class__.__name__, e)45        if os.path.isdir(directory):46            return47    assert os.path.isdir(48        directory49    ), "FAILED: ensure_makedirs(%r) (after %s iterations):\n%s" % (50        directory,51        max_iterations,52        exception_text,53    )54def read_file_contents(filename, context=None, encoding=None):55    filename_ = realpath_with_context(filename, context)56    assert os.path.exists(filename_)57    with open(filename_, "r") as file_:58        file_contents = file_.read()59    return file_contents60def create_textfile_with_contents(filename, contents, encoding="utf-8"):61    """62    Creates a textual file with the provided contents in the workdir.63    Overwrites an existing file.64    """65    ensure_directory_exists(os.path.dirname(filename))66    if os.path.exists(filename):67        os.remove(filename)68    outstream = codecs.open(filename, "w", encoding)69    outstream.write(contents)70    if contents and not contents.endswith("\n"):71        outstream.write("\n")72    outstream.flush()73    outstream.close()74    assert os.path.exists(filename), "ENSURE file exists: %s" % filename75def ensure_file_exists(filename, context=None):76    real_filename = filename77    if context:78        real_filename = realpath_with_context(filename, context)79    if not os.path.exists(real_filename):80        create_textfile_with_contents(real_filename, "")81    assert os.path.exists(real_filename), "ENSURE file exists: %s" % filename82def ensure_directory_exists(dirname, context=None):83    """84    Ensures that a directory exits.85    If it does not exist, it is automatically created.86    """87    real_dirname = dirname88    if context:89        real_dirname = realpath_with_context(dirname, context)90    if not os.path.exists(real_dirname):91        mas_iterations = 292        if sys.platform.startswith("win"):93            mas_iterations = 1094        ensure_makedirs(real_dirname, mas_iterations)95    assert os.path.exists(real_dirname), "ENSURE dir exists: %s" % dirname...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
