Search code examples
pythonpython-importsquish

Importing file in Squish using python


If two files have function with same name ,importing them using source(findFile()) in a script and calling it accesses the function in the file associated at the last.How to access a function in a particular file?Does squish with python support import file syntax?

Here is a reference

script_1.py

def runner1():
    test.log("Hey")

script_2.py

def runner1():
    test.log("Bye")

Script :

source(findFile("scripts","script_1.py"))
source(findFile("scripts","script_2.py"))


runner1()//function call

O/P:Bye

Note:When I import using filename it throws error as "module not present"


Solution

  • source() causes the "symbols" (functions, variables) in the specified file to be loaded into the namespace/scope of the test.py file. This means that source() is the wrong tool for this problem.

    (Using the trick shown by Orip, to assign the function to another symbol/name after the first source() I would advise against, since other code relying on the desired function to be available under the initial name would call the wrong function eventually.)

    Using Python's import statement you can achieve that the functions are in separate namespaces, by treating the files as Python modules. For this to work you have to include the directory paths containing the desired files into Python's own "search path" - sys.path:

    Contents of suite_mine/tst_testcase1/test.py:

    # -*- coding: utf-8 -*-
    
    import os.path
    import sys
    
    # Add path to our modules to the Python search path at runtime:
    sys.path.append(os.path.dirname(findFile("scripts", "file1.py")))
    sys.path.append(os.path.dirname(findFile("scripts", "file2.py")))
    
    # Now import our modules:
    import file1
    import file2
    
    
    def main():
        # Access functions in our modules:
        file1.do_it()
        file2.do_it()
    

    Contents of suite_mine/tst_testcase1/file1.py:

    # -*- coding: utf-8 -*-
    
    import test
    
    
    def do_it():
        test.log("file1.py")
    

    Contents of suite_mine/tst_testcase1/file2.py:

    # -*- coding: utf-8 -*-
    
    import test
    
    
    def do_it():
        test.log("file2.py")
    

    Resulting log entries:

    file1.py
    file2.py