import os
import os.path
import tempfile
import shutil
import subprocess
import imp
from nose.tools import eq_
from nose.tools import with_setup


class BaseRewriteScript(object):
    def __init__(self):
        info = imp.find_module('runner', ['lib/build_pack_utils'])
        self.run = imp.load_module('runner', *info)

    def setUp(self):
        self.rewrite = os.path.abspath("bin/rewrite")
        self.env = {'PYTHONPATH': os.path.abspath('lib')}
        self.env.update(os.environ)
        # setup config
        self.cfg_dir = tempfile.mkdtemp(prefix='config-')
        os.rmdir(self.cfg_dir)
        # setup directory to run from
        self.run_dir = tempfile.mkdtemp(prefix='run-')
        os.makedirs(os.path.join(self.run_dir, 'logs'))
        os.makedirs(os.path.join(self.run_dir, 'bin'))

    def tearDown(self):
        if os.path.exists(self.cfg_dir):
            shutil.rmtree(self.cfg_dir)
        if os.path.exists(self.run_dir):
            shutil.rmtree(self.run_dir)


class TestRewriteScriptPhp(BaseRewriteScript):
    def __init__(self):
        BaseRewriteScript.__init__(self)

    def setUp(self):
        BaseRewriteScript.setUp(self)
        shutil.copytree('defaults/config/php/5.5.x', self.cfg_dir)

    def tearDown(self):
        BaseRewriteScript.tearDown(self)

    @with_setup(setup=setUp, teardown=tearDown)
    def test_rewrite_no_args(self):
        try:
            self.run.check_output(self.rewrite,
                                  cwd=os.path.join(self.run_dir, 'bin'),
                                  env=self.env,
                                  stderr=subprocess.STDOUT,
                                  shell=True)
            assert False
        except self.run.CalledProcessError, e:
            eq_('Argument required!  Specify path to configuration '
                'directory.\n', e.output)
            eq_(255, e.returncode)

    @with_setup(setup=setUp, teardown=tearDown)
    def test_rewrite_arg_file(self):
        try:
            cfg_file = os.path.join(self.cfg_dir, 'php.ini')
            self.run.check_output("%s %s" % (self.rewrite, cfg_file),
                                  env=self.env,
                                  cwd=os.path.join(self.run_dir, 'bin'),
                                  stderr=subprocess.STDOUT,
                                  shell=True)
            assert False
        except self.run.CalledProcessError, e:
            eq_('Path [%s] is not a directory.\n' % cfg_file, e.output)
            eq_(255, e.returncode)

    @with_setup(setup=setUp, teardown=tearDown)
    def test_rewrite_arg_dir(self):
        res = self.run.check_output("%s %s" % (self.rewrite, self.cfg_dir),
                                    env=self.env,
                                    cwd=os.path.join(self.run_dir, 'bin'),
                                    stderr=subprocess.STDOUT,
                                    shell=True)
        eq_('', res)
        with open(os.path.join(self.cfg_dir, 'php.ini')) as fin:
            cfgFile = fin.read()
            eq_(-1, cfgFile.find('@{HOME}'))
            eq_(-1, cfgFile.find('@{TMPDIR}'))
        with open(os.path.join(self.cfg_dir, 'php-fpm.conf')) as fin:
            cfgFile = fin.read()
            eq_(-1, cfgFile.find('@{HOME}'))
            eq_(-1, cfgFile.find('@{TMPDIR}'))
            eq_(True, cfgFile.find('www@my.domain.com') >= 0)


class TestRewriteScriptWithHttpd(BaseRewriteScript):
    def __init__(self):
        BaseRewriteScript.__init__(self)

    def setUp(self):
        BaseRewriteScript.setUp(self)
        shutil.copytree('defaults/config/httpd/2.4.x', self.cfg_dir)

    def tearDown(self):
        BaseRewriteScript.tearDown(self)

    @with_setup(setup=setUp, teardown=tearDown)
    def test_rewrite_with_sub_dirs(self):
        res = self.run.check_output("%s %s" % (self.rewrite, self.cfg_dir),
                                    env=self.env,
                                    cwd=os.path.join(self.run_dir, 'bin'),
                                    stderr=subprocess.STDOUT,
                                    shell=True)
        eq_('', res)
        for root, dirs, files in os.walk(self.cfg_dir):
            for f in files:
                with open(os.path.join(root, f)) as fin:
                    eq_(-1, fin.read().find('@{'))


class TestRewriteScriptWithNginx(BaseRewriteScript):
    def __init__(self):
        BaseRewriteScript.__init__(self)

    def setUp(self):
        BaseRewriteScript.setUp(self)
        self.env = {'PYTHONPATH': os.path.abspath('lib'),
                    'VCAP_APP_PORT': '80'}
        self.env.update(os.environ)
        shutil.copytree('defaults/config/nginx/1.5.x', self.cfg_dir)

    def tearDown(self):
        BaseRewriteScript.tearDown(self)

    @with_setup(setup=setUp, teardown=tearDown)
    def test_rewrite(self):
        res = self.run.check_output("%s %s" % (self.rewrite, self.cfg_dir),
                                    env=self.env,
                                    cwd=os.path.join(self.run_dir, 'bin'),
                                    stderr=subprocess.STDOUT,
                                    shell=True)
        eq_('', res)
        for root, dirs, files in os.walk(self.cfg_dir):
            for f in files:
                with open(os.path.join(root, f)) as fin:
                    eq_(-1, fin.read().find('@{'), f)

@@ -1973,33 +1973,16 @@
 (self):%0A
-        try:%0A    
         
@@ -2030,35 +2030,37 @@
 p.ini')%0A        
-   
+res =
  self.run.check_
@@ -2124,36 +2124,32 @@
                 
-    
 env=self.env,%0A  
@@ -2138,36 +2138,32 @@
   env=self.env,%0A
-    
                 
@@ -2237,36 +2237,32 @@
                 
-    
 stderr=subproces
@@ -2293,36 +2293,32 @@
                 
-    
 shell=True)%0A    
@@ -2325,142 +2325,162 @@
     
-    assert False%0A        except self.run.CalledProcessError, e:%0A            eq_('Path %5B%25s%5D is not a directory.%5Cn' %25
+eq_('', res)%0A        with open(os.path.join(self.cfg_dir, 'php.ini')) as fin:%0A            cfgFile = fin.read()%0A            eq_(-1,
  cfg
-_file, e.output
+File.find('@%7BHOME%7D')
 )%0A  
@@ -2493,33 +2493,45 @@
     eq_(
-255, e.returncode
+-1, cfgFile.find('@%7BTMPDIR%7D')
 )%0A%0A    @

Test was checking that rewrite failed when run with the path to a file. This is now OK. Test was modified to confirm that the file is processed.