Esempio n. 1
0
def unmanagedDLL():
    '''
    Places an unmanaged DLL inside DLLs.
    '''
    twain = Environment.GetEnvironmentVariable("SystemRoot") + "\\twain.dll"
    File.Copy(twain,
              DLLS_DIR + "\\twain.dll")
Esempio n. 2
0
    def read(self):
        '''
		reading rules configuration
		returns string of parsed rules delimited by System.Environment.NewLine
		if the parser made any alterations the editedByParser property will be
		set to True
		'''
        s1 = []
        s = []
        myParser = parser()
        self.editedByParser = False
        if File.Exists(self.theFile):
            File.Copy(self.theFile, globalvars.BAKFILE,
                      True)  # just in case something bad happens
            s1 = File.ReadAllLines(self.theFile)
            s1 = [line for line in s1 if str.Trim(line) <> '']
            for line in s1:
                myParser.validate(unicode(line))
                if myParser.err:
                    self.editedByParser = True
                    pre = myParser.commentedLine(line)
                else:
                    pre = line
                s.Add(pre)
        elif File.Exists(globalvars.SAMPLEFILE):
            s = File.ReadAllLines(globalvars.SAMPLEFILE)

        tmp = str('')
        s = [line for line in s if str.Trim(line) <> '']
        for line in s:
            tmp += '%s%s' % (line, System.Environment.NewLine)
        return tmp
Esempio n. 3
0
 def __import_legacy_settings(cls, legacy_dir, profile_dir):
     '''
   See if there are any legacy settings at the given legacy location, and 
   copy them to the given profile location, if that location doesn't exist.
   '''
     if not File.Exists(cls.SETTINGS_FILE):
         Directory.CreateDirectory(profile_dir)
         settings_file = legacy_dir + r'\settings.dat'
         advanced_file = legacy_dir + r'\advanced.dat'
         geometry_file = legacy_dir + r'\geometry.dat'
         series_file = legacy_dir + r'\series.dat'
         if File.Exists(settings_file):
             File.Copy(settings_file, cls.SETTINGS_FILE, False)
         if File.Exists(advanced_file):
             File.Copy(advanced_file, cls.ADVANCED_FILE, False)
         if File.Exists(geometry_file):
             File.Copy(geometry_file, cls.GEOMETRY_FILE, False)
         if File.Exists(series_file):
             File.Copy(series_file, cls.SERIES_FILE, False)
Esempio n. 4
0
def deploy_file(filename):
    "Copies a file to the bin\Debug folder, replacing any file of the same name already there."
    new_filename = build_dir + "\\" + filename[filename.rfind("\\") + 1 :]
    try:
        if File.Exists(new_filename):
            File.Delete(new_filename)
    except:
        # don't worry about replacing read-only files that we can't delete
        pass
    else:
        File.Copy(filename, new_filename)
Esempio n. 5
0
def setUp():
    '''
    Sets up the DLLs directory.
    '''
    #if it exists, we cannot continue because we will
    #not have the correct permissions to move/remove the
    #DLLs directory
    if Directory.Exists(DLLS_DIR):
        print "ERROR - cannot test anything with a pre-existing DLLs directory"
        raise Exception(
            "Cannot move/delete DLLs which is being used by this process!")

    Directory.CreateDirectory(DLLS_DIR)

    File.Copy(IP_DIR + "\\IronPython.dll", DLLS_DIR + "\\IronPython.dll")

    Directory.SetCurrentDirectory(DLLS_DIR)

    #create a number of "normal" assemblies
    okAssemblies(50)

    #create 5 assemblies in the fooFIVE namespace with nearly
    #identical contents
    dupAssemblies(5)

    #recreate the sys module
    overrideNative()

    #ensure corrupt DLLs cannot work
    corruptDLL()

    #ensure unmanaged DLLs don't break it
    unmanagedDLL()

    #create an exe and a DLL competing for the same
    #namespace
    dllVsExe()

    #create an exe in it's own namespace
    exeOnly()

    #create a DLL that's really a *.txt and
    #create a *.txt that's really a DLL
    textFiles()

    #creates "unique" DLL names that should be loadable
    #by IP
    uniqueDLLNames()

    #cleanup after ourselves
    File.Delete(DLLS_DIR + "\\IronPython.dll")
Esempio n. 6
0
def ExecuteDynamoScript(uiapp, dynamoScriptFilePath, showUI=False):
    externalCommandResult = None
    # NOTE: The temporary copy of the Dynamo script file is created in same folder as the original so
    # that any relative paths in the script won't break.
    tempDynamoScriptFilePath = Path.Combine(
        Path.GetDirectoryName(dynamoScriptFilePath), Path.GetRandomFileName())
    File.Copy(dynamoScriptFilePath, tempDynamoScriptFilePath)
    try:
        SetDynamoScriptRunType(tempDynamoScriptFilePath,
                               DYNAMO_RUNTYPE_AUTOMATIC)
        externalCommandResult = ExecuteDynamoScriptInternal(
            uiapp, tempDynamoScriptFilePath, showUI)
    finally:
        File.Delete(tempDynamoScriptFilePath)
    return externalCommandResult
def CopySnapshotRevitJournalFile(snapshotDataFolderPath, output):
    revitJournalFilePath = None
    try:
        snapshotDataFilePath = GetSnapshotDataFilePath(snapshotDataFolderPath)
        revitJournalFilePath = ReadSnapshotDataRevitJournalFilePath(snapshotDataFilePath)
    except Exception, e:
        output()
        output("WARNING: failed to read journal file path from snapshot data file.")
        exception_util.LogOutputErrorDetails(e, output)
        output()
        output("Attempting to read journal file path from temporary snapshot data file instead.")
        snapshotDataFilePath = GetTemporarySnapshotDataFilePath(snapshotDataFolderPath)
        revitJournalFilePath = ReadSnapshotDataRevitJournalFilePath(snapshotDataFilePath)
    revitJournalFileName = Path.GetFileName(revitJournalFilePath)
    snapshotRevitJournalFilePath = Path.Combine(snapshotDataFolderPath, revitJournalFileName)
    File.Copy(revitJournalFilePath, snapshotRevitJournalFilePath)
    return

def ConsolidateSnapshotData(dataExportFolderPath, output):
    try:
        snapshotDataFilePath = GetSnapshotDataFilePath(dataExportFolderPath)
        temporarySnapshotDataFilePath = GetTemporarySnapshotDataFilePath(dataExportFolderPath)
        if File.Exists(snapshotDataFilePath):
            if File.Exists(temporarySnapshotDataFilePath):
                File.Delete(temporarySnapshotDataFilePath)
        elif File.Exists(temporarySnapshotDataFilePath):
            File.Move(temporarySnapshotDataFilePath, snapshotDataFilePath)
        else:
            output()
            output("WARNING: could not find snapshot data file in snapshot data folder:")
            output()
Esempio n. 8
0
#--Globals

#if this is a debug build and the assemblies are being saved...peverify is run.
#for the test to pass, Maui assemblies must be in the AssembliesDir
if is_peverify_run:
    AddReferenceToDlrCore()
    clr.AddReference("Microsoft.Scripting")
    from Microsoft.Scripting.Runtime import ScriptDomainManager
    from System.IO import Path

    tempMauiDir = Path.GetTempPath()

    print "Copying Maui.Core.dll to %s for peverify..." % (tempMauiDir)
    if not File.Exists(tempMauiDir + '\\Maui.Core.dll'):
        File.Copy(
            testpath.rowan_root +
            '\\Languages\\IronPython\\External\\Maui\\Maui.Core.dll',
            tempMauiDir + '\\Maui.Core.dll')

#Cleanup the last run
for t_name in ['ip_session.log', 'ip_session_stderr.log']:
    if File.Exists(t_name):
        File.Delete(t_name)
    Assert(not File.Exists(t_name))


#------------------------------------------------------------------------------
#--Helper functions
def getTestOutput():
    '''
    Returns stdout and stderr output for a console test.
    '''
Esempio n. 9
0
#------------------------------------------------------------------------------
#--Globals

#if this is a debug build and the assemblies are being saved...peverify is run.
#for the test to pass, Maui assemblies must be in the AssembliesDir
if is_peverify_run:
    AddReferenceToDlrCore()
    clr.AddReference("Microsoft.Scripting")
    from Microsoft.Scripting.Runtime import ScriptDomainManager
    from System.IO import Path

    tempMauiDir = Path.GetTempPath()
    
    print "Copying Maui.Core.dll to %s for peverify..." % (tempMauiDir)
    if not File.Exists(tempMauiDir + '\\Maui.Core.dll'):
        File.Copy(testpath.rowan_root + '\\Util\\Internal\\Maui_old\\Maui.Core.dll',
                  tempMauiDir + '\\Maui.Core.dll')

#Cleanup the last run
for t_name in ['ip_session.log', 'ip_session_stderr.log']:
    if File.Exists(t_name):
        File.Delete(t_name)
    Assert(not File.Exists(t_name))
    
#------------------------------------------------------------------------------
#--Helper functions
def getTestOutput():
    '''
    Returns stdout and stderr output for a console test.
    '''
    #On some platforms 'ip_session.log' is not immediately created after
    #calling the 'close' method of the file object writing to 'ip_session.log'.
Esempio n. 10
0
def main():
    indigo = Indigo()
    output_dir_base = os.path.join(base_root, "ref")
    output_dir = os.path.join(base_root, "out")
    pattern_list = []
    exclude_pattern_list = []
    nunit_report_name = ""
    junit_report_name = ""

    if 'LABEL' in os.environ:
        binenv = os.environ['LABEL'].upper()
        python_exec = os.environ[binenv]
    else:
        python_exec = sys.executable

    for i in range(1, len(sys.argv), 2):
        if sys.argv[i] == '-p':
            pattern_list = sys.argv[i + 1].split(',')
        elif sys.argv[i] == '-e':
            exclude_pattern_list = sys.argv[i + 1].split(',')
        elif sys.argv[i] == '-o':
            output_dir = sys.argv[i + 1]
        elif sys.argv[i] == '-b':
            output_dir_base = sys.argv[i + 1]
        elif sys.argv[i] == '-n':
            nunit_report_name = sys.argv[i + 1]
        elif sys.argv[i] == '-j':
            junit_report_name = sys.argv[i + 1]
        elif sys.argv[i] == '-exec':
            python_exec = sys.argv[i + 1]
        else:
            print("Unexpected options: %s" % (sys.argv[i]))
            exit()

    if not dir_exists(output_dir):
        makedirs(output_dir)

    sys.stdout = Logger(output_dir + "/results.txt")

    if python_exec.startswith('"') and python_exec.endswith('"'):
        python_exec = python_exec[1:-1]

    print("Indigo version: " + indigo.version())
    print("Indigo library path: " + dll_full_path())
    print("Date & time: " + datetime.datetime.now().strftime("%d.%m.%Y %H:%M"))
    if sys.platform == 'cli':
        import System.Environment
    #print("Platform: {}".format(platform.platform() if sys.platform != 'cli' else System.Environment.OSVersion.ToString()))
    #print("Processor: {}".format(platform.processor() if sys.platform != 'cli' else 'x86_64' if System.Environment.Is64BitProcess else 'x86'))
    print("Python: " + sys.version.replace('\n', '\t'))
    print("Executable: " + python_exec)
    import socket
    print("Host name: " + socket.gethostname())  # platform.node())
    print("")

    # Collect tests and sort them
    tests_dir = os.path.join(base_root, 'tests')
    tests = sorted(get_tests(tests_dir))
    # Calcuate maximum lenthd of the test names
    max_name_len = max((len(item[0]) + len(item[1]) + 1 for item in tests))
    # add small gap
    max_name_len += 3

    test_results = []

    tests_status = 0

    total_time = time.time()
    # Execute tests in sorted order
    for root, filename in tests:
        test_dir = os.path.join(output_dir, root)
        if not dir_exists(test_dir):
            os.makedirs(test_dir)
        test_name = os.path.join(root, filename).replace('\\', '/')

        if test_name != "":
            # Check test name by input pattern
            if len(pattern_list):
                skip_test = True
                for pattern in pattern_list:
                    if re.search(pattern, test_name):
                        skip_test = False
                if skip_test:
                    continue
            # exclude some files from test by pattern
            if len(exclude_pattern_list):
                skip_test = False
                for exclude_pattern in exclude_pattern_list:
                    if re.search(exclude_pattern, test_name):
                        skip_test = True
                if skip_test:
                    continue

        sys.stdout.write("%s" % test_name)
        sys.stdout.flush()

        spacer_len = max_name_len - len(test_name)

        test_root = os.path.join(tests_dir, root)

        old_dir = os.path.abspath(os.curdir)
        os.chdir(test_root)
        out_filename = os.path.join(test_dir, filename + '.out')
        err_filename = os.path.join(test_dir, filename + '.err')
        with open_file_utf8(out_filename) as sys.stdout, open_file_utf8(
                err_filename) as sys.stderr:
            t0 = time.time()
            try:
                runpy.run_path(filename, run_name='__main__')
            except:
                sys.stderr.write(traceback.format_exc())
            tspent = time.time() - t0
        os.chdir(old_dir)
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__

        output_file = os.path.join(test_dir, filename + '.out')
        error_file = os.path.join(test_dir, filename + '.err')
        failed_stderr = False
        if not file_size(error_file):
            os.remove(error_file)
        else:
            failed_stderr = True
        base_dir = os.path.join(output_dir_base, root)
        base_output_file = os.path.join(base_dir, filename + ".out")

        base_exists = False
        ndiffcnt = 0
        diff_file = None
        if file_exists(base_output_file):
            diff_file = os.path.join(test_dir, filename + ".diff")
            # copy reference file
            system_name = getPlatform()
            if system_name and file_exists(
                    os.path.join(base_dir, system_name, filename + '.out')):
                base_output_file = os.path.join(base_dir, system_name,
                                                filename + '.out')
            new_ref_file = os.path.join(test_dir, filename + ".std")
            if not os.path.normpath(
                    os.path.abspath(base_output_file)) == os.path.normpath(
                        os.path.abspath(new_ref_file)):
                if not sys.platform == 'cli':
                    shutil.copy(base_output_file, new_ref_file)
                else:
                    import clr
                    clr.AddReference("System.IO.FileSystem")
                    from System.IO import File
                    File.Copy(base_output_file, new_ref_file, True)

            ndiffcnt = write_difference(new_ref_file, output_file, diff_file)
            # remove empty diff file
            if not ndiffcnt:
                os.remove(diff_file)
            base_exists = True

        spacer = '.'
        msg = ''
        if failed_stderr:
            test_status = "[ERROR]"
            tests_status |= 2
        elif not base_exists:
            test_status = "[NEW]"
        elif not ndiffcnt:
            test_status = "[PASSED]"
            spacer = ' '
            spacer_len += 2
        else:
            test_status = "[FAILED]"
            if root != 'todo':
                tests_status |= 1

        print("{}{}    {:.2f} sec".format(spacer * spacer_len, test_status,
                                          tspent))
        if diff_file and file_exists(diff_file):
            f = open(diff_file, 'rt')
            msg = 'Diff:\n' + f.read()
            f.close()
        if error_file and file_exists(error_file):
            f = open(error_file, 'rt')
            msg = 'Error:\n' + f.read()
            f.close()

        test_results.append((root, filename, test_status, msg, tspent))

    total_time = time.time() - total_time
    print("\nTotal time: {:.2f} sec".format(total_time))

    if nunit_report_name != "":
        from generate_nunit_report import generateNUnitReport
        generateNUnitReport(test_results, nunit_report_name)

    if junit_report_name != "":
        from generate_junit_report import generate_junit_report
        generate_junit_report(test_results, junit_report_name)

    return tests_status
Esempio n. 11
0
    clr.AddReference("sbs_library")
    from SbsTest import C
    o = C()
    g1 = o.M1
    g2 = o.M2
    g3 = o.M3
    
    #for peverify runs
    from System.IO import Path, File, Directory
    if File.Exists(Path.GetTempPath() + r"\sbs_library.dll"):
        try:
            File.Delete(Path.GetTempPath() + r"\sbs_library.dll")
        except:
            pass
    if not File.Exists(Path.GetTempPath() + r"\sbs_library.dll"):
        File.Copy(Directory.GetCurrentDirectory() + r"\sbs_library.dll", Path.GetTempPath() + r"\sbs_library.dll")
    
else:
    g1 = f1
    g2 = f2
    g3 = f3

# combinations
choices = [(), (0,), (1,), (2,), (3,), (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3), (0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3), (0, 1, 2, 3) ]

def to_str(l): return [str(x) for x in l] 

def replace_B(line):
    count = 0
    while True:
        pos = line.find("B")
Esempio n. 12
0
    clr.AddReferenceToFile("sbs_library.dll")
    from SbsTest import C
    o = C()
    g1 = o.M1
    g2 = o.M2
    g3 = o.M3
    
    #for peverify runs
    from System.IO import Path, File, Directory
    if File.Exists(Path.Combine(Path.GetTempPath(), "sbs_library.dll")):
        try:
            File.Delete(Path.Combine(Path.GetTempPath(), "sbs_library.dll"))
        except:
            pass
    if not File.Exists(Path.Combine(Path.GetTempPath(), "sbs_library.dll")):
        File.Copy(Path.Combine(Directory.GetCurrentDirectory(), "sbs_library.dll"), Path.Combine(Path.GetTempPath(), "sbs_library.dll"))
    
else:
    g1 = f1
    g2 = f2
    g3 = f3

# combinations
choices = [(), (0,), (1,), (2,), (3,), (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3), (0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3), (0, 1, 2, 3) ]

def to_str(l): return [str(x) for x in l] 

def replace_B(line):
    count = 0
    while True:
        pos = line.find("B")
                                           projectname + '.a5proj')
cwspath = ZenConnectDocument.GetZenConnectDocumentPath()
cwsdata_path = Path.Combine(cwspath, projectname + '_data')

# get all open documents
opendocs = Zen.Application.Documents

for doc in opendocs:

    if doc.IsZenImage and doc.Name != 'Navigation':
        image = Zen.Application.Documents.GetByName(doc.Name)
        # add current image document to ZEN Connect workspace
        ZenConnectDocument.AddImageToZenConnectProject(image.FileName)

        if copydata:
            File.Copy(image.FileName, Path.Combine(cwsdata_path, image.Name))
            print('Copied File: ', image.FileName, ' to: ', cwsdata_path)

        print('Added image to ZEN Connect: ', image.Name)

        # check for labels or preview images
        try:
            att = image.Core.Attachments.GetEnumerator()
            index = 0

            index_to_remove = -1
            for a in att:

                if a.Name == 'SlidePreview':
                    preview = a.GetImageDocument()
                    print(a.Name)