#!/usr/bin/python3

import apt_pkg
import dbus
import os
import sys
import tempfile
import unittest
sys.path.insert(0, "../")

from UbuntuSystemService.backend import ServiceBackend

class TestProxy(unittest.TestCase):

    def test_write(self):
        # regression test for #877254
        canary = 'Acquire::http::proxy::server2.local "DIRECT";\n'
        # setup tmpdir
        tmpdir = tempfile.mkdtemp()
        os.makedirs(os.path.join(tmpdir, "apt.conf.d"))
        f=open(os.path.join(tmpdir, "apt.conf"), "w")
        f.write(canary)
        f.close()
        # create backend
        bus = dbus.SessionBus()
        apt_pkg.config.set("Dir::etc", tmpdir)
        backend = ServiceBackend(bus=bus)
        # write and verify apt proxy settings
        backend._write_apt_proxy("http", "http://localhost:3128")
        self.assertEqual(open(os.path.join(tmpdir, "apt.conf")).read(),
                         canary+
                         'Acquire::http::proxy "http://localhost:3128";\n')
        # clear it again
        backend._clear_apt_proxy("http")
        self.assertEqual(open(os.path.join(tmpdir, "apt.conf")).read(), 
                         canary)
        # write and verify apt proxy settings
        backend._write_apt_proxy("http", "http://localhost:3128")
        self.assertEqual(open(os.path.join(tmpdir, "apt.conf")).read(),
                         canary+
                         'Acquire::http::proxy "http://localhost:3128";\n')



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