Skip to content

Commit

Permalink
Merge pull request #95 from 3c2b2ff5/python3_first
Browse files Browse the repository at this point in the history
first step to make code python3 compatible
  • Loading branch information
jaqx0r authored Oct 29, 2019
2 parents b34210e + a4f8f39 commit a79e231
Show file tree
Hide file tree
Showing 41 changed files with 463 additions and 401 deletions.
10 changes: 5 additions & 5 deletions nss_cache/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def __init__(self):
handler = logging.handlers.SysLogHandler(address='/dev/log',
facility=facility)
except socket.error:
print '/dev/log could not be opened; falling back on stderr.'
print('/dev/log could not be opened; falling back on stderr.')
# Omitting an argument to StreamHandler results in sys.stderr being
# used.
handler = logging.StreamHandler()
Expand Down Expand Up @@ -188,7 +188,7 @@ def Run(self, args, env):
# Parse the commandline.
try:
(options, args) = self.parser.parse_args(args)
except SystemExit, e:
except SystemExit as e:
# OptionParser objects raise SystemExit (error() calls exit()
# calls sys.exit()) upon a parser error.
# This can be handled better by overriding error or monkeypatching
Expand All @@ -213,7 +213,7 @@ def Run(self, args, env):

# Identify the command to dispatch.
if not args:
print 'No command given'
print('No command given')
self.parser.print_help()
return os.EX_USAGE
# print global help if command is 'help' with no argument
Expand All @@ -232,13 +232,13 @@ def Run(self, args, env):
command_callable = getattr(command, command_name.capitalize())
except AttributeError:
self.log.warn('%s is not implemented', command_name)
print 'command %r is not implemented' % command_name
print('command %r is not implemented' % command_name)
self.parser.print_help()
return os.EX_SOFTWARE

try:
retval = command_callable().Run(conf=conf, args=args)
except error.SourceUnavailable, e:
except error.SourceUnavailable as e:
self.log.error('Problem with configured data source: %s', e)
return os.EX_TEMPFAIL

Expand Down
20 changes: 10 additions & 10 deletions nss_cache/app_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

import logging
import os
import StringIO
from io import BytesIO as StringIO
import sys
import unittest

Expand All @@ -31,7 +31,7 @@ class TestNssCacheApp(unittest.TestCase):
"""Unit tests for NssCacheApp class."""

def setUp(self):
dev_null = StringIO.StringIO()
dev_null = StringIO()
self.stdout = sys.stdout
sys.stdout = dev_null

Expand Down Expand Up @@ -85,14 +85,14 @@ def testParseCommandLineConfigFile(self):

def testBadOptionsCauseNoExit(self):
a = app.NssCacheApp()
stderr_buffer = StringIO.StringIO()
stderr_buffer = StringIO()
old_stderr = sys.stderr
sys.stderr = stderr_buffer
self.assertEquals(2, a.Run(['--invalid'], {}))
sys.stderr = old_stderr

def testHelpOptionPrintsGlobalHelp(self):
stdout_buffer = StringIO.StringIO()
stdout_buffer = StringIO()
a = app.NssCacheApp()
old_stdout = sys.stdout
sys.stdout = stdout_buffer
Expand All @@ -109,7 +109,7 @@ def testHelpOptionPrintsGlobalHelp(self):

def testHelpCommandOutput(self):
# trap stdout into a StringIO
stdout_buffer = StringIO.StringIO()
stdout_buffer = StringIO()
a = app.NssCacheApp()
old_stdout = sys.stdout
sys.stdout = stdout_buffer
Expand All @@ -127,7 +127,7 @@ def testHelpCommandOutput(self):
# # This will fail when run under 'nosetests -s' because nose will
# # also intercept sys.stdout :( (Recommend refactoring NssCacheApp
# # to take in an output stream for help and usage?
# output = cStringIO.StringIO()
# output = StringIO()
# stdout = sys.stdout
# sys.stdout = output

Expand All @@ -151,16 +151,16 @@ def testHelpCommandOutput(self):
# self.levels = []

# def emit(self, record):
# print record
# print(record)
# self.levels.append(record.levelno)
# print self.levels
# print(self.levels)

# handler = test_handler()
# a = app.NssCacheApp()
# print "log:", a.log
# print("log:", a.log)
# a.log.addHandler(handler)
# a.log.debug2('logged at level debug2')
# print handler.levels
# print(handler.levels)
# self.failUnless(5 in handler.levels)

# def testVerboseLoggingLevel(self):
Expand Down
3 changes: 0 additions & 3 deletions nss_cache/caches/cache_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,3 @@ def Create(conf, map_name, automount_mountpoint=None):

files.RegisterAllImplementations(RegisterImplementation)
nssdb.RegisterAllImplementations(RegisterImplementation)



6 changes: 3 additions & 3 deletions nss_cache/caches/cache_factory_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ class DummyCache(caches.Cache):
old_cache_implementations = cache_factory._cache_implementations
cache_factory._cache_implementations = {}
cache_factory.RegisterImplementation('dummy', 'dummy', DummyCache)
self.failUnlessEqual(1, len(cache_factory._cache_implementations))
self.failUnlessEqual(1, len(cache_factory._cache_implementations['dummy']))
self.failUnlessEqual(DummyCache,
self.assertEqual(1, len(cache_factory._cache_implementations))
self.assertEqual(1, len(cache_factory._cache_implementations['dummy']))
self.assertEqual(DummyCache,
cache_factory._cache_implementations['dummy']['dummy'])
cache_factory._cache_implementations = old_cache_implementations

Expand Down
6 changes: 3 additions & 3 deletions nss_cache/caches/caches.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def _Begin(self):
self.temp_cache_file = os.fdopen(fd, 'w+b')
self.log.debug('opened temporary cache filename %r',
self.temp_cache_filename)
except OSError, e:
except OSError as e:
if e.errno == errno.EACCES:
self.log.info('Got OSError (%s) when trying to create temporary file',
e)
Expand All @@ -116,7 +116,7 @@ def _Rollback(self):
# Safe file remove (ignore "no such file or directory" errors):
try:
os.remove(self.temp_cache_filename)
except OSError, e:
except OSError as e:
if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
raise # re-raise exception if a different error occured

Expand Down Expand Up @@ -150,7 +150,7 @@ def _Commit(self):
uid = stat_info.st_uid
gid = stat_info.st_gid
os.chown(self.temp_cache_filename, uid, gid)
except OSError, e:
except OSError as e:
if e.errno == errno.ENOENT:
if self.map_name == "sshkey":
os.chmod(self.temp_cache_filename,
Expand Down
5 changes: 4 additions & 1 deletion nss_cache/caches/caches_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@
import tempfile
import unittest

import mox
try:
import mox
except ImportError:
import mox3

from nss_cache import config
from nss_cache.caches import caches
Expand Down
15 changes: 9 additions & 6 deletions nss_cache/caches/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,23 @@
import shutil
import stat
import sys
import ConfigParser
try:
from ConfigParser import SafeConfigParser as ConfigParser
except ImportError:
from configparser import ConfigParser

from nss_cache import config
from nss_cache import error
from nss_cache.caches import caches
from nss_cache.util import file_formats

if sys.version >= (2, 5):
if sys.version_info[0:2] >= (2, 5):
def LongestLength(l): return len(max(l, key=len))
else: # Python < 2.4, 50% slower
def LongestLength(l): return max([len(x) for x in l])

# Load suffix config variables
parser = ConfigParser.ConfigParser()
parser = ConfigParser()
for i in sys.argv:
if ('nsscache.conf') in i:
# Remove '--config-file=' from the string
Expand Down Expand Up @@ -237,8 +240,8 @@ def WriteIndex(self):
self.log.debug('Writing index %s', tmp_index_filename)

index = self._indices[index_name]
key_length = LongestLength(index.keys())
pos_length = LongestLength(index.values())
key_length = LongestLength(list(index.keys()))
pos_length = LongestLength(list(index.values()))
max_length = key_length + pos_length
# Open for write/truncate
index_file = open(tmp_index_filename, 'w')
Expand All @@ -249,7 +252,7 @@ def WriteIndex(self):
uid = stat_info.st_uid
gid = stat_info.st_gid
os.chown(tmp_index_filename, uid, gid)
except OSError, e:
except OSError as e:
if e.errno == errno.ENOENT:
os.chmod(tmp_index_filename,
stat.S_IRUSR|stat.S_IWUSR|stat.S_IRGRP|stat.S_IROTH)
Expand Down
23 changes: 13 additions & 10 deletions nss_cache/caches/files_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@
import unittest
import sys

import mox
try:
import mox
except ImportError:
import mox3

from nss_cache import config
from nss_cache.maps import automount
Expand All @@ -49,7 +52,7 @@ def tearDown(self):

def testInstantiation(self):
cache = files.FilesCache(self.config, config.MAP_PASSWORD)
self.failIfEqual(None, cache)
self.assertNotEqual(None, cache)

def testWrite(self):
cache = files.FilesPasswdMapHandler(self.config)
Expand All @@ -76,7 +79,7 @@ def testCacheFilenameSuffixOption(self):
cache._Commit()
expected_cache_filename = os.path.join(self.workdir,
'test.blarg')
self.failUnless(os.path.exists(expected_cache_filename))
self.assertTrue(os.path.exists(expected_cache_filename))

def testWritePasswdEntry(self):
"""We correctly write a typical entry in /etc/passwd format."""
Expand Down Expand Up @@ -173,14 +176,14 @@ def testAutomountSetsFilename(self):
# also tests GetMapLocation() because it uses it :)
conf = {'dir': self.workdir, 'cache_filename_suffix': ''}
cache = files.FilesAutomountMapHandler(conf)
self.assertEquals(cache.GetMapLocation(), '%s/auto.master' % self.workdir)
self.assertEqual(cache.GetMapLocation(), '%s/auto.master' % self.workdir)

cache = files.FilesAutomountMapHandler(conf, automount_mountpoint='/home')
self.assertEquals(cache.GetMapLocation(), '%s/auto.home' % self.workdir)
self.assertEqual(cache.GetMapLocation(), '%s/auto.home' % self.workdir)

cache = files.FilesAutomountMapHandler(conf,
automount_mountpoint='/usr/meh')
self.assertEquals(cache.GetMapLocation(), '%s/auto.usr_meh' % self.workdir)
self.assertEqual(cache.GetMapLocation(), '%s/auto.usr_meh' % self.workdir)

def testCacheFileDoesNotExist(self):
"""Make sure we just get an empty map rather than exception."""
Expand All @@ -201,15 +204,15 @@ def testIndexCreation(self):
cache.WriteIndex()

index_filename = cache.GetCacheFilename() + '.ixname'
self.failUnless(os.path.exists(index_filename),
self.assertTrue(os.path.exists(index_filename),
'Index not created %s' % index_filename)
f = open(index_filename)
self.assertEqual('bar\x0015\x00\x00\n', f.readline())
self.assertEqual('foo\x000\x00\x00\x00\n', f.readline())
self.assertEqual('quux\x0030\x00\n', f.readline())

index_filename = cache.GetCacheFilename() + '.ixuid'
self.failUnless(os.path.exists(index_filename),
self.assertTrue(os.path.exists(index_filename),
'Index not created %s' % index_filename)
f = open(index_filename)
self.assertEqual('10\x000\x00\x00\n', f.readline())
Expand All @@ -228,10 +231,10 @@ def testWriteCacheAndIndex(self):
self.assertTrue('foo' in written)
self.assertTrue('bar' in written)
index_filename = cache.GetCacheFilename() + '.ixname'
self.failUnless(os.path.exists(index_filename),
self.assertTrue(os.path.exists(index_filename),
'Index not created %s' % index_filename)
index_filename = cache.GetCacheFilename() + '.ixuid'
self.failUnless(os.path.exists(index_filename),
self.assertTrue(os.path.exists(index_filename),
'Index not created %s' % index_filename)

entries = [passwd.PasswdMapEntry(dict(name='foo', uid=10, gid=10)),
Expand Down
9 changes: 6 additions & 3 deletions nss_cache/caches/nssdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@

__author__ = 'jaq@google.com (Jamie Wilkinson)'

import bsddb
try:
from bsddb import btopen
except ImportError:
from bsddb3 import btopen
import fcntl
import os
import select
Expand Down Expand Up @@ -115,7 +118,7 @@ def _LoadBdbCacheFile(self, data):
self.log.debug('cache file does not exist: %r', db_file)
raise error.CacheNotFound('cache file does not exist: %r' % db_file)

db = bsddb.btopen(db_file, 'r')
db = btopen(db_file, 'r')
for k in db:
if self.IsMapPrimaryKey(k):
password_entry = self.ConvertValueToMapEntry(db[k])
Expand Down Expand Up @@ -253,7 +256,7 @@ def Verify(self, written_keys):
EmptyMap: The cache being verified is empty.
"""
self.log.debug('verification started %s', self.temp_cache_filename)
db = bsddb.btopen(self.temp_cache_filename, 'r')
db = btopen(self.temp_cache_filename, 'r')
# cast keys to a set for fast __contains__ lookup in the loop
# following
cache_keys = set(db)
Expand Down
Loading

0 comments on commit a79e231

Please sign in to comment.