• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2# Copyright (c) 2011 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Tests for pyauto_utils."""
7
8import glob
9import os
10import shutil
11import tempfile
12import unittest
13
14import pyauto_utils
15
16
17class ExistingPathReplacerTest(unittest.TestCase):
18  """Tests for ExistingPathReplacer."""
19
20  def setUp(self):
21    self._workdir = tempfile.mkdtemp()
22    self.assertEqual(0, len(os.listdir(self._workdir)))
23
24  def tearDown(self):
25    shutil.rmtree(self._workdir, ignore_errors=True)
26
27  def _CreateFile(self, path):
28    fp = open(path, 'w')
29    fp.write('magic')
30    fp.close()
31
32  def _IsOrigFile(self, path):
33    if not os.path.isfile(path):
34      return False
35    return open(path).read() == 'magic'
36
37  def testNonExistingFile(self):
38    """Test when the requested file does not exist."""
39    myfile = os.path.join(self._workdir, 'myfile.txt')
40    self.assertFalse(os.path.isfile(myfile))
41    r = pyauto_utils.ExistingPathReplacer(myfile, path_type='file')
42    self.assertTrue(os.path.isfile(myfile))
43    del r
44    self.assertEqual(0, len(os.listdir(self._workdir)))
45
46  def testExistingFile(self):
47    """Test when the requested file exists."""
48    myfile = os.path.join(self._workdir, 'myfile.txt')
49    self._CreateFile(myfile)
50    self.assertTrue(self._IsOrigFile(myfile))
51    r = pyauto_utils.ExistingPathReplacer(myfile, path_type='file')
52    self.assertFalse(self._IsOrigFile(myfile))
53    self.assertEqual(2, len(os.listdir(self._workdir)))
54    del r
55    self.assertEqual(1, len(os.listdir(self._workdir)))
56    self.assertTrue(self._IsOrigFile(myfile))
57
58  def testNonExistingDir(self):
59    """Test when the requested dir does not exist."""
60    mydir = os.path.join(self._workdir, 'mydir')
61    self.assertFalse(os.path.isdir(mydir))
62    r = pyauto_utils.ExistingPathReplacer(mydir, path_type='dir')
63    self.assertTrue(os.path.isdir(mydir))
64    self.assertEqual(0, len(os.listdir(mydir)))
65    del r
66    self.assertFalse(os.path.isdir(mydir))
67
68  def testExistingDir(self):
69    """Test when the requested dir exists."""
70    # Create a dir with one file
71    mydir = os.path.join(self._workdir, 'mydir')
72    os.makedirs(mydir)
73    self.assertEqual(1, len(os.listdir(self._workdir)))
74    myfile = os.path.join(mydir, 'myfile.txt')
75    open(myfile, 'w').close()
76    self.assertTrue(os.path.isfile(myfile))
77    r = pyauto_utils.ExistingPathReplacer(mydir)
78    self.assertEqual(2, len(os.listdir(self._workdir)))
79    self.assertFalse(os.path.isfile(myfile))
80    del r
81    self.assertEqual(1, len(os.listdir(self._workdir)))
82    self.assertTrue(os.path.isfile(myfile))
83
84
85if __name__ == '__main__':
86  unittest.main()
87