def GetImage(type, quadkey): global cacheHits global cacheMisses global cache global allowCaching if allowCaching is True: try: cache[type + quadkey] cacheHits += 1 return Image.FromFile(nt.getcwd() + "\\cache\\" + type + quadkey + ".jpeg") except (KeyError, IOError): cacheMisses += 1 img = GetImageFromStream(type, quadkey) if not img is None: try: img.Save(nt.getcwd() + "\\cache\\" + type + quadkey + ".jpeg") cache[type + quadkey] = True return img except: print "Error writing cache" return img else: return GetImageFromStream(type, quadkey)
def test__getfullpathname(): AreEqual(nt._getfullpathname('.'), nt.getcwd()) AreEqual(nt._getfullpathname('<bad>'), path_combine(nt.getcwd(), '<bad>')) AreEqual(nt._getfullpathname('bad:'), path_combine(nt.getcwd(), 'bad:')) AreEqual(nt._getfullpathname(':bad:'), path_combine(nt.getcwd(), ':bad:')) AreEqual(nt._getfullpathname('::'), '::\\') AreEqual(nt._getfullpathname('1:'), '1:\\') AreEqual(nt._getfullpathname('1:a'), '1:\\a') AreEqual(nt._getfullpathname('1::'), '1:\\:') AreEqual(nt._getfullpathname('1:\\'), '1:\\')
def test__getfullpathname(self): self.assertEqual(nt._getfullpathname('.'), nt.getcwd()) self.assertEqual(nt._getfullpathname('<bad>'), os.path.join(nt.getcwd(), '<bad>')) self.assertEqual(nt._getfullpathname('bad:'), os.path.join(nt.getcwd(), 'bad:')) self.assertEqual(nt._getfullpathname(':bad:'), os.path.join(nt.getcwd(), ':bad:')) self.assertEqual(nt._getfullpathname('::'), '::\\') self.assertEqual(nt._getfullpathname('1:'), '1:\\') self.assertEqual(nt._getfullpathname('1:a'), '1:\\a') self.assertEqual(nt._getfullpathname('1::'), '1:\\:') self.assertEqual(nt._getfullpathname('1:\\'), '1:\\')
def test__getfullpathname(): AreEqual(nt._getfullpathname("."), nt.getcwd()) AreEqual(nt._getfullpathname("<bad>"), path_combine(nt.getcwd(), "<bad>")) AreEqual(nt._getfullpathname("bad:"), path_combine(nt.getcwd(), "bad:")) AreEqual(nt._getfullpathname(":bad:"), path_combine(nt.getcwd(), ":bad:")) AreEqual(nt._getfullpathname("::"), "::\\") AreEqual(nt._getfullpathname("1:"), "1:\\") AreEqual(nt._getfullpathname("1:a"), "1:\\a") AreEqual(nt._getfullpathname("1::"), "1:\\:") AreEqual(nt._getfullpathname("1:\\"), "1:\\")
def test_chdir(): currdir = nt.getcwd() nt.mkdir('tsd') nt.chdir('tsd') AreEqual(currdir+'\\tsd', nt.getcwd()) nt.chdir(currdir) AreEqual(currdir, nt.getcwd()) nt.rmdir('tsd') # the directory is empty or does not exist AssertErrorWithNumber(WindowsError, 22, lambda:nt.chdir('')) AssertErrorWithNumber(WindowsError, 2, lambda:nt.chdir('tsd'))
def test_chdir(self): currdir = nt.getcwd() nt.mkdir('tsd') nt.chdir('tsd') self.assertEqual(os.path.join(currdir, 'tsd'), nt.getcwd()) nt.chdir(currdir) self.assertEqual(currdir, nt.getcwd()) nt.rmdir('tsd') # the directory is empty or does not exist self.assertRaisesNumber(WindowsError, 22, lambda:nt.chdir('')) self.assertRaisesNumber(WindowsError, 2, lambda:nt.chdir('tsd'))
def ClearCache(): try: files = nt.listdir(nt.getcwd() + "\\cache") except: print "Error reading cache folder" return for i in range(0, len(files)): if files[i].find(".jpeg") > -1: try: nt.remove(nt.getcwd() + "\\cache\\" + files[i]) except: x = None
def test_cp24720(): f = file(nt.getcwd() + "\\site.py", "w") f.write("import sys\nsys.foo = 456\n") f.close() orig_ipy_path = Environment.GetEnvironmentVariable("IRONPYTHONPATH") try: Environment.SetEnvironmentVariable("IRONPYTHONPATH", "") TestCommandLine(("-c", "import site;import sys;print hasattr(sys, 'foo')"), "False\n") Environment.SetEnvironmentVariable("IRONPYTHONPATH", ".") TestCommandLine(("-c", "import site;import sys;print hasattr(sys, 'foo')"), "True\n") finally: Environment.SetEnvironmentVariable("IRONPYTHONPATH", orig_ipy_path) nt.remove(nt.getcwd() + "\\site.py")
def test_main(): import ctypes.test skipped, testcases = ctypes.test.get_tests(ctypes.test, "test_*.py", verbosity=0) suites = [unittest.makeSuite(t) for t in testcases] if due_to_ironpython_bug("http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=374"): for suite in suites: length = len(suite._tests) i = 0 while i < length: if suite._tests[i].id() in IRONPYTHON_DISABLED_LIST: suite._tests.pop(i) i -= 1 length -= 1 i += 1 try: run_unittest(unittest.TestSuite(suites)) finally: if due_to_ironpython_bug("http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=22393"): try: System.IO.File.Delete(nt.getcwd() + r"\Python26.dll") except: pass print "%d of these test cases were disabled under IronPython." % len(IRONPYTHON_DISABLED_LIST)
def test_remove(): # remove an existing file handler = open("create_test_file.txt","w") handler.close() path1 = nt.getcwd() nt.remove(path1+'\\create_test_file.txt') AreEqual(nt.listdir(nt.getcwd()).count('create_test_file.txt'), 0) AssertErrorWithNumber(OSError, 2, nt.remove, path1+'\\create_test_file2.txt') AssertErrorWithNumber(OSError, 2, nt.unlink, path1+'\\create_test_file2.txt') AssertErrorWithNumber(OSError, 22, nt.remove, path1+'\\create_test_file?.txt') AssertErrorWithNumber(OSError, 22, nt.unlink, path1+'\\create_test_file?.txt') # the path is a type other than string AssertError(TypeError, nt.remove, 1) AssertError(TypeError, nt.remove, True) AssertError(TypeError, nt.remove, None)
def fullpath(path): if colon not in path: return nt.getcwd() + separator + path elif sys.platform!="win32": from System.IO.Path import GetFullPath return GetFullPath(path) else: return path
def LoadCache(): try: files = nt.listdir(nt.getcwd() + "\\cache") except: print "Error reading cache folder" return for f in files: if f.endswith(".jpeg"): cache[f[:-5]] = True
def SaveSettings(self): import clr clr.AddReference("System.Xml") from System.Xml import XmlDocument import nt xmldoc = XmlDocument() try: xmldoc.Load(nt.getcwd() + "\load.xml") except: print "Error reading load.xml" return nodelist = xmldoc.GetElementsByTagName("Cache") a = xmldoc.CreateAttribute("allow") if self.checkCache.Checked is True: a.Value = "true" else: a.Value = "false" nodelist.Item(0).Attributes.Append(a) nodelist = xmldoc.GetElementsByTagName("TopLeftPreviewTile") a = xmldoc.CreateAttribute("x") a.Value = str(self.previewTile[0][0].tile[0]) nodelist.Item(0).Attributes.Append(a) a = xmldoc.CreateAttribute("y") a.Value = str(self.previewTile[0][0].tile[1]) nodelist.Item(0).Attributes.Append(a) a = xmldoc.CreateAttribute("dimension") if self.radio3x3.Checked is True: a.Value = "3" else: a.Value = "4" nodelist.Item(0).Attributes.Append(a) a = xmldoc.CreateAttribute("level") a.Value = str(self.scrollZoom.Value) nodelist.Item(0).Attributes.Append(a) try: xmldoc.Save(nt.getcwd() + "\load.xml") except: print "Error writing load.xml"
def test_cp11923_second(): import nt import sys old_path = [x for x in sys.path] sys.path.append(nt.getcwd()) try: #Test setup _t_test = testpath.public_testdir + "\\cp11116_main.py" write_to_file(_t_test, """import cp11116_a try: cp11116_a.a() except: pass cp11116_a.a() """) _t_test_a = testpath.public_testdir + "\\cp11116_a.py" write_to_file(_t_test_a, """def a(): raise None """) #Actual test t_out, t_in, t_err = nt.popen3(sys.executable + " " + nt.getcwd() + r"\cp11116_main.py") lines = t_err.readlines() t_err.close() t_out.close() t_in.close() #Verification Assert("cp11116_main.py\", line 7, in" in lines[1], lines[1]) line_num = 3 if is_cli: line_num -= 1 Assert(lines[line_num].rstrip().endswith("cp11116_a.py\", line 2, in a"), lines[line_num]) finally: sys.path = old_path nt.unlink(_t_test) nt.unlink(_t_test_a)
def test_cp1019(): #--Test that bogus encodings fail properly t_in, t_out, t_err = nt.popen3(sys.executable + " " + nt.getcwd() + r"\encoded_files\cp1019.py") t_err_lines = t_err.readlines() t_out_lines = t_out.readlines() t_err.close() t_out.close() t_in.close() AreEqual(len(t_out_lines), 0) Assert(t_err_lines[0].startswith(" File")) Assert(t_err_lines[1].startswith("SyntaxError: encoding problem: with BOM"))
def genPeverifyInteropAsm(file): #if this isn't a test run that will invoke peverify there's no point in #continuing if not is_peverify_run: return else: mod_name = file.rsplit("\\", 1)[1].split(".esc")[0] print("Generating interop assemblies for the", mod_name, "test module which are needed in %TEMP% by peverify...") from System.IO import Path tempDir = Path.GetTempPath() cwd = nt.getcwd() #maps COM interop test module names to a list of DLLs module_dll_dict = { "excel" : [], "msagent" : [agentsvr_path], "scriptpw" : [scriptpw_path], "word" : [], } dlrcomlib_list = [ "dlrcomserver", "paramsinretval", "method", "obj", "prop", ] if is_cli32: temp_name = testpath.rowan_root + "\\Test\\DlrComLibrary\\Debug\\DlrComLibrary.dll" else: temp_name = testpath.rowan_root + "\\Test\\DlrComLibrary\\x64\\Release\\DlrComLibrary.dll" for mod_name in dlrcomlib_list: module_dll_dict[mod_name] = [ temp_name ] if not file_exists_in_path("tlbimp.exe"): print("ERROR: tlbimp.exe is not in the path!") sys.exit(1) try: if mod_name not in module_dll_dict: print("WARNING: cannot determine which interop assemblies to install!") print(" This may affect peverify runs adversely.") print() return else: nt.chdir(tempDir) for com_dll in module_dll_dict[mod_name]: if not file_exists(com_dll): print("\tERROR: %s does not exist!" % (com_dll)) continue print("\trunning tlbimp on", com_dll) run_tlbimp(com_dll) finally: nt.chdir(cwd)
def SaveCurrentGame(self, caption): import clr clr.AddReference("System.Xml") from System.Xml import * import nt xmldoc = XmlDocument() try: xmldoc.Load(nt.getcwd() + "\load.xml") except: print "Error reading load.xml" return nodeSavedGames = xmldoc.GetElementsByTagName("SavedGames") nodeNewGame = xmldoc.CreateElement("Game") a = xmldoc.CreateAttribute("caption") a.Value = caption nodeNewGame.Attributes.Append(a) a = xmldoc.CreateAttribute("type") a.Value = self.currentGameState[0] nodeNewGame.Attributes.Append(a) a = xmldoc.CreateAttribute("x") a.Value = str(self.currentGameState[1]) nodeNewGame.Attributes.Append(a) a = xmldoc.CreateAttribute("y") a.Value = str(self.currentGameState[2]) nodeNewGame.Attributes.Append(a) a = xmldoc.CreateAttribute("level") a.Value = str(self.currentGameState[3]) nodeNewGame.Attributes.Append(a) a = xmldoc.CreateAttribute("dimension") a.Value = str(self.currentGameState[4]) nodeNewGame.Attributes.Append(a) nodeSavedGames[0].AppendChild(nodeNewGame) try: xmldoc.Save(nt.getcwd() + "\load.xml") except: print "Error writing load.xml"
def file_exists_in_path(file): full_path = [nt.environ[x] for x in nt.environ.keys() if x.lower() == "path"] if len(full_path)==0: return False else: full_path = full_path[0] for path in [nt.getcwd()] + full_path.split(";"): path = path.lstrip().rstrip() if file_exists(path + "\\" + file) == True: return True return False
def test_ipy_dash_m_pkgs(): # Python packages work import nt Assert("testpkg1" in [x.lower() for x in nt.listdir(nt.getcwd())], nt.getcwd()) old_ipy_path = get_environ_variable("IRONPYTHONPATH") try: nt.environ["IRONPYTHONPATH"] = nt.getcwd() ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -m testpkg1") res, output, err, exit = ipi.StartAndRunToCompletion() AreEqual(res, True) # run should have worked AreEqual(exit, 0) # should have returned 0 AreEqual(output, "") # Bad module names should not work ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -m libxyz") res, output, err, exit = ipi.StartAndRunToCompletion() AreEqual(res, True) # run should have worked AreEqual(exit, 1) # should have returned 0 Assert("ImportError: No module named libxyz" in err, "stderr is:" + str(err)) finally: nt.environ["IRONPYTHONPATH"] = old_ipy_path
def test_rename(): # normal test handler = open("oldnamefile.txt","w") handler.close() str_old = "oldnamefile.txt" dst = "newnamefile.txt" nt.rename(str_old,dst) AreEqual(nt.listdir(nt.getcwd()).count(dst), 1) AreEqual(nt.listdir(nt.getcwd()).count(str_old), 0) nt.remove(dst) # the destination name is a directory handler = open("oldnamefile.txt","w") handler.close() str_old = "oldnamefile.txt" dst = "newnamefile.txt" nt.mkdir(dst) AssertError(OSError, nt.rename,str_old,dst) nt.rmdir(dst) nt.remove(str_old) # the dst already exists handler1 = open("oldnamefile.txt","w") handler1.close() handler2 = open("newnamefile.txt","w") handler2.close() str_old = "oldnamefile.txt" dst = "newnamefile.txt" AssertError(OSError, nt.rename,str_old,dst) nt.remove(str_old) nt.remove(dst) # the source file specified does not exist str_old = "oldnamefile.txt" dst = "newnamefile.txt" AssertError(OSError, nt.rename,str_old,dst)
def test_file_encodings_negative(): ''' TODO: - we should use *.py files in the correct encoding instead of dynamically generating ASCII files - need variations on the encoding names ''' import sys import nt sys.path.append(nt.getcwd() + "\\tmp_encodings") try: nt.mkdir(nt.getcwd() + "\\tmp_encodings") except: pass try: #negative case f = open(nt.getcwd() + "\\tmp_encodings\\" + "bad_encoding.py", "w") f.write("# coding: bad") f.close() AssertError(SyntaxError, __import__, "bad_encoding") finally: #cleanup sys.path.remove(nt.getcwd() + "\\tmp_encodings")
def check_package(package_name): ''' Checks all subpackages and modules in the package_name package. ''' cwd = nt.getcwd() if cwd==CPY_LIB_DIR: root_name = package_name else: root_name = cwd.split(CPY_DIR + "\\Lib\\")[1].replace("\\", ".") + "." + package_name #First check that the root package can be imported try: import_helper(package_name) log_ok(root_name) except (Exception, SystemExit), e: log_broken(root_name, e)
def main(cpy_dir): global CPY_DIR global CPY_LIB_DIR CPY_DIR = cpy_dir CPY_LIB_DIR = cpy_dir + "\\Lib" #E.g., C:\Python25\Lib path.append(CPY_LIB_DIR) path.insert(0, ".") print "------------------------------------------------------------------------" print "--PACKAGES" cwd = nt.getcwd() nt.chdir(CPY_LIB_DIR) for pack_name in nt.listdir(CPY_LIB_DIR): if not is_package(pack_name): continue #Importing all tests takes too long elif pack_name in ["test"]: continue check_package(pack_name) print nt.chdir(cwd) print "------------------------------------------------------------------------" print "--MODULES" for x in nt.listdir(CPY_LIB_DIR): if x.endswith(".py"): mod_name = x.split(".py", 1)[0] else: continue try: import_helper(mod_name) log_ok(mod_name) except Exception, e: log_broken(mod_name, e)
def LoadAllSavedSettings(): import clr clr.AddReference("System.Xml") from System.Xml import * import nt games = [] state = [] allowCaching = False try: reader = XmlTextReader(nt.getcwd() + "\load.xml") while reader.Read() is True: if reader.NodeType == XmlNodeType.Element: if reader.Name == "Game": game = [] game += [reader.GetAttribute("caption")] game += [reader.GetAttribute("type")] game += [int(reader.GetAttribute("y"))] game += [int(reader.GetAttribute("x"))] game += [int(reader.GetAttribute("level"))] game += [int(reader.GetAttribute("dimension"))] games += [game] elif reader.Name == "TopLeftPreviewTile": state += [int(reader.GetAttribute("x"))] state += [int(reader.GetAttribute("y"))] state += [int(reader.GetAttribute("dimension"))] state += [int(reader.GetAttribute("level"))] elif reader.Name == "Cache": if reader.GetAttribute("allow").lower() == "true": allowCaching = True except: print "Error reading load.xml" return [[], [327, 714, 3, 11], True] return [games, state, allowCaching]
def is_package(dir_name): ''' Returns True if dir_name is actually a Python package in the current working directory. ''' #*.py, *.pyd, etc if "." in dir_name: return False #Make sure it exists try: if not nt.stat(dir_name): return False except: return False #Make sure it has an __init__.py try: if "__init__.py" not in nt.listdir(nt.getcwd() + "\\" + dir_name): return False except: return False return True
def run_pkg_helper(filename, ns_name=None, exclude_list = []): #CodePlex 17621 - don't want to run the test package twice if ns_name!=None and ns_name!="__main__" and sys.platform=="win32": return -1 from exceptions import SystemExit #Determine the package structure import nt cwd = nt.getcwd() common_end = 0 for i in xrange(len(cwd)): if cwd[i]!=filename[i]: break common_end+=1 common_end+=1 temp_package = filename[common_end:filename.rfind("\\")+1] temp_package.replace("\\", ".") #get the module names in the package mod_names = [temp_package + x for x in get_mod_names(filename) if x not in exclude_list] mod_names = [x.replace("\\", ".") for x in mod_names] for test_module in mod_names: print "--------------------------------------------------------------------" print "Importing", test_module, "..." try: __import__(test_module) except SystemExit, e: if e.code!=0: raise Exception("Importing '%s' caused an unexpected exit code: %s" % (test_module, str(e.code))) print ""
"-------------------------------------------------------\n") bug_report.write( """Complete list of module attributes that should be removed from IronPython: """) for x in needs_to_be_removed: bug_report.write(" " + x) bug_report.close() return bug_report_name #--MAIN------------------------------------------------------------------------ try: nt.mkdir(nt.getcwd() + "\\bug_reports") except: pass for mod_name in MODULES: #--First figure out what's missing and what's extra in a module # and write this to disk. ipy_should_impl_filename = "bug_reports\\mod_to_impl_%s.log" % mod_name ipy_should_not_impl_filename = "bug_reports\\mod_rm_impl_%s.log" % mod_name IPY_SHOULD_IMPL = open(ipy_should_impl_filename, "w") IPY_SHOULD_NOT_IMPL = open(ipy_should_not_impl_filename, "w") get_cpython_results(mod_name) IPY_SHOULD_IMPL.close() IPY_SHOULD_NOT_IMPL.close()
def test_listdir(): AssertError(TypeError, nt.listdir, None) if is_cpython: #http://ironpython.codeplex.com/workitem/28207 AreEqual(nt.listdir(nt.getcwd()), nt.listdir('.')) else: AreEqual(nt.listdir(''), nt.listdir('.'))
def test_getcwdu(): AreEqual(nt.getcwd(),nt.getcwdu()) nt.mkdir('dir_create_test') AreEqual(nt.listdir(nt.getcwdu()).count('dir_create_test'), 1) nt.rmdir('dir_create_test')
def __init__(self): ### CREATE CONSTANTS ### self.TOP_BORDER = 20 self.SIDE_BORDER = 10 self.BOTTOM_BORDER = 60 ### CREATE INSTANCE VARIABLES ### self.gridDimension = 3 self.normalTileDimension = 128 self.tileDimension = self.normalTileDimension self.grid = [] for i in range(0, self.gridDimension): self.grid += [[]] for j in range(0, self.gridDimension): self.grid[i] += [None] self.gameInProgress = False self.clearCacheOnExit = False self.exitFromMenu = False self.savedSettings = LoadAllSavedSettings() self.savedPuzzles = self.savedSettings[0] self.previewState = self.savedSettings[1] LoadCache() if self.savedSettings[2] == True: TurnOnCache() else: TurnOffCache() ### SET UP MENU ### self.CreateMenu() ### SET UP PANELS ### self.CreatePanels() ### SET PROPERTIES OF THE FORM ### self.Text = "Puzzle" self.BackColor = Color.White w = self.gridDimension * self.tileDimension + 2 * self.SIDE_BORDER + self.menu.Size.Width h = self.gridDimension * self.tileDimension + self.TOP_BORDER + self.BOTTOM_BORDER self.ClientSize = Size(w, h) self.FormClosing += self.formClosing self.FormBorderStyle = FormBorderStyle.Fixed3D self.MaximizeBox = False self.KeyPreview = True ### PLACE WLL BANNER ### self.wllPicture = PictureBox() self.wllPicture.SizeMode = PictureBoxSizeMode.AutoSize import nt try: self.wllPicture.Image = Image.FromFile(nt.getcwd() + "\\banner.bmp") except: self.wllPicture.Image = None self.wllPicture.Location = Point(self.ClientSize.Width - self.wllPicture.Size.Width, self.ClientSize.Height - self.wllPicture.Size.Height) self.Controls.Add(self.wllPicture) try: self.Icon = Icon(nt.getcwd() + "\\icon.ico") except: print "Error loading icon.ico" ### SET UP KEYBOARD HANDLER ### self.KeyDown += self.keyDown ### SET DEFAULT GAME ### #self.SetBoard('a', 47.55, -122.322, 11, 3) self.SetBoard('a', 45.05, 14.26, 5, 3)
''' Created on Jan 26, 2016 @author: Ashwin ''' import zipfile from os.path import dirname from nt import getcwd with zipfile.ZipFile(dirname(getcwd())+'\\data\\0000021344_COCA COLA CO.zip','r') as z: z.extractall(dirname(getcwd())+'\\unzipped')