[Zope3-checkins] CVS: Zope3/src/zope/fssync/tests - tempfiles.py:1.1 test_fsmerger.py:1.4 test_fsutil.py:1.3 test_merger.py:1.11 test_metadata.py:1.3 test_network.py:1.4 test_snarf.py:1.2

Guido van Rossum guido@python.org
Wed, 28 May 2003 10:40:04 -0400


Update of /cvs-repository/Zope3/src/zope/fssync/tests
In directory cvs.zope.org:/tmp/cvs-serv1551

Modified Files:
	test_fsmerger.py test_fsutil.py test_merger.py 
	test_metadata.py test_network.py test_snarf.py 
Added Files:
	tempfiles.py 
Log Message:
Refactor tests: move temporary creation to a separate module.

=== Added File Zope3/src/zope/fssync/tests/tempfiles.py ===
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Handy mixin for test case classes to manipulate temporary files.

$Id: tempfiles.py,v 1.1 2003/05/28 14:40:04 gvanrossum Exp $
"""

import os
import shutil
import tempfile
import unittest

class TempFiles(unittest.TestCase):

    def setUp(self):
        """Initialize the list of temporary names."""
        self.tempnames = []

    def tearDown(self):
        """Clean up temporary names."""
        for fn in self.tempnames:
            if os.path.isdir(fn):
                shutil.rmtree(fn)
            elif os.path.isfile(fn):
                os.remove(fn)

    def tempdir(self):
        """Create and register a temporary directory."""
        dir = tempfile.mktemp()
        self.tempnames.append(dir)
        os.mkdir(dir)
        return dir

    def tempfile(self, data=None, mode="w"):
        """Create and register a temporary file."""
        tfn = tempfile.mktemp()
        self.tempnames.append(tfn)
        if data is not None:
            self.writefile(data, tfn, mode)
        return tfn

    def cmpfile(self, fn1, fn2, mode="r"):
        """Compare two files for equality; they must exist."""
        assert mode in ("r", "rb")
        data1 = self.readfile(fn1)
        data2 = self.readfile(fn2)
        return data1 == data2

    def readfile(self, fn, mode="r"):
        """Read data from a given file."""
        assert mode in ("r", "rb")
        f = open(fn, mode)
        try:
            data = f.read()
        finally:
            f.close()
        return data

    def writefile(self, data, fn, mode="w"):
        """Write data to a given file."""
        assert mode in ("w", "wb")
        f = open(fn, mode)
        try:
            f.write(data)
        finally:
            f.close()


=== Zope3/src/zope/fssync/tests/test_fsmerger.py 1.3 => 1.4 ===
--- Zope3/src/zope/fssync/tests/test_fsmerger.py:1.3	Wed May 28 09:48:16 2003
+++ Zope3/src/zope/fssync/tests/test_fsmerger.py	Wed May 28 10:40:04 2003
@@ -17,52 +17,24 @@
 """
 
 import os
-import shutil
 import unittest
-import tempfile
 
 from os.path import exists, isdir, isfile, realpath, normcase, split, join
 
 from zope.fssync.fsmerger import FSMerger
 
 from zope.fssync.tests.mockmetadata import MockMetadata
+from zope.fssync.tests.tempfiles import TempFiles
 
-class TestFSMerger(unittest.TestCase):
+class TestFSMerger(TempFiles):
 
     def setUp(self):
+        TempFiles.setUp(self)
         # Create a mock metadata database
         self.metadata = MockMetadata()
-        # Create a list of temporary names to be removed in tearDown
-        self.tempnames = []
         # Create a handy entry
         self.entry = {"path": "/foo"}
 
-    def tearDown(self):
-        # Clean up temporary files and directories
-        for fn in self.tempnames:
-            if isdir(fn):
-                shutil.rmtree(fn)
-            elif isfile(fn):
-                os.remove(fn)
-
-    def addtempdir(self):
-        # Create and register a temporary directory
-        dir = tempfile.mktemp()
-        self.tempnames.append(dir)
-        os.mkdir(dir)
-        return dir
-
-    def addtempfile(self, data):
-        # Create and register a temporary file
-        filename = tempfile.mktemp()
-        self.tempnames.append(filename)
-        f = open(filename, "w")
-        try:
-            f.write(data)
-        finally:
-            f.close()
-        return filename
-
     diff3ok = None
 
     def check_for_diff3(self):
@@ -73,9 +45,9 @@
     def diff3_check(self):
         if not hasattr(os, "popen"):
             return False
-        f1 = self.addtempfile("a")
-        f2 = self.addtempfile("b")
-        f3 = self.addtempfile("b")
+        f1 = self.tempfile("a")
+        f2 = self.tempfile("b")
+        f3 = self.tempfile("b")
         pipe = os.popen("diff3 -m -E %s %s %s" % (f1, f2, f3), "r")
         output = pipe.read()
         sts = pipe.close()
@@ -235,8 +207,8 @@
         reports = []
         m = FSMerger(self.metadata, reports.append)
 
-        localtopdir = self.addtempdir()
-        remotetopdir = self.addtempdir()
+        localtopdir = self.tempdir()
+        remotetopdir = self.tempdir()
         localdir = join(localtopdir, "local")
         remotedir = join(remotetopdir, "remote")
         os.mkdir(localdir)


=== Zope3/src/zope/fssync/tests/test_fsutil.py 1.2 => 1.3 ===
--- Zope3/src/zope/fssync/tests/test_fsutil.py:1.2	Thu May 15 07:25:40 2003
+++ Zope3/src/zope/fssync/tests/test_fsutil.py	Wed May 28 10:40:04 2003
@@ -17,12 +17,12 @@
 """
 
 import os
-import tempfile
 import unittest
 
 from os.path import split, join, exists, isdir, isfile
 
 from zope.fssync import fsutil
+from zope.fssync.tests.tempfiles import TempFiles
 
 def FIX(path):
     # This fixes only relative paths
@@ -31,7 +31,7 @@
     parts = [mapping.get(x, x) for x in parts]
     return os.path.join(*parts)
 
-class TestFSUtil(unittest.TestCase):
+class TestFSUtil(TempFiles):
 
     def test_split(self):
         self.assertEqual(fsutil.split(FIX("foo/bar")), ("foo", "bar"))
@@ -58,30 +58,17 @@
                          FIX("foo/@@Zope/Annotations/bar"))
 
     def test_ensuredir(self):
-        tmpdir = tempfile.mktemp()
-        try:
-            self.assertEqual(exists(tmpdir), False)
-            self.assertEqual(isdir(tmpdir), False)
-            fsutil.ensuredir(tmpdir)
-            self.assertEqual(isdir(tmpdir), True)
-            fsutil.ensuredir(tmpdir)
-            self.assertEqual(isdir(tmpdir), True)
-        finally:
-            if isdir(tmpdir):
-                os.rmdir(tmpdir)
+        tmpdir = self.tempfile(None)
+        self.assertEqual(exists(tmpdir), False)
+        self.assertEqual(isdir(tmpdir), False)
+        fsutil.ensuredir(tmpdir)
+        self.assertEqual(isdir(tmpdir), True)
+        fsutil.ensuredir(tmpdir)
+        self.assertEqual(isdir(tmpdir), True)
 
     def test_ensuredir_error(self):
-        tmpfile = tempfile.mktemp()
-        try:
-            f = open(tmpfile, "w")
-            try:
-                f.write("x\n")
-            finally:
-                f.close()
-            self.assertRaises(OSError, fsutil.ensuredir, tmpfile)
-        finally:
-            if isfile(tmpfile):
-                os.remove(tmpfile)
+        tmpfile = self.tempfile("x\n")
+        self.assertRaises(OSError, fsutil.ensuredir, tmpfile)
 
 def test_suite():
     loader = unittest.TestLoader()


=== Zope3/src/zope/fssync/tests/test_merger.py 1.10 => 1.11 ===
--- Zope3/src/zope/fssync/tests/test_merger.py:1.10	Wed May 28 09:48:16 2003
+++ Zope3/src/zope/fssync/tests/test_merger.py	Wed May 28 10:40:04 2003
@@ -17,60 +17,19 @@
 """
 
 import os
-import shutil
 import unittest
-import tempfile
 
-from os.path import exists, isdir, isfile, realpath, normcase
+from os.path import exists
 
 from zope.fssync.merger import Merger
 
 from zope.fssync.tests.mockmetadata import MockMetadata
+from zope.fssync.tests.tempfiles import TempFiles
 
 added = {"flag": "added"}
 removed = {"flag": "removed"}
 
-class TestMerger(unittest.TestCase):
-
-    def setUp(self):
-        unittest.TestCase.setUp(self)
-        # Create a list of temporary files to clean up at the end
-        self.tempfiles = []
-
-    def tearDown(self):
-        # Clean up temporary files (or directories)
-        for fn in self.tempfiles:
-            if isdir(fn):
-                shutil.rmtree(fn)
-            elif isfile(fn):
-                os.remove(fn)
-        unittest.TestCase.tearDown(self)
-
-    def addfile(self, data, suffix="", mode="w"):
-        # Register a temporary file; write data to it if given
-        file = tempfile.mktemp(suffix)
-        self.tempfiles.append(file)
-        if data is not None:
-            f = open(file, mode)
-            try:
-                f.write(data)
-            finally:
-                f.close()
-        return file
-
-    def cmpfile(self, file1, file2, mode="r"):
-        # Compare two files; they must exist
-        f1 = open(file1, mode)
-        try:
-            data1 = f1.read()
-        finally:
-            f1.close()
-        f2 = open(file2, mode)
-        try:
-            data2 = f2.read()
-        finally:
-            f2.close()
-        return data1 == data2
+class TestMerger(TempFiles):
 
     diff3ok = None
 
@@ -82,9 +41,9 @@
     def diff3_check(self):
         if not hasattr(os, "popen"):
             return False
-        f1 = self.addfile("a")
-        f2 = self.addfile("b")
-        f3 = self.addfile("b")
+        f1 = self.tempfile("a")
+        f2 = self.tempfile("b")
+        f3 = self.tempfile("b")
         pipe = os.popen("diff3 -m -E %s %s %s" % (f1, f2, f3), "r")
         output = pipe.read()
         sts = pipe.close()
@@ -93,9 +52,9 @@
     def runtest(self, localdata, origdata, remotedata,
                 localmetadata, remotemetadata, exp_localdata,
                 exp_action, exp_state, exp_merge_state=None):
-        local = self.addfile(localdata)
-        orig = self.addfile(origdata)
-        remote = self.addfile(remotedata)
+        local = self.tempfile(localdata)
+        orig = self.tempfile(origdata)
+        remote = self.tempfile(remotedata)
         md = MockMetadata()
         if localmetadata is not None:
             md.setmetadata(local, localmetadata)


=== Zope3/src/zope/fssync/tests/test_metadata.py 1.2 => 1.3 ===
--- Zope3/src/zope/fssync/tests/test_metadata.py:1.2	Mon May 12 16:41:23 2003
+++ Zope3/src/zope/fssync/tests/test_metadata.py	Wed May 28 10:40:04 2003
@@ -17,42 +17,20 @@
 """
 
 import os
-import shutil
 import unittest
-import tempfile
 
-from os.path import exists, isdir, isfile, split, join, realpath, normcase
+from os.path import exists, dirname, isfile, join
 
 from zope.xmlpickle import loads, dumps
 
 from zope.fssync.metadata import Metadata
+from zope.fssync.tests.tempfiles import TempFiles
 
-class TestMetadata(unittest.TestCase):
-
-    def setUp(self):
-        unittest.TestCase.setUp(self)
-        # Create a list of temporary files to clean up at the end
-        self.tempfiles = []
-
-    def tearDown(self):
-        # Clean up temporary files (or directories)
-        for fn in self.tempfiles:
-            if isdir(fn):
-                shutil.rmtree(fn)
-            elif isfile(fn):
-                os.remove(fn)
-        unittest.TestCase.tearDown(self)
-
-    def adddir(self):
-        # Register and create a temporary directory
-        dir = tempfile.mktemp()
-        self.tempfiles.append(dir)
-        os.mkdir(dir)
-        return dir
+class TestMetadata(TempFiles):
 
     def test_initial_state(self):
         md = Metadata()
-        dir = self.adddir()
+        dir = self.tempdir()
         self.assertEqual(md.getnames(dir), [])
         foo = join(dir, "foo")
         self.assertEqual(md.getentry(foo), {})
@@ -60,7 +38,7 @@
 
     def test_adding(self):
         md = Metadata()
-        dir = self.adddir()
+        dir = self.tempdir()
         foo = join(dir, "foo")
         e = md.getentry(foo)
         e["hello"] = "world"
@@ -71,14 +49,14 @@
 
     def test_deleting(self):
         md, foo = self.test_adding()
-        dir = os.path.dirname(foo)
+        dir = dirname(foo)
         md.getentry(foo).clear()
         self.assertEqual(md.getentry(foo), {})
         self.assertEqual(md.getnames(dir), [])
 
     def test_flush(self):
         md, foo = self.test_adding()
-        dir = os.path.dirname(foo)
+        dir = dirname(foo)
         md.flush()
         efile = join(dir, "@@Zope", "Entries.xml")
         self.assert_(isfile(efile))


=== Zope3/src/zope/fssync/tests/test_network.py 1.3 => 1.4 ===
--- Zope3/src/zope/fssync/tests/test_network.py:1.3	Thu May 15 16:03:05 2003
+++ Zope3/src/zope/fssync/tests/test_network.py	Wed May 28 10:40:04 2003
@@ -17,55 +17,22 @@
 """
 
 import os
-import shutil
 import unittest
-import tempfile
 
 from StringIO import StringIO
 
 from os.path import isdir, isfile, join
 
 from zope.fssync.fssync import Network, Error
+from zope.fssync.tests.tempfiles import TempFiles
 
 sample_rooturl = "http://user:passwd@host:8080/path"
 
-class TestNetwork(unittest.TestCase):
+class TestNetwork(TempFiles):
 
     def setUp(self):
-        unittest.TestCase.setUp(self)
+        TempFiles.setUp(self)
         self.network = Network()
-        # Create a list of temporary files to clean up at the end
-        self.tempfiles = []
-
-    def tearDown(self):
-        # Clean up temporary files (or directories)
-        for fn in self.tempfiles:
-            if isdir(fn):
-                shutil.rmtree(fn)
-            elif isfile(fn):
-                os.remove(fn)
-        unittest.TestCase.tearDown(self)
-
-    def adddir(self):
-        # Create and register a temporary directory
-        dir = tempfile.mktemp()
-        self.tempfiles.append(dir)
-        os.mkdir(dir)
-        return dir
-
-    def cmpfile(self, file1, file2, mode="r"):
-        # Compare two files; they must exist
-        f1 = open(file1, mode)
-        try:
-            data1 = f1.read()
-        finally:
-            f1.close()
-        f2 = open(file2, mode)
-        try:
-            data2 = f2.read()
-        finally:
-            f2.close()
-        return data1 == data2
 
     def test_initial_state(self):
         self.assertEqual(self.network.rooturl, None)
@@ -93,11 +60,11 @@
 
     def test_findrooturl_notfound(self):
         # XXX This test will fail if a file /tmp/@@Zope/Root exists :-(
-        target = self.adddir()
+        target = self.tempdir()
         self.assertEqual(self.network.findrooturl(target), None)
 
     def test_findrooturl_found(self):
-        target = self.adddir()
+        target = self.tempdir()
         zdir = join(target, "@@Zope")
         os.mkdir(zdir)
         rootfile = join(zdir, "Root")
@@ -108,7 +75,7 @@
 
     def test_saverooturl(self):
         self.network.setrooturl(sample_rooturl)
-        target = self.adddir()
+        target = self.tempdir()
         zdir = join(target, "@@Zope")
         os.mkdir(zdir)
         rootfile = join(zdir, "Root")
@@ -119,7 +86,7 @@
         self.assertEqual(data.strip(), sample_rooturl)
 
     def test_loadrooturl(self):
-        target = self.adddir()
+        target = self.tempdir()
         self.assertRaises(Error, self.network.loadrooturl, target)
         zdir = join(target, "@@Zope")
         os.mkdir(zdir)


=== Zope3/src/zope/fssync/tests/test_snarf.py 1.1 => 1.2 ===
--- Zope3/src/zope/fssync/tests/test_snarf.py:1.1	Tue May 27 10:46:07 2003
+++ Zope3/src/zope/fssync/tests/test_snarf.py	Wed May 28 10:40:04 2003
@@ -17,13 +17,12 @@
 """
 
 import os
-import shutil
 import unittest
-import tempfile
 
 from StringIO import StringIO
 
 from zope.fssync.snarf import copybytes, Snarfer, Unsnarfer
+from zope.fssync.tests.tempfiles import TempFiles
 
 class TestCopyBytes(unittest.TestCase):
 
@@ -54,38 +53,12 @@
         self.assertRaises(IOError, copybytes, 6, istr, ostr)
 
 
-class TestSnarfer(unittest.TestCase):
+class TestSnarfer(TempFiles):
 
     def setUp(self):
+        TempFiles.setUp(self)
         self.ostr = StringIO()
         self.snf = Snarfer(self.ostr)
-        self.tempfiles = []
-
-    def tearDown(self):
-        for tfn in self.tempfiles:
-            if os.path.isdir(tfn):
-                shutil.rmtree(tfn)
-            elif os.path.exists(tfn):
-                os.remove(tfn)
-
-    def writefile(self, fn, data):
-        fp = open(fn, "wb")
-        try:
-            fp.write(data)
-        finally:
-            fp.close()
-
-    def tempfile(self, data):
-        tfn = tempfile.mktemp()
-        self.tempfiles.append(tfn)
-        self.writefile(tfn, data)
-        return tfn
-
-    def tempdir(self):
-        tfn = tempfile.mktemp()
-        self.tempfiles.append(tfn)
-        os.mkdir(tfn)
-        return tfn
 
     def test_addstream(self):
         istr = StringIO("12345")
@@ -143,13 +116,13 @@
         f1 = os.path.join(tfn, "f1")
         f1a = os.path.join(tfn, "f1~")
         f2 = os.path.join(tfn, "f2")
-        self.writefile(f1, "f1data")
-        self.writefile(f1a, "f1adata")
-        self.writefile(f2, "f2data")
+        self.writefile("f1data", f1)
+        self.writefile("f1adata", f1a)
+        self.writefile("f2data", f2)
         d1 = os.path.join(tfn, "d1")
         os.mkdir(d1)
         d1f1 = os.path.join(d1, "f1")
-        self.writefile(d1f1, "d1f1data")
+        self.writefile("d1f1data", d1f1)
         return tfn
 
 class TestUnsnarfer(unittest.TestCase):