import os
import unittest
import subprocess
import mox
from cam import openssl_wrap


class PopenStub(object):

    def __init__(self, stdout='', returncode=0):
        self.stdout = stdout
        self.returncode = returncode

    def communicate(self):
        return self.stdout, 'unused'


class OpensslWrapTest(unittest.TestCase):

    def setUp(self):
        self.mox = mox.Mox()

    def tearDown(self):
        self.mox.VerifyAll()
        self.mox.UnsetStubs()

    def test_run(self):
        self.mox.StubOutWithMock(subprocess, 'Popen', use_mock_anything=True)
        pipe_stub = PopenStub(stdout='output')
        subprocess.Popen(['openssl', 'test'], stdout=subprocess.PIPE, env=mox.IsA(dict)
                         ).AndReturn(pipe_stub)
        self.mox.ReplayAll()
        result = openssl_wrap.run('test')
        self.assertEquals('output', result)

    def test_run_fails(self):
        self.mox.StubOutWithMock(subprocess, 'Popen', use_mock_anything=True)
        pipe_stub = PopenStub(returncode=1)
        subprocess.Popen(['openssl', 'test'], stdout=subprocess.PIPE, env=mox.IsA(dict)
                         ).AndReturn(pipe_stub)
        self.mox.ReplayAll()
        def r():
            result = openssl_wrap.run('test')
        self.assertRaises(openssl_wrap.CommandError, r)

    def test_run_with_config(self):
        self.mox.StubOutWithMock(subprocess, 'Popen', use_mock_anything=True)
        pipe_stub = PopenStub(stdout='output')
        subprocess.Popen(['openssl', 'test', '-config', 'conf', '-batch', 'arg'],
                         stdout=subprocess.PIPE, env=mox.IsA(dict)).AndReturn(pipe_stub)
        self.mox.ReplayAll()
        result = openssl_wrap.run_with_config('.', 'conf', 'test', 'arg')


if __name__ == '__main__':
    unittest.main()
