Skip to content

Commit

Permalink
Feat: support var
Browse files Browse the repository at this point in the history
  • Loading branch information
cedric05 committed Dec 27, 2024
1 parent b50cb8e commit db78a24
Show file tree
Hide file tree
Showing 7 changed files with 106 additions and 33 deletions.
51 changes: 23 additions & 28 deletions dotextensions/server/handlers/basic_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,34 +201,29 @@ def load_model(self):
self.content = self.content + CONTEXT_SEP + CONTEXT_SEP.join(self.args.contexts)

def select_target(self):
try:
# first try to resolve target from current context
super().select_target()
except UndefinedHttpToExtend as ex:
# if it weren't able to figure out context, try to resolve from
# contexts
for context in self.args.contexts:
try:
# if model is generated, try to figure out target
model: MultidefHttp = dothttp_model.model_from_str(context)
# by including targets in to model
self.model.allhttps = self.model.allhttps + model.allhttps
if model.import_list and model.import_list.filename:
if self.model.import_list and self.model.import_list.filename:
self.model.import_list.filename += (
model.import_list.filename
)
else:
self.model.import_list = model.import_list
self.load_imports()
self.content += context + "\n\n" + context
return super(ContentBase, self).select_target()
except Exception as e:
# contexts, can not always be correct syntax
# in such scenarios, don't complain, try to resolve with
# next contexts
logger.info("ignoring exception, context is not looking good")
raise ex
for context in self.args.contexts:
try:
# if model is generated, try to figure out target
model: MultidefHttp = dothttp_model.model_from_str(context)
# by including targets in to model
self.load_properties_from_var(model, self.property_util)
self.model.allhttps = self.model.allhttps + model.allhttps
if model.import_list and model.import_list.filename:
if self.model.import_list and self.model.import_list.filename:
self.model.import_list.filename += (
model.import_list.filename
)
else:
self.model.import_list = model.import_list
self.load_imports()
self.content += context + "\n\n" + context

except Exception as e:
# contexts, can not always be correct syntax
# in such scenarios, don't complain, try to resolve with
# next contexts
logger.info("ignoring exception, context is not looking good")
return super(ContentBase, self).select_target()


class ContentRequestCompiler(ContentBase, RequestCompiler):
Expand Down
4 changes: 2 additions & 2 deletions dothttp/http.tx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@

MULTISET: (import_list=IMPORT)? (var_list=VAR*)? (allhttps=HTTP+)?;
MULTISET: (import_list=IMPORT)? (variables=VAR*)? (allhttps=HTTP+)?;

VAR:
"var" name=ID "=" value=Value
"var" name=ID ("=" value=Value)?
;

IMPORT: ('import' filename=String ';')* ;
Expand Down
6 changes: 6 additions & 0 deletions dothttp/models/parse_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
from ..exceptions import DotHttpException


@dataclass
class Variable:
name: str
value: Union[None, str]

@dataclass
class NameWrap:
name: str
Expand Down Expand Up @@ -240,6 +245,7 @@ class ImportStmt:
@dataclass
class MultidefHttp:
import_list: Optional[ImportStmt]
variables : List[Variable]
allhttps: List[Http]


Expand Down
11 changes: 10 additions & 1 deletion dothttp/parse/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
from ..utils.common import get_real_file_path, triple_or_double_tostring
from ..utils.constants import *
from ..utils.property_util import PropertyProvider
from .dsl_jsonparser import json_or_array_to_json
from .dsl_jsonparser import json_or_array_to_json, jsonmodel_to_json


def install_unix_socket_scheme():
Expand Down Expand Up @@ -236,6 +236,7 @@ def _load_imports(
model, filename
):
import_list += model.allhttps
BaseModelProcessor.load_properties_from_var(model, property_util)
property_util.add_infile_properties(content)

@staticmethod
Expand Down Expand Up @@ -352,7 +353,15 @@ def load_props_needed_for_content(self):
self._load_props_from_content(self.content, self.property_util)

def _load_props_from_content(self, content, property_util: PropertyProvider):
self.load_properties_from_var(self.model, property_util)
property_util.add_infile_properties(content)

@staticmethod
def load_properties_from_var(model, property_util):
for variable in model.variables:
if variable.value:
var_value = jsonmodel_to_json(variable.value, lambda k:k)
property_util.infile_properties[variable.name] = Property([''], variable.name, var_value)


class HttpDefBase(BaseModelProcessor):
Expand Down
2 changes: 1 addition & 1 deletion dothttp/utils/property_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ def get_updated_content(self, content, type="str"):
value = func(var)
base_logger.debug(f"using `{value}` for property {var}")
for text_to_replace in content_prop_needed[var].text:
content = content.replace("{{" + text_to_replace + "}}", value)
content = content.replace("{{" + text_to_replace + "}}", str(value))
return content

def validate_n_gen(self, prop, cache: Dict[str, Property]):
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "dothttp-req"
version = "0.0.43"
version = "0.0.44a1"
description = "Dothttp is Simple http client for testing and development"
authors = ["Prasanth <[email protected]>"]
license = "MIT"
Expand Down
63 changes: 63 additions & 0 deletions test/extensions/test_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,66 @@ def test_execute_content_context_multiple_base(self):
""",
result.result["body"],
)

def test_execute_content_context_with_var_normal(self):
# tests to pick first context if multiple contexts are there
result = self.execute_and_result(
"""
@name('test')
POST "http://localhost:8000/post"
json({
"a":{{a}},
"b":"{{b}}",
})
""",
target="test",
contexts=[
# as it is not single file
# there can be multiple targets
# defined with same name
# in such scenario
# only first one will be picked
"""
var a = 10
""",
"""
var b = 20
"""
],
curl=False,
)
self.assertEqual(
{
"a": 10,
"b": '20',
},
json.loads(result.result["body"])["json"],
)


def test_execute_content_context_with_var_with_json(self):
# tests to pick first context if multiple contexts are there
result = self.execute_and_result(
"""
@name('test')
POST "http://localhost:8000/post"
json({
"c" : {{c}}
})
""",
target="test",
contexts=[
"""
var c = {"ram":"ranga", "raja":[1, true, false, null]}
"""
],
curl=False,
)
self.assertEqual(
{
"c" : {"ram":"ranga", "raja":[1, True, False, None]}
},
json.loads(result.result["body"])["json"],
)

0 comments on commit db78a24

Please sign in to comment.