# -*- encoding: UTF8 -*-
# Test harness for ValidateContentFormat.py
from __future__ import print_function
import sys
import unittest
import os
import re
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import testp4
import P4
import logging
from ValidateContentFormat import ValidateContentFormat
os.environ["LOGS"] = "."
LOGGER_NAME = "TestValidateContentFormat"
LOG_FILE = "log-ValidateContentFormat.log"
python3 = sys.version_info[0] >= 3
def ensureDirectory(directory):
if not os.path.isdir(directory):
os.makedirs(directory)
def localDirectory(root, *dirs):
"Create and ensure it exists"
dir_path = os.path.join(root, *dirs)
ensureDirectory(dir_path)
return dir_path
def create_file(file_name, contents):
"Create file with specified contents"
ensureDirectory(os.path.dirname(file_name))
if python3:
contents = bytes(contents.encode())
with open(file_name, 'wb') as f:
f.write(contents)
def append_to_file(file_name, contents):
"Append contents to file"
if python3:
contents = bytes(contents.encode())
with open(file_name, 'ab+') as f:
f.write(contents)
class TestValidateContentFormat(unittest.TestCase):
def __init__(self, methodName='runTest'):
super(TestValidateContentFormat, self).__init__(methodName=methodName)
self.logger = logging.getLogger(LOGGER_NAME)
self.logger.setLevel(logging.DEBUG)
logformat = '%(levelname)s [%(asctime)s] [%(filename)s : %(lineno)d] - %(message)s'
logging.basicConfig(format=logformat, filename=LOG_FILE, level=logging.DEBUG)
def assertRegex(self, *args, **kwargs):
if python3:
return super(TestValidateContentFormat, self).assertRegex(*args, **kwargs)
else:
return super(TestValidateContentFormat, self).assertRegexpMatches(*args, **kwargs)
def setUp(self):
pass
def tearDown(self):
pass
def create_test_file(self, contents):
fname = "~temp_file"
with open(fname, "w") as f:
f.write(contents)
return fname
def testValidateYaml(self):
"""Some basic yaml tests"""
trig = ValidateContentFormat("1")
tfile = self.create_test_file("""
api: "api/v6"
user: swarmtest
ticket: A123453
""")
result = trig.yaml_load_errors(tfile)
self.assertEqual("", result)
tfile = self.create_test_file("""
review_description:
- "Please review me!"
- "Don't forget to check YYYY"
projects:
- name: ProjectA
create_review: y
require_job: y
update_review: n
depot_paths:
- //depot/inside/...
- "-//depot/inside/*_file1"
default_reviewers:
- user1
- user2
""")
result = trig.yaml_load_errors(tfile)
self.assertEqual("", result)
tfile = self.create_test_file("""
review_description:
- "Please review me!
- "Don't forget to check YYYY"
""")
result = trig.yaml_load_errors(tfile)
self.assertNotEqual("", result)
def testValidateContentFormat(self):
"""trigger fires and sends expected info to Swarm"""
self.server = testp4.P4Server()
trig_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ValidateContentFormat.py")
config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_config.yaml")
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'] = ['validate-content change-content //... " python ' + trig_path +
" -p %quote%" + port + "%quote% -u " + p4.user +
' --yaml %change% "']
self.logger.debug(triggers)
p4.save_triggers(triggers)
# Reconnect to pick up changes
p4.disconnect()
p4.connect()
inside = localDirectory(self.server.client_root, "inside")
inside_file1 = os.path.join(inside, "inside_file1.yaml")
create_file(inside_file1, """
api: "api/v6"
user: swarmtest
ticket: A123453
""")
p4.run('add', inside_file1)
result = p4.run('submit', '-d', 'inside_file1 added')
self.assertEquals("1", result[-1]['submittedChange'])
# Bad yaml format is found
p4.run('edit', inside_file1)
create_file(inside_file1, """
review_description:
- "Please review me!
- "Don't forget to check YYYY"
""")
try:
result = p4.run('submit', '-d', 'inside_file1 edited')
self.assertTrue(False, "Expected exception not found")
except P4.P4Exception as e:
self.assertRegex(str(e), r"Invalid format for")
# Bad file without appropriate extension is OK because skipped
inside_file2 = os.path.join(inside, "inside_file2")
create_file(inside_file2, """
review_description:
- "Please review me!
- "Don't forget to check YYYY"
""")
p4.run('add', inside_file2)
result = p4.run('submit', '-d', 'inside_file2 added')
self.assertEquals("3", result[-1]['submittedChange'])
if __name__ == '__main__':
unittest.main()