Skip to content

Commit

Permalink
Fix Bug
Browse files Browse the repository at this point in the history
Fix Test
  • Loading branch information
Xenxia committed Apr 24, 2023
1 parent 71f2f6f commit 5b1326d
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:

strategy:
matrix:
python: ["3.6","3.7","3.8","3.9","3.10"]
python: ["3.7","3.8","3.9","3.10","3.11"]

runs-on: ubuntu-latest

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<div align="center">
<h1>TemplateStr-Python</h1>
<h3>TemplateStr allows to add variable, function, condition and switch in a string.</h3>
<img src="https://img.shields.io/badge/Python-v3.6%5E-green?style=flat-square&logo=python&logoColor=ffd13e&color=3470a2"/>
<img src="https://img.shields.io/badge/Python-v3.7%5E-green?style=flat-square&logo=python&logoColor=ffd13e&color=3470a2"/>
<a href="https://github.com/CheeseGrinder/TemplateStr-Python/actions/workflows/python-app.yml">
<img src="https://img.shields.io/github/workflow/status/CheeseGrinder/TemplateStr-Python/Python test?label=Test&style=flat-square"/>
<img src="https://img.shields.io/github/actions/workflow/status/CheeseGrinder/TemplateStr-Python/python_test.yml?label=Test&style=flat-square"/>
</a>
</div>

Expand Down
38 changes: 15 additions & 23 deletions templateStr/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ class TemplateStr:
def __init__(self, functionList: list = [], variableDict: dict = {}):
'''
`functionList: list`
`variableDict: dict`
'''

self.__functions = functionList
Expand Down Expand Up @@ -79,9 +77,9 @@ def __typing(self, string: str, typing: str = "False") -> list:
list_temp.append(numberfloat)
elif groupParam['variable'] != None:
if groupParam['index'] == None:
list_temp.append(self.__getVariable(groupParam['variable'])[0])
list_temp.append(self.__getVariable(groupParam['variable']))
else:
list_temp.append(self.__getVariable(groupParam['variable'], int(groupParam['index']))[0])
list_temp.append(self.__getVariable(groupParam['variable'], int(groupParam['index'])))

elif groupParam['list'] != None:
l = groupParam['list'].split(", ")
Expand All @@ -107,9 +105,7 @@ def __typing(self, string: str, typing: str = "False") -> list:

return list_temp

def __getVariable(self, key: str, index: int = None) -> Tuple[Any, bool]:

ok: bool = True
def __getVariable(self, key: str, index: int = None) -> Any:

try:
if '.' in key and not key.isspace():
Expand Down Expand Up @@ -137,7 +133,7 @@ def __getVariable(self, key: str, index: int = None) -> Tuple[Any, bool]:
# ok = False
# fvalue = f"[key '{key}' is not list]"

return (fvalue, ok)
return fvalue

def parse(self, text: str) -> str:
'''
Expand Down Expand Up @@ -178,9 +174,9 @@ def parseVariable(self, text: str) -> str:
key: str = group['variable']
var: Any
if group['index'] == None:
var = self.__getVariable(key)[0]
var = self.__getVariable(key)
else:
var = self.__getVariable(key, int(group['index']))[0]
var = self.__getVariable(key, int(group['index']))

text = text.replace(match, str(var))

Expand All @@ -203,20 +199,16 @@ def parseFunction(self, text: str) -> str:
match: str = group['match']
parameters: str = group['parameters']

value: str = "none"

v: Tuple = self.__getVariable(parameters)

if parameters != None and v[1]:
value = v[0]
def __v(p) -> str:
if p != None: return str(self.__getVariable(p))

functionName: str = group['functionName']

if functionName == 'uppercase': text = text.replace(match, value.upper())
elif functionName == 'uppercaseFirst': text = text.replace(match, value.capitalize())
elif functionName == 'lowercase': text = text.replace(match, value.lower())
# elif functionName == 'casefold': text = text.replace(match, value.casefold())
elif functionName == 'swapcase': text = text.replace(match, value.swapcase())
if functionName == 'uppercase': text = text.replace(match, __v(parameters).upper())
elif functionName == 'uppercaseFirst': text = text.replace(match, __v(parameters).capitalize())
elif functionName == 'lowercase': text = text.replace(match, __v(parameters).lower())
# elif functionName == 'casefold': text = text.replace(match, __v(parameters).casefold())
elif functionName == 'swapcase': text = text.replace(match, __v(parameters).swapcase())
elif functionName == 'time': text = text.replace(match, strftime("%H:%M:%S", localtime()))
elif functionName == 'date': text = text.replace(match, strftime("%d/%m/%Y", localtime()))
elif functionName == 'dateTime': text = text.replace(match, strftime("%d/%m/%Y,%H:%M:%S", localtime()))
Expand Down Expand Up @@ -314,7 +306,7 @@ def parseSwitch(self, text: str) -> str:

for key in dictTemp.keys():

if key == str(self.__getVariable(keyVar)[0]):
if key == str(self.__getVariable(keyVar)):
result = dictTemp[key]
break
else:
Expand All @@ -325,7 +317,7 @@ def parseSwitch(self, text: str) -> str:

for key in dictTemp.keys():

if self.__typing(key, typeVar)[0] == self.__getVariable(keyVar)[0]:
if self.__typing(key, typeVar)[0] == self.__getVariable(keyVar):
result = dictTemp[key]
break
else:
Expand Down
55 changes: 39 additions & 16 deletions test_TemplateStr.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import unittest
from templateStr import TemplateStr
from templateStr.error import NotFoundVariableError
from time import strftime, localtime

def test() -> str:
Expand Down Expand Up @@ -128,10 +129,11 @@ def testAll(self):
text_1: list = ["Name is @{uppercase; str}, ${int} years old. Dict: ${Dict.value}. my keyboard: #{lower == 'azerty'; azerty | qwerty}, ?{lower; azerty::yes, AZERTY::yo, _::ynyway}",
"Name is JAME, 32 years old. Dict: Dict in Dict. my keyboard: azerty, yes"]
text_2: list = ["test var in var ${${var}}", "test var in var 32"]
text_3: list = ["test func in func @{lowercase; @{uppercase; str}}", "test func in func none"]
text_4: list = ["test if in if #{lower == 'azerty2'; azerty | #{lower == 'querty'; yes | no}}", "test if in if no"]
text_5: list = ["test switch in switch ?{str; Jame::?{Build; Succes::#0, Failed::#1, _::#default}, Tony::#1, Marco::#2, _::#default}", "test switch in switch #0"]
text_6: list = ["test wtf ?{str; Jame::?{int/${var}; 32::#0, 36::#1, _::#default}, Tony::#1, Marco::#2, _::#default2}", "test wtf #0"]
text_3: list = ["test if in if #{lower == 'azerty2'; azerty | #{lower == 'querty'; yes | no}}", "test if in if no"]
text_4: list = ["test switch in switch ?{str; Jame::?{Build; Succes::#0, Failed::#1, _::#default}, Tony::#1, Marco::#2, _::#default}", "test switch in switch #0"]
text_5: list = ["test wtf ?{str; Jame::?{int/${var}; 32::#0, 36::#1, _::#default}, Tony::#1, Marco::#2, _::#default2}", "test wtf #0"]

text_error_1: list = ["test func in func @{lowercase; @{uppercase; str}}", "[key 'JAME' not exist]"]

parser = TemplateStr(funcs, varDict)

Expand All @@ -140,29 +142,50 @@ def testAll(self):
self.assertEqual(parser.parse(text_3[0]), text_3[1], "text_3")
self.assertEqual(parser.parse(text_4[0]), text_4[1], "text_4")
self.assertEqual(parser.parse(text_5[0]), text_5[1], "text_5")
self.assertEqual(parser.parse(text_6[0]), text_6[1], "text_6")

try:
parser.parse(text_error_1[0])
except NotFoundVariableError as err:
self.assertEqual(str(err), text_error_1[1], "text_error_1")

def testVariable(self):

text_1: list = ["var bool = ${bool} and name = ${str}", "var bool = True and name = Jame"]
text_2: list = ["${Dict.value}", "Dict in Dict"]
text_3: list = ["${MasterDict.SecondDict.value}", "Dict in Dict in Dict"]
text_4: list = ["${word}", "[key 'word' not exist]"]
text_5: list = ["${dict.dict1.value}", "[key 'dict.dict1.value' not exist]"]
text_6: list = ["${list[1]}", "42"]
text_7: list = ["${lists[1]}", "[key 'lists' not exist]"]
text_8: list = ["${list[2]}", "[index '2' out of range]"]
text_4: list = ["${list[1]}", "42"]

text_error_1: list = ["${word}", "[key 'word' not exist]"]
text_error_2: list = ["${dict.dict1.value}", "[key 'dict.dict1.value' not exist]"]
text_error_3: list = ["${lists[1]}", "[key 'lists' not exist]"]
text_error_4: list = ["${list[2]}", "[index '2' out of range]"]

parser = TemplateStr(variableDict=varDict)

self.assertEqual(parser.parseVariable(text_1[0]), text_1[1], "text_1")
self.assertEqual(parser.parseVariable(text_2[0]), text_2[1], "text_2")
self.assertEqual(parser.parseVariable(text_3[0]), text_3[1], "text_3")
self.assertEqual(parser.parseVariable(text_4[0]), text_4[1], "text_4")
self.assertEqual(parser.parseVariable(text_5[0]), text_5[1], "text_5")
self.assertEqual(parser.parseVariable(text_6[0]), text_6[1], "text_6")
self.assertEqual(parser.parseVariable(text_7[0]), text_7[1], "text_7")
self.assertEqual(parser.parseVariable(text_8[0]), text_8[1], "text_8")

try:
parser.parseVariable(text_error_1[0])
except NotFoundVariableError as err:
self.assertEqual(str(err), text_error_1[1], "text_error_1")

try:
parser.parseVariable(text_error_2[0])
except NotFoundVariableError as err:
self.assertEqual(str(err), text_error_2[1], "text_error_2")

try:
parser.parseVariable(text_error_3[0])
except NotFoundVariableError as err:
self.assertEqual(str(err), text_error_3[1], "text_error_3")

try:
parser.parseVariable(text_error_4[0])
except IndexError as err:
self.assertEqual(str(err), text_error_4[1], "text_error_4")

def testInternFunction(self):

Expand Down Expand Up @@ -205,7 +228,7 @@ def testConditionEqual(self):
int_Equal_Str: list = ["#{i/4 == 'text'; yes | no}", "no"]
float_Equal_Str: list = ["#{f/4.5 == 'text'; yes | no}", "no"]
bool_Equal_Str: list = ["#{b/True == 'text'; yes | no}", "no"]
var_Equal_Str: list = ["#{age == 'text'; yes | no}", "no"]
var_Equal_Str: list = ["#{int == 'text'; yes | no}", "no"]

parser = TemplateStr(variableDict=varDict)

Expand All @@ -223,7 +246,7 @@ def testConditionNoTEqual(self):
int_NoT_Equal_Str: list = ["#{i/4 != 'text'; yes | no}", "yes"]
float_NoT_Equal_Str: list = ["#{f/4.5 != 'text'; yes | no}", "yes"]
bool_NoT_Equal_Str: list = ["#{b/True != 'text'; yes | no}", "yes"]
var_NoT_Equal_Str: list = ["#{age != 'text'; yes | no}", "yes"]
var_NoT_Equal_Str: list = ["#{int != 'text'; yes | no}", "yes"]

parser = TemplateStr(variableDict=varDict)

Expand Down

0 comments on commit 5b1326d

Please sign in to comment.