# -*- encoding: UTF8 -*-
# Test harness for DefaultChangeDesc.py

from __future__ import print_function

import sys
import unittest
import os

from p4testutils import TestCase, P4Server

parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent_dir)
from DefaultChangeDesc import DefaultChangeDesc

os.environ["LOGS"] = "."
LOGGER_NAME = "DefaultChangeDesc"
LOG_FILE = "log-DefaultChangeDesc.log"


class TestDefaultChangeDesc(TestCase):
    def __init__(self, methodName='runTest'):
        super(TestDefaultChangeDesc, self).__init__(LOGGER_NAME, LOG_FILE, methodName=methodName)

    def setUp(self):
        pass

    def tearDown(self):
        pass


    def setupServer(self):
        self.server = P4Server()
        trig_path = os.path.join(parent_dir, "DefaultChangeDesc.py")
        p4 = self.server.p4
        p4.logger = self.logger
        # This works if no spaces in server root pathname!
        port = p4.port.replace('"', '')
        self.logger.debug("port: |%s|" % port)
        triggers = p4.fetch_triggers()
        triggers['Triggers'] = ['default-change-desc form-out change "python {} -p %quote%{}%quote% '
                                '-u {} %user% %formfile%"'.format(trig_path, port, p4.user)]
        self.logger.debug(triggers)
        p4.save_triggers(triggers)
        # Reconnect to pick up changes
        p4.disconnect()
        p4.connect()
        return p4

    def testChangeDesc(self):
        """jobs are renamed for p4dtg"""
        p4 = self.setupServer()

        chg = p4.fetch_change()
        self.assertRegex(chg["Description"], "OS-NNNN.*")
        chg["Description"] = "My change description"
        p4.save_change(chg)

        # Make sure that the trigger doesn't fire again - so what is put in above survives
        chg = p4.fetch_change("1")
        self.assertRegex(chg["Description"], "My change description")



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