Conghao97's picture tcftrees's picture
ProgramGen release
d086025
Raw History Blame Contribute Delete
41.5 kB
diff --git a/PyProjManCore/__init__.py b/PyProjManCore/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/PyProjManCore/helpers.py b/PyProjManCore/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..765c3b2f99d194b30d039fc6ff8f75987c0761fa --- /dev/null +++ b/PyProjManCore/helpers.py @@ -0,0 +1,26 @@ +def assign_type(source, type1, type2): + """Check class of source, if matches passed types, then assign destination the value of source""" + if isinstance(source, type1) \ + or isinstance(source, type2): + return source + return None + + +def calculate_dates_and_durations(start=None, end=None, duration=None): + """ + Calculates Start Date, End Date or Duration from the other two known's + Rule is: + If all Given Data is not none, then calculate end date from start and duration, + if two are known, then calculate the third from them + if less than two are known, then do nothing + """ + if start is not None \ + and duration is not None: + end = start + duration + if start is not None \ + and end is not None: + duration = end - start + if end is not None \ + and duration is not None: + start = end - duration + return start, end, duration diff --git a/PyProjManCore/proj_man.py b/PyProjManCore/proj_man.py new file mode 100644 index 0000000000000000000000000000000000000000..c01f8ccce890536e7aa48a1bed515ed3d59e7642 --- /dev/null +++ b/PyProjManCore/proj_man.py @@ -0,0 +1,35 @@ +from PyProjManCore.task import Task + + +class ProjMan: + """Project Manager Object, uses Tasks and Time Elements""" + def __init__(self, root: Task=None, name=None): + """ + Initialize a project, with minimum one task as root task + :type root: object + """ + self._root = root + self._name = name + + @property + def root(self): + """Root Task of this project""" + return self._root + + @property + def name(self): + """Name of a project""" + return self._name + + def add_child(self, child): + self._root.append_dependant(child) + + def add_parent(self, parent): + self._root.append_prerequisite(parent) + self._root = parent + + def list_tasks(self): + """List of All Tasks defined in a project starting from root to last task""" + print("List Tasks ") + result = self._root.list_children([self.root]) + return result diff --git a/PyProjManCore/proj_stats.py b/PyProjManCore/proj_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..7305d371daa3ec5eff358284391d9be4363ef4a6 --- /dev/null +++ b/PyProjManCore/proj_stats.py @@ -0,0 +1,68 @@ +from PyProjManCore.task import Task + + +class ProjStats: + """Project Statistics Object, used for reporting purposes""" + def __init__(self, name=None): + """empty object""" + self._project_name = name + self._first_task = None + self._last_task = None + self._task_count = 0 + self._project_duration = None + self._list_tasks = [] + + @property + def name(self): + return self._project_name + + @name.setter + def name(self, value): + self._project_name = value + + @property + def first(self): + return self._first_task + + @first.setter + def first(self, value: Task): + self._first_task = value + + @property + def last(self): + return self._last_task + + @last.setter + def last(self, value: Task): + self._last_task = value + + @property + def count(self): + return self._task_count + + @count.setter + def count(self, value): + self._task_count = value + + @property + def duration(self): + return self._project_duration + + @duration.setter + def duration(self, value): + self._project_duration = value + + @property + def tasks(self): + return self._list_tasks + + @tasks.setter + def tasks(self, value): + self._list_tasks = value + + def append_task(self, value): + self._list_tasks.append(value) + + def remove_task(self, value): + while value in self._list_tasks: + self._list_tasks.remove(value) diff --git a/PyProjManCore/sand_box.py b/PyProjManCore/sand_box.py new file mode 100644 index 0000000000000000000000000000000000000000..c555b8a1c587b2527e560b9b06f96e825df36c03 --- /dev/null +++ b/PyProjManCore/sand_box.py @@ -0,0 +1,39 @@ +# Scrap Paper File to try different Things + +# Test How to build a task variable +from PyProjManCore.task import Task + +root = Task("Root Task") + +# Define 3 Layers of tasks +# Layer 1 +l1a = Task("Prerequisite a, Layer 1") +l1b = Task("Prerequisite b, Layer 1") +root.append_prerequisite(l1a) +root.append_prerequisite(l1a) +root.append_prerequisite(l1b) +# Layer 2 +l2a = Task("Prerequisite a, Layer 2") +l2b = Task("Prerequisite b, Layer 2") +l1a.append_prerequisite(l2a) +l1a.append_prerequisite(l2b) +l2c = Task("Prerequisite c, Layer 2") +l2d = Task("Prerequisite d, Layer 2") +l1b.append_prerequisite(l2c) +l1b.append_prerequisite(l2d) +# Layer 3 +l3a = Task("Prerequisite a, Layer 3") +l2a.append_prerequisite(l3a) +l2b.append_prerequisite(l3a) +l3b = Task("Prerequisite b, Layer 3") +l2a.append_prerequisite(l3b) +# Assign each layer the layer over it as a prerequisite + +c_up = root.crawl_up() + +root.report() +l1a.report() +print(len(c_up)) +print("All Prerequisites") +for parent in c_up: + print(parent.id) diff --git a/PyProjManCore/task.py b/PyProjManCore/task.py new file mode 100644 index 0000000000000000000000000000000000000000..d0a27a5fd2527ed756af5561c351a9a0b717c9dd --- /dev/null +++ b/PyProjManCore/task.py @@ -0,0 +1,169 @@ +import itertools +import uuid +# Building Block +import PyProjManCore.helpers +from PyProjManCore.time_element import TimeElement + + +class Task: + """Building block of a project plan""" + type = "Task Element" + task_id = itertools.count() + + def __init__(self, name=None): + # Basic Information + self._id = uuid.uuid4() + self._short_id = next(self.task_id) + self._name = name + # Timing Metrics + self._planned = None + self._actual = None + # Optional Time Metrics + self._worst = None + self._best = None + # Percentage Completed + self._pct_complete = 0.0 + # Lists used for the task tree structure + self._dependants = [] + self._prerequisites = [] + + # Task methods + def list_children(self, children): + """Lists Tasks defined under a task""" + if len(self._dependants) > 0: + children.extend(self._dependants) + for child in self._dependants: + if len(child.list_children(children)) > 0: + children.extend(child.list_children(children)) + return list(set(children)) + + def report(self): + """Report Current Task Statistics""" + # List Task ID, Name + print("{} : {}".format(self.id, self.name)) + # List Task Status + print("{} % Completed ".format(self.completed*100)) + # List Planned/Actual Time Metrics + print(""" +Planned: + Start : {} + End : {} + Duration: {} +Actual: + Start : {} + End : {} + Duration: {} + """.format(self.planned.start, self.planned.end, self.planned.duration, + self.actual.start, self.actual.end, self.actual.duration)) + + # List Prerequisite Tasks + print("Prerequisite Tasks") + for prereq in self.prerequisites: + print("{} - {}".format(prereq.id, prereq.name)) + # List Dependant Tasks + print("Dependant Tasks") + for dependant in self.dependants: + print("{} - {}".format(dependant.id, dependant.name)) + + @property + def id(self): + """Unique Task ID, readonly value + :rtype: UUID + """ + return self._id + + # Name + @property + def name(self): + """Task Name""" + return self._name + + @name.setter + def name(self, value): + self._name = value + + # Predecessors + @property + def prerequisites(self): + """Task predecessors ... aka predecessors""" + return self._prerequisites + + @prerequisites.setter + def prerequisites(self, value): + """One transaction setting""" + self._prerequisites = value + + def append_prerequisite(self, value): + """Append to prerequisites array""" + if value not in self._prerequisites: + + self._prerequisites.append(value) + value.append_dependant(self) + return self._prerequisites + + # Dependants + @property + def dependants(self): + """Tasks depending on current task... aka children""" + return self._dependants + + @dependants.setter + def dependants(self, value): + self._dependants = value + + def append_dependant(self, value): + if value not in self._dependants: + self._dependants.append(value) + value.append_prerequisite(self) + return self._dependants + + # Planned + @property + def planned(self): + """Task planned timings""" + return self._planned + + @planned.setter + def planned(self, value): + self._planned = PyProjManCore.helpers.assign_type(value, TimeElement, TimeElement) + + @property + def actual(self): + """Task actual start date/time""" + return self._actual + + @actual.setter + def actual(self, value): + self._actual = PyProjManCore.helpers.assign_type(value, TimeElement, TimeElement) + + @property + def best_scenario(self): + """Best Scenario Case Timing""" + return self._best + + @best_scenario.setter + def best_scenario(self, value): + self._best = PyProjManCore.helpers.assign_type(value, TimeElement, TimeElement) + + @property + def worst_scenario(self): + """Worst Scenario Case Timing""" + return self._worst + + @worst_scenario.setter + def worst_scenario(self, value): + self._worst = PyProjManCore.helpers.assign_type(value, TimeElement, TimeElement) + + # Status + @property + def completed(self): + """Percentage Completed of this task, real number ranging from 0 to 1""" + return self._pct_complete + + @completed.setter + def completed(self, value): + self._pct_complete = value + + def crawl_up(self): + pass + diff --git a/PyProjManCore/time_element.py b/PyProjManCore/time_element.py new file mode 100644 index 0000000000000000000000000000000000000000..cedb29a0bc3adb7390f9acd4c1df214360145919 --- /dev/null +++ b/PyProjManCore/time_element.py @@ -0,0 +1,58 @@ +import datetime +from PyProjManCore.helpers import assign_type, calculate_dates_and_durations + + +class TimeElement: + """ + Time Element, is a repeated unit used in the Task Object + It can be actual time, estimated time, + best case estimated time, + worst case estimated time or anything else + This piece of code was refactored in a separate class to avoid high number of methods in Task class + """ + + def __init__(self, start=None, end=None, duration=None): + self._start = None + self._end = None + self._duration = None + self._start = assign_type(start, datetime.date, datetime.datetime) + self._end = assign_type(end, datetime.date, datetime.datetime) + self._duration = assign_type(duration, datetime.timedelta, datetime.timedelta) + self._start, self._end, self._duration = calculate_dates_and_durations(self._start, self._end, self._duration) + + def recalculate(self): + """Recalculates date/time components""" + self._start, self._end, self._duration = calculate_dates_and_durations(self._start, + self._end, + self._duration) + + @property + def start(self): + return self._start + + @start.setter + def start(self, value): + self._start = assign_type(value, datetime.datetime, datetime.date) + self.recalculate() + + @property + def end(self): + return self._end + + @end.setter + def end(self, value): + self._end = assign_type(value, datetime.datetime, datetime.date) + self.recalculate() + + @property + def duration(self): + return self._duration + + @duration.setter + def duration(self, value): + self._duration = assign_type(value, datetime.timedelta, datetime.timedelta) + self.recalculate() + + def __eq__(self, other): + if isinstance(other, TimeElement): + return self._start == other.start and self._end == other.end and self._duration == other.duration diff --git a/PyProjManUI/__init__.py b/PyProjManUI/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/PyProjManUI/parser.py b/PyProjManUI/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..b01cb3db400cba65d148ceefd4e33bf5537b34d9 --- /dev/null +++ b/PyProjManUI/parser.py @@ -0,0 +1,227 @@ +from pyparsing import ZeroOrMore, Regex +from PyProjManCore.proj_man import ProjMan +import json +import os + +# This parser object should handle the following entities +# action +# object(s) +# parameters +# each verb objects and parameters are linked to an API call defined in the api.py module + + +class OpCode: + """Used to systematically communicate with ProjMan""" + def __init__(self, verb=None, parameters=None, feedback=None, error=None): + """Made of: + a verb + list of objects + list of literals + """ + self._verb = verb + self._inp_params = parameters + self._feedback = feedback + self._error = error + self._override_feedback = False + + @property + def error(self): + return self._error + + def __str__(self): + ret = "Opcode Verb : [{}] Parameters:".format(self._verb) + for par in self._inp_params: + ret = ret + "{}, ".format(par) + ret = ret + " Feedback : {} Error : {}".format(self._feedback, self._error) + return ret + + +def tokenizer(inp: str): + """Slice input string into tokens""" + parser = ZeroOrMore(Regex(r'\[[^]]*\]') | Regex(r'"[^"]*"') | Regex(r'[^ ]+')) + tokens = [] + for token in parser.parseString(inp): + tokens.append(token.replace('"','').replace("'",'').replace('[','').replace(']','')) + return tokens + + +class PyProjManParser: + """PyProjMan parser used by the text based UI to interact with PyProjMan API""" + def __init__(self, project: ProjMan = None, config_file=None): + """This should contact API object first, but for Alpha release, it will directly contact ProjMan""" + # Load Parser Data + try: + if config_file is None: + config_file = os.path.join(os.getcwd(), 'data', 'parser.json') + with open(config_file) as parser_data_file: + parser_data = json.load(parser_data_file) + self._version = parser_data['Version'] + self._release = parser_data['Release'] + self._ignore_case = parser_data['IgnoreCase'] + raw_primitives = parser_data['Primitives'] + self._primitives = {} + for k, v in raw_primitives.items(): + self._primitives[k] = int(v, 16) # Evaluate Hex + del raw_primitives + self._verbs = parser_data['Verbs'] + self._parameters = parser_data['Parameters'] + self._decorators = parser_data['Decorators'] + raw_reply = parser_data['Reply'] + self._reply = {} + for k, v in raw_reply.items(): + self._reply[int(k)] = v + del raw_reply + raw_err_codes = parser_data['ErrorCodes'] + self._error_codes = {} + for k, v in raw_err_codes.items(): + self._error_codes[int(k)] = v + del raw_err_codes + self._help_strings = parser_data['HelpString'] + + self._valid = True + except FileNotFoundError: + print(""" +Fatal Error: +Configuration file not found +Exiting +""") + self._valid = False + + # Load initial project + if project is None: + project = ProjMan() + self._project = project + + def listen(self): + """Listens to user input""" + _active = True + op_code = OpCode() + + while _active: + inp = input("PyProjMan > ") # 1: read input from user : in a form of a string + op_code._override_feedback = False + op_code = self.parse(inp) # 2: pass input string to parse() function : get op code + op_code = self.hook(op_code) # 3: pass op code to hook() : get feedback as op code + self.feed_back(op_code) # 4: display feedback op code to user via feed_back() + if op_code._verb == self._primitives['EXIT']: + _active = False + + def parse(self, inp: str): + """parse input string to call functions + :returns op code mapped to function calls from ProjMan""" + op_code = OpCode() + # TODO: + # 1: split string into a verb and rest of string + tokens = tokenizer(inp) + # 2: lookup verb in the _verbs dictionary, and place its numeric value + if tokens[0].lower() in self._verbs: + op_code = OpCode(verb=self._primitives[self._verbs[tokens[0].lower()]]) + op_code._inp_params = [] + for token in tokens[1:]: + if token.lower() in self._parameters: + op_code._inp_params.append(self._primitives[self._parameters[token.lower()]]) + else: + op_code._inp_params.append(token) + else: + op_code = OpCode(error=903) # Invalid Verb + + # 3: slice input string into tokens; keywords and literals + # literals identified by double quotes, single quotes or square brackets surrounding them + # 4: lookup non literal tokens and replace them with values from _objects and _decoration dictionary + # 5: check for syntax maps + # if all is ok, return op code object + # otherwise, return a syntax error op code object + return op_code + + def feed_back(self, op_code: OpCode): + """Returns feedback from PyProjMan to end user + :returns a string to user interface""" + + # Reverse lookup Op Code into text using the _reply dictionary, and construct feedback + # this should return a string + if not op_code._override_feedback: + op_code._feedback = self.lookup_primative(op_code._verb) + for param in op_code._inp_params: + if isinstance(param, int): + op_code._feedback = op_code._feedback + " {}".format(self.lookup_primative(param)) + else: + op_code._feedback = op_code._feedback + " {}".format(param) + print("{} : {}".format(self._error_codes[op_code._error], op_code._feedback)) + return op_code + + def hook(self, op_code): + """what really interacts with ProjMan + :argument op_code + :returns op code """ + # TODO: + # Lookup verb in a large switch statement, and make a call based on the numeric value, + # passing objects, and literals as arguments + # collect response, and convert it into op code, and return it to caller function + # Create a Project + + if op_code._verb == self._primitives['CREATE'] and op_code._inp_params[0] == self._primitives['PROJECT']: + self._project = ProjMan(name=op_code._inp_params[1]) + op_code._error=100 + elif op_code._verb == self._primitives['EXIT']: + op_code._error=200 + elif op_code._verb == self._primitives['MANUAL']: + op_code = self.help(op_code) + else: + op_code._error=901 + return op_code + + def lookup_primative(self, primative_value): + if primative_value in self._primitives.values(): + for k,v in self._primitives.items(): + if v == primative_value: + return k + return None + + @property + def valid(self): + return self._valid + + @property + def release(self): + return self._release + + @property + def version(self): + return self._version + + def help(self, op_code): + """Provides Help on how to use the CLI""" + if len(op_code._inp_params) > 0: + inquiry = op_code._inp_params[0] + if isinstance(inquiry, int): + if inquiry in self._primitives.values(): + inquiry = self.lookup_primative(inquiry) + + # Lookup keywords + # In verbs + if inquiry in self._verbs.keys(): + inquiry = self._verbs[inquiry] + + # In Parameters + if inquiry in self._parameters.keys(): + inquiry = self._parameters[inquiry] + + if inquiry in self._primitives.keys(): + op_code._feedback = "{} ({}) \n{}".format(op_code._inp_params[0],inquiry, self.help_primitive(inquiry)) + else: + op_code._feedback = 'Unable to find keyword {}'.format(op_code._inp_params[0]) + op_code._error = 902 + op_code._override_feedback = True + return op_code + else: + op_code._feedback = "PyProjMan version {} - {} release!".format(self.version, self.release) + op_code._feedback = op_code._feedback + "\nList of keywords :" + for verb_key, primitive_key in self._verbs.items(): + op_code._feedback = op_code._feedback + "\n {} \t- \t{}".format(verb_key,self.help_primitive(primitive_key)) + op_code._error = 100 + op_code._override_feedback = True + return op_code + + def help_primitive(self, prim): + """Givin a primitive key, get help text""" + return self._help_strings[prim] \ No newline at end of file diff --git a/PyProjManUI/ui_helper.py b/PyProjManUI/ui_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/UnitTesting/__init__.py b/UnitTesting/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/UnitTesting/test.json b/UnitTesting/test.json new file mode 100644 index 0000000000000000000000000000000000000000..4ed0d64a1bab1d619f972e3b281885fda7abe3f2 --- /dev/null +++ b/UnitTesting/test.json @@ -0,0 +1,108 @@ +{ + "FileDescription": "PyProjMan Keyword Dictionary", + "Version":"0.0.2", + "Release":"alpha", + "IgnoreCase":true, + "Primitives" : { + "ADD": "0x100", + "ADVICE": "0x110", + "ASSIGN": "0x120", + "CREATE": "0x130", + "DELETE": "0x140", + "DEMOTE": "0x150", + "ESTIMATE": "0x160", + "LINK": "0x170", + "LIST": "0x180", + "PROMOTE": "0x190", + "REPORT": "0x1a0", + "DISPLAY": "0x1b0", + "SUMMARY": "0x1c0", + "EXIT": "0x200", + "MANUAL": "0x210", + "LOAD": "0x220", + "SAVE": "0x230", + "SYNCHRONIZE": "0x240", + "ACTUAL": "0x300", + "BEST": "0x310", + "DATE": "0x320", + "MEAN": "0x330", + "FILE": "0x340", + "PROJECT": "0x350", + "STATUS": "0x360", + "TASK": "0x370", + "WORST": "0x380", + "ON": "0x400", + "TO": "0x410", + "FROM": "0x420", + "SUCCESS": "0x800", + "ERROR": "0x810" + }, + "Verbs": { + "add": "ADD", + "adv": "ADVICE", + "advice": "ADVICE", + "assign": "ASSIGN", + "create": "CREATE", + "del": "DELETE", + "delete": "DELETE", + "dem": "DEMOTE", + "demote": "DEMOTE", + "disp": "DISPLAY", + "display": "DISPLAY", + "est": "ESTIMATE", + "estimate": "ESTIMATE", + "exit": "EXIT", + "help": "MANUAL", + "link": "LINK", + "list": "LIST", + "load": "LOAD", + "man": "MANUAL", + "manual": "MANUAL", + "open": "LOAD", + "promote": "PROMOTE", + "quit": "EXIT", + "remove": "DELETE", + "report": "REPORT", + "save": "SAVE", + "show": "DISPLAY", + "summary": "SUMMARY", + "sync": "SYNCHRONIZE", + "synchronize": "SYNCHRONIZE" + }, + "Parameters":{ + "best": "BEST", + "act": "ACTUAL", + "actual": "ACTUAL", + "dat": "DATE", + "date": "DATE", + "est": "MEAN", + "estimated": "MEAN", + "file": "FILE", + "planned": "MEAN", + "proj": "PROJECT", + "project": "PROJECT", + "stat": "STATUS", + "status": "STATUS", + "task": "TASK", + "worst": "WORST" + }, + "Decorators" : { + "on": "ON", + "to": "TO", + "from": "FROM" + }, + "Reply": { + "100": "Success", + "200": "Bye", + "999": "" + }, + "ErrorCodes": { + "100": "Success", + "200": "Exiting!", + "300": "Pending", + "901": "Syntax Error", + "902": "Not Found", + "903": "Invalid Verb", + "999": "Failure" + } +} \ No newline at end of file diff --git a/UnitTesting/test_helper.py b/UnitTesting/test_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..613baa67f287205f38d31e2e794630befcb33e32 --- /dev/null +++ b/UnitTesting/test_helper.py @@ -0,0 +1,2 @@ +def prepare_type1(): + return None diff --git a/UnitTesting/test_parser.py b/UnitTesting/test_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..4dc9927c75dd0847aca99a02218bf427b015020a --- /dev/null +++ b/UnitTesting/test_parser.py @@ -0,0 +1,115 @@ +from unittest import TestCase + +import os + +from PyProjManCore.proj_man import ProjMan +from PyProjManUI.parser import PyProjManParser, OpCode + + +def helper_load_cfg_file(): + print(os.path.join('PyProjMan','UnitTesting', 'test.json')) + #p = PyProjManParser(config_file=os.path.join(os.getcwd(), 'test.json')) + p = PyProjManParser(config_file = os.path.join(os.getcwd(),'PyProjManUI','data', 'parser.json')) + return p + + +class TestPyProjManParser(TestCase): + """Test PyProjManParser""" + def test_init(self): + """Can we define a PyProjManParserobject?""" + p = helper_load_cfg_file() + self.assertIsInstance(p, PyProjManParser) + + def test_load_parser_data_version(self): + """Can read Version from Config file""" + p = helper_load_cfg_file() + target = '0.0.3' + self.assertEqual(target,p._version) + + def test_load_parser_data_release(self): + """Can read Release from Config file""" + p = helper_load_cfg_file() + target = 'alpha' + self.assertEqual(target,p._release) + + def test_load_parser_data_ignore_case(self): + """Can read Ignore Case from Config file""" + p = helper_load_cfg_file() + target = True + self.assertEqual(target, p._ignore_case) + + def test_load_parser_data_primitives(self): + """Can read Primitives from Config file""" + p = helper_load_cfg_file() + target = {"ADD": 256} + key = 'ADD' + value = 256 + target = {key: value} + self.assertEqual(target[key], p._primitives[key]) + + def test_load_parser_data_verbs(self): + """Can read Verbs from Config file""" + p = helper_load_cfg_file() + target = {"add": "ADD"} + key = 'add' + value = 'ADD' + target = {key: value} + self.assertEqual(target[key], p._verbs[key]) + + def test_load_parser_data_parameters(self): + """Can read Parameters from Config file""" + p = helper_load_cfg_file() + key = 'best' + value = 'BEST' + target = {key: value} + self.assertEqual(target[key], p._parameters[key]) + + + def test_load_parser_data_decorators(self): + """Can read Decorators from Config file""" + p = helper_load_cfg_file() + key = 'on' + value = 'ON' + target = {key: value} + self.assertEqual(target[key], p._decorators[key]) + + def test_load_parser_data_reply(self): + """Can read Reply from Config file""" + p = helper_load_cfg_file() + key = 200 + value = 'Bye' + target = {key: value} + print(p._reply[key]) + self.assertEqual(target[key], p._reply[key]) + + def test_load_parser_data_err_codes(self): + """Can read Error Codes from Config file""" + p = helper_load_cfg_file() + key = 100 + value = 'Success' + target = {key: value} + self.assertEqual(target[key], p._error_codes[key]) + + def test_parse_create_project_verb(self): + """Parse input string of create project (Verb)""" + p = helper_load_cfg_file() + op_code = p.parse("CREATE PROJECT [Test Project]") + target = p._primitives['CREATE'] + self.assertEqual(op_code._verb, target) + + def test_parse_create_project_parameters(self): + """Parse input string of create project (Parameters)""" + p = helper_load_cfg_file() + op_code = p.parse("CREATE PROJECT [Test Project]") + target = p._primitives['PROJECT'] + self.assertIn(target,op_code._inp_params) + + def test_parse_create_project_realization(self): + """Parse input string of create project (Creates the project)""" + p = helper_load_cfg_file() + project_name = "Test Project" + op_code = p.parse("CREATE PROJECT [{}]".format(project_name)) + print(op_code) + op_code = p.hook(op_code) + print(op_code) + self.assertEqual(p._project.name, project_name) \ No newline at end of file diff --git a/UnitTesting/test_proj_man.py b/UnitTesting/test_proj_man.py new file mode 100644 index 0000000000000000000000000000000000000000..b8f319c78671013c4955099be22fe663fba428ee --- /dev/null +++ b/UnitTesting/test_proj_man.py @@ -0,0 +1,97 @@ +from unittest import TestCase +from PyProjManCore.proj_man import ProjMan +from PyProjManCore.task import Task + + +class TestProjMan(TestCase): + def test_init(self): + """Check Type of ProjMan""" + pm = ProjMan() + self.assertIsInstance(pm, ProjMan) + + def test_root(self): + """Can create a new project with a root Task""" + root = Task("Root Task") + pm = ProjMan(root) + self.assertEqual(root, pm.root) + + def test_name(self): + """Can we define a name in the constructor?""" + project_name = "Some Project Name" + pm = ProjMan(None, project_name) + self.assertEqual(project_name, pm.name) + + def test_add_child(self): + """PM Can add a child""" + root = Task("Root Task") + pm = ProjMan(root) + child = Task("Child Task") + pm.add_child(child) + self.assertIn(child, root.dependants) + + def test_add_child2(self): + """PM Adding a child implies root is a parent for the child""" + root = Task("Root Task") + pm = ProjMan(root) + child = Task("Child Task") + pm.add_child(child) + self.assertIn(root, child.prerequisites) + + def test_add_parent(self): + """Can Add Parent to Root Task""" + root = Task("Root Task") + pm = ProjMan(root) + parent = Task("Parent Task") + pm.add_parent(parent) + self.assertIn(parent, root.prerequisites) + + def test_add_parent_rebase1(self): + """Adding Parent to root Task, Rebase Root to Parent""" + root = Task("Root Task") + pm = ProjMan(root) + parent = Task("Parent Task") + pm.add_parent(parent) + self.assertEqual(parent, pm.root) + + def test_add_parent_rebase2(self): + """Adding Parent to root Task, Makes former root a child to parent""" + root = Task("Root Task") + pm = ProjMan(root) + parent = Task("Parent Task") + pm.add_parent(parent) + self.assertIn(root, pm.root.dependants) + + def test_list_tasks(self): + """Listing all tasks in a project""" + # Create Root + root = Task("Root Task") + # Create Project + pm = ProjMan(root) + # Append Children + child1 = Task("Child Task 1") + pm.add_child(child1) + + child2 = Task("Child Task 2") + pm.add_child(child2) + + task_list = pm.list_tasks() + self.assertTrue( + root in task_list and + child1 in task_list and + child2 in task_list) + + def test_list_tasks_duplicates(self): + """Listing all tasks in a project, no duplicates""" + # Create Root + root = Task("Root Task") + # Create Project + pm = ProjMan(root) + # Append Children + child1 = Task("Child Task 1") + pm.add_child(child1) + + child2 = Task("Child Task 2") + pm.add_child(child2) + + task_list = pm.list_tasks() + self.assertEqual(3, len(task_list)) diff --git a/UnitTesting/test_proj_stats.py b/UnitTesting/test_proj_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..263209e58c00284fcb4c2fb46e7a05d3a6eaff02 --- /dev/null +++ b/UnitTesting/test_proj_stats.py @@ -0,0 +1,68 @@ +from datetime import timedelta +from unittest import TestCase + +from PyProjManCore.proj_stats import ProjStats +from PyProjManCore.task import Task + + +class TestProjStats(TestCase): + def test_init(self): + stat = ProjStats() + self.assertIsInstance(stat, ProjStats) + + def test_name_constructor(self): + name = "Project Name" + stat = ProjStats(name) + self.assertEqual(name, stat.name) + + def test_name_attribute(self): + name = "Project Name" + stat = ProjStats() + stat.name = name + self.assertEqual(name, stat.name) + + def test_first(self): + stat = ProjStats() + first = Task("First") + stat.first = first + self.assertEqual(first, stat.first) + + def test_last(self): + stat = ProjStats() + last = Task("Last") + stat.first = last + self.assertEqual(last, stat.first) + + def test_count(self): + stat = ProjStats() + count = 5 + stat.count = count + self.assertEqual(count, stat.count) + + def test_duration(self): + stat = ProjStats() + duration = timedelta(days=5, hours=10, minutes=3) + stat.duration = duration + self.assertEqual(duration, stat.duration) + + def test_tasks_list(self): + stat = ProjStats() + tasks = ["Task 1", "Task 2", "Task 3"] + stat.tasks = tasks + self.assertListEqual(tasks, stat.tasks) + + def test_append_to_tasks(self): + stat = ProjStats() + tasks = ["Task 1", "Task 2", "Task 3"] + stat.tasks = tasks + new_task = "New Task" + stat.append_task(new_task) + self.assertIn(new_task, stat.tasks) + + def test_delete_from_tasks(self): + stat = ProjStats() + tasks = ["Task 1", "Task 2", "Task 3"] + stat.tasks = tasks + removed_task = "Task 2" + stat.remove_task(removed_task) + self.assertNotIn(removed_task, stat.tasks) diff --git a/UnitTesting/test_task.py b/UnitTesting/test_task.py new file mode 100644 index 0000000000000000000000000000000000000000..233ae6fcda6462550d165df923d4b66ac6889641 --- /dev/null +++ b/UnitTesting/test_task.py @@ -0,0 +1,73 @@ +from datetime import datetime +from unittest import TestCase +from PyProjManCore.task import Task +from PyProjManCore.time_element import TimeElement + + +class TestTaskParameters(TestCase): + """Test Fields of Task Object""" + def test_id(self): + """Check if Task ID has UUID Version 4""" + t = Task() + expected = 4 + self.assertEqual(expected, t.id.version) + + def test_name(self): + """Test Task Name Property Setter and Getter""" + expected = 'Task' + t = Task(expected) + t.name = expected + self.assertEqual(t.name, expected, t.name) + + def test_planned_dates(self): + """Define planned start date""" + expected = datetime(year=2017, month=11, day=30) + planned = TimeElement() + planned.start = expected + t = Task("Sample Task") + t.planned = planned + self.assertEqual(expected, t.planned.start) + + def test_actual_dates(self): + """Define actual start date""" + expected = datetime(year=2017, month=11, day=30) + actual = TimeElement() + actual.start = expected + t = Task("Sample Task") + t.actual = actual + self.assertEqual(expected, t.actual.start) + + def test_prerequisites(self): + """ + Create a list of tasks + Create a single task + Assign list of tasks to the single task + """ + target = Task() + prereqs = [] + for i in range(10): + p = Task("Super-task {}".format(i)) + prereqs.append(p) + target.prerequisites = prereqs + self.assertEqual(prereqs, target.prerequisites) + + def test_dependants(self): + """ + Create a task + Create a set of tasks + set set of tasks as dependants of the first task + """ + target = Task() + dependants = [] + for i in range(10): + d = Task("Sub-task {}".format(i)) + dependants.append(d) + target.dependants = dependants + self.assertEqual(dependants, target.dependants) + + def test_completed(self): + """Test Task completion percentage""" + t = Task() + expected = 0.5 + t.completed = expected + self.assertEqual(expected, t.completed) diff --git a/UnitTesting/test_task_exceptions.py b/UnitTesting/test_task_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..8aeb3f0e6eaf0b794445c49f437f4d93015497cb --- /dev/null +++ b/UnitTesting/test_task_exceptions.py @@ -0,0 +1,29 @@ +from unittest import TestCase + +from PyProjManCore.task import Task + + +class TestTaskOperationsExceptions(TestCase): + """Test Exceptions for Task operations""" + def test_append_duplicate_prereq(self): + """Test appending duplicate prerequisites to a task, it should be unique""" + root = Task("Root Task") + parent = Task("Parent Task") + root.append_prerequisite(parent) + root.append_prerequisite(parent) + self.assertNotEqual(2, len(root.prerequisites)) + + def test_cyclic_dependency(self): + """ + Test case of a cyclic dependency, i.e. a Task depends on itself, + or a task has both prerequisite and child the same + """ + self.fail("Not implemented ") + + def test_append_duplicate_dep(self): + """Test appending duplicate dependants to a task, it should be unique""" + root = Task("Root Task") + child = Task("Child Task") + root.append_dependant(child) + root.append_dependant(child) + self.assertNotEqual(2, len(root.dependants)) diff --git a/UnitTesting/test_task_happy.py b/UnitTesting/test_task_happy.py new file mode 100644 index 0000000000000000000000000000000000000000..71ba8a949e314deb93db07af10f0a6da31ab0568 --- /dev/null +++ b/UnitTesting/test_task_happy.py @@ -0,0 +1,27 @@ +from unittest import TestCase + +from PyProjManCore.task import Task + + +class TestTaskOperationsHappyPath(TestCase): + """Test Basic Operations of a task, in the happy path""" + def test_append_prereq(self): + """ + Create a Task + Create another task and append it to prerequisites of first task + """ + target = Task() + prereq = Task() + target.prerequisites.append(prereq) + self.assertIn(prereq, target.prerequisites) + + def test_append_dependants(self): + """ + Create a Task + Create a second task + Append second task to first task's list of dependants + """ + target = Task() + dep = Task() + target.append_dependant(dep) + self.assertIn(dep, target.dependants) diff --git a/py_proj_man.py b/py_proj_man.py new file mode 100644 index 0000000000000000000000000000000000000000..3dfbc82b64f5b44185f00015bfbcd403427cf4c4 --- /dev/null +++ b/py_proj_man.py @@ -0,0 +1,21 @@ +# Entry point to the application +import os + +from PyProjManUI.parser import PyProjManParser + + +def main(args=None): + """PyProjMan, a commandline project management tool, with brains!""" + print("\033[1mWelcome to PyProjMan") + p = PyProjManParser(config_file = os.path.join(os.getcwd(),'PyProjManUI','data', 'parser.json')) + if p.valid: + print("""\033[0mRelease : {} - \033[1m {}\033[0m +A commandline project management tool +With Brains!""".format(p.version, p.release)) + if args is not None: + p.parse(args) + p.listen() + + +if __name__ == "__main__": + main()
diff --git a/PyProjManCore/__init__.py b/PyProjManCore/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/PyProjManCore/helpers.py b/PyProjManCore/helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..765c3b2f99d194b30d039fc6ff8f75987c0761fa
--- /dev/null
+++ b/PyProjManCore/helpers.py
@@ -0,0 +1,26 @@
+def assign_type(source, type1, type2):
+ """Check class of source, if matches passed types, then assign destination the value of source"""
+ if isinstance(source, type1) \
+ or isinstance(source, type2):
+ return source
+ return None
+
+
+def calculate_dates_and_durations(start=None, end=None, duration=None):
+ """
+ Calculates Start Date, End Date or Duration from the other two known's
+ Rule is:
+ If all Given Data is not none, then calculate end date from start and duration,
+ if two are known, then calculate the third from them
+ if less than two are known, then do nothing
+ """
+ if start is not None \
+ and duration is not None:
+ end = start + duration
+ if start is not None \
+ and end is not None:
+ duration = end - start
+ if end is not None \
+ and duration is not None:
+ start = end - duration
+ return start, end, duration
diff --git a/PyProjManCore/proj_man.py b/PyProjManCore/proj_man.py
new file mode 100644
index 0000000000000000000000000000000000000000..c01f8ccce890536e7aa48a1bed515ed3d59e7642
--- /dev/null
+++ b/PyProjManCore/proj_man.py
@@ -0,0 +1,35 @@
+from PyProjManCore.task import Task
+
+
+class ProjMan:
+ """Project Manager Object, uses Tasks and Time Elements"""
+ def __init__(self, root: Task=None, name=None):
+ """
+ Initialize a project, with minimum one task as root task
+ :type root: object
+ """
+ self._root = root
+ self._name = name
+
+ @property
+ def root(self):
+ """Root Task of this project"""
+ return self._root
+
+ @property
+ def name(self):
+ """Name of a project"""
+ return self._name
+
+ def add_child(self, child):
+ self._root.append_dependant(child)
+
+ def add_parent(self, parent):
+ self._root.append_prerequisite(parent)
+ self._root = parent
+
+ def list_tasks(self):
+ """List of All Tasks defined in a project starting from root to last task"""
+ print("List Tasks ")
+ result = self._root.list_children([self.root])
+ return result
diff --git a/PyProjManCore/proj_stats.py b/PyProjManCore/proj_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..7305d371daa3ec5eff358284391d9be4363ef4a6
--- /dev/null
+++ b/PyProjManCore/proj_stats.py
@@ -0,0 +1,68 @@
+from PyProjManCore.task import Task
+
+
+class ProjStats:
+ """Project Statistics Object, used for reporting purposes"""
+ def __init__(self, name=None):
+ """empty object"""
+ self._project_name = name
+ self._first_task = None
+ self._last_task = None
+ self._task_count = 0
+ self._project_duration = None
+ self._list_tasks = []
+
+ @property
+ def name(self):
+ return self._project_name
+