Exemplo n.º 1
0
    async def handler(self, request: Request, method: str) -> Response:
        _ = self.__server
        __response = Response(status_code=404)
        _endpoint_method_data = request.app.state.mock.get(request.url.path)
        _header = dict(zip(request.headers.keys(), request.headers.values()))
        _query = dict(zip(request.query_params.keys(), request.query_params.values()))
        _body = {}
        __raw_body = await request.body()
        try:
            _form = await request.form()
            _keys = _form.keys()
            _values = _form.values()
            _body = dict(zip(_keys, _values))
        finally:
            pass

        try:
            _body = await request.json()
        except JSONDecodeError:
            pass

        if _endpoint_method_data:
            _endpoint: Dict = _endpoint_method_data.get(method, {'responses': [], 'delay': 0})
            _responses: List[SwaVanResponse] = _endpoint.get('responses', '')
            for _response in _responses:
                _matched_rules = rule_matcher(_response.rules, _header, _query, _body)
                _and_rules = _response.connector.lower() == "and" and all(_matched_rules)
                _or_rules = _response.connector.lower() == "or" and any(_matched_rules)
                _have_rules = len(_response.rules) != 0
                _and_or_rules_and_has_rules = _and_rules or _or_rules or not _have_rules
                _and_or_rule_matched = RuleStatus.Matched if _and_or_rules_and_has_rules else RuleStatus.Unmatched
                _code_rule_matched = filter_by_code(
                    _response.filter_by,
                    query=_query,
                    headers=_header,
                    body=_body,
                    rule_status=_and_or_rule_matched) if _response.filter_by else _and_or_rule_matched
                if _code_rule_matched == RuleStatus.Matched:
                    if _response.redirect:
                        try:
                            __response_data = await SwaVanRestEndpoint.proxy_request(
                                _response,
                                method,
                                request.app.state.proxies)
                            if __response_data:
                                __response = __response_data
                        except requests.exceptions.ConnectionError as err:
                            __response.status_code = 500
                            __response.body = b"Unable to redirect request, please check the log message"
                            SwaVanLogRecorder.send_log(f"Unable to redirect request {err}")
                    elif _response.content_path:
                        __response = await SwaVanRestEndpoint.file_response(_response)
                    else:
                        __response = await SwaVanRestEndpoint.make_response(_response)
                    break
            sleeping_period = _endpoint.get('delay') or request.app.state.delay or 0
            time.sleep(sleeping_period)

        return __response
Exemplo n.º 2
0
def make_http_request(params: RequestModal) -> Response:
    _params = asdict(params)
    try:
        return request(**_params)
    except HTTPError as http_err:
        SwaVanLogRecorder.send_log(f'HTTP error occurred: {http_err}')
    except Exception as err:
        SwaVanLogRecorder.send_log(f'Other error occurred: {err}')
Exemplo n.º 3
0
 def save(cls, _endpoint: Endpoint) -> bool:
     is_saved = False
     try:
         DataStoreService.save(asdict(_endpoint), cls.__filename)
         is_saved = True
     except Exception as e:
         SwaVanLogRecorder.send_log(f"Error on save: {e}")
     finally:
         return is_saved
Exemplo n.º 4
0
 def save(cls, _mock: MockModal) -> bool:
     is_saved = False
     try:
         DataStoreService.save(asdict(_mock), cls.__filename)
         is_saved = True
     except IOError as err:
         SwaVanLogRecorder.send_log(f"Error on mock save {err}")
     finally:
         return is_saved
Exemplo n.º 5
0
 def load(cls) -> List[Endpoint]:
     endpoints = []
     try:
         endpoints = [
             Endpoint.from_dict(endpoint)
             for endpoint in DataStoreService.load(cls.__filename)
         ]
     except Exception as e:
         SwaVanLogRecorder.send_log(f"Error while loading data: {e}")
     finally:
         return endpoints
Exemplo n.º 6
0
    def save(self):
        _rows = []
        for _row in self.validated_endpoints():
            _row.id = str(uuid.uuid4())
            _row.pid = SwaVanCache.get_selected_env()
            _rows.append(_row)

        if len(_rows) > 0:
            _status = EndpointService.save_all(_rows)
            if _status:
                SwaVanLogRecorder.send_log(f"{len(_rows)} endpoint/s imported")
                self.saved.emit()
Exemplo n.º 7
0
    def save_all(cls, _endpoints: List[Endpoint]) -> bool:
        is_saved = False

        try:
            DataStoreService.save_all([
                asdict(_endpoint)
                for _endpoint in _endpoints if not cls.is_endpoint_duplicate(
                    _endpoint.url, _endpoint.http_method, _endpoint.id,
                    _endpoint.pid)
            ], cls.__filename)
            is_saved = True
        except Exception as e:
            SwaVanLogRecorder.send_log(f"Error while saving all: {e}")
        finally:
            return is_saved
Exemplo n.º 8
0
def match_body(_rule: Rule, _data) -> bool:
    _operator, _value = None, None
    _fields = _rule.field.split(".")
    try:
        for field in _fields:
            if isinstance(_data, list) and len(_data) > 0:
                _data = _data[int(field)]
            elif isinstance(_data, dict):
                _data = _data.get(field, None)
            _operator, _value = _rule.operator, _rule.value
        return SwaVanComparable.action(_rule.operator, _data, _rule.value)
    except Exception as err:
        SwaVanLogRecorder.send_log(
            f"Error occurred while comparing with body: {err}")
        return False
Exemplo n.º 9
0
def curl_handler(command: str) -> RequestModal:
    try:
        removed_unwanted = command.replace("\\", "")
        _request = parse_context(f"{removed_unwanted}")
        return RequestModal(method=_request.method,
                            url=_request.url,
                            data=_request.data or None,
                            headers=dict(
                                zip(_request.headers.keys(),
                                    _request.headers.values())),
                            cookies=dict(
                                zip(_request.cookies.keys(),
                                    _request.cookies.values())),
                            verify=True,
                            auth=_request.auth)
    except Exception as err:
        SwaVanLogRecorder.send_log(f"Unable to parse the cURL {err}")
Exemplo n.º 10
0
def response_modifier(function_body,
                      response: Response) -> Union[SwaVanHttpResponse, None]:
    _custom = code_to_text(function_body)
    if 'def swavan_response() -> None:' in _custom:
        _mutable_response = mutable_response(response=response)
        _func_literal = string_func_wrapper(_custom, 'swavan_response')
        print(_func_literal)
        try:
            exec(
                _func_literal, {
                    "swavan": SwaVanHttp(response=_mutable_response),
                    "Dict": Dict,
                    'json': json
                }, {
                    "Dict": Dict,
                    'json': json
                })
        except Exception as err:
            SwaVanLogRecorder.send_log(
                f"Error occurred while execution custom code {err}")
            SwaVanLogRecorder.send_log(f"Custom code change didn't applied")
        return _mutable_response
    return None
Exemplo n.º 11
0
Arquivo: page.py Projeto: swavan/oneui
    def create_log_view(self):
        _dock = QDockWidget("Log", self)
        _dock.setFloating(True)
        _view = QTextEdit()
        _dock.setWindowModality(Qt.WindowModality.NonModal)
        for row in SwaVanLogRecorder.reading_log():
            _pre = _view.toPlainText()
            _view.setPlainText(f"{_pre}\n{row}")

        _view.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        _view.setHorizontalScrollBarPolicy(
            Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        _dock.setWidget(_view)
        self.mock_right_size.addWidget(_dock)
Exemplo n.º 12
0
 def __init__(self, _mock: Mock):
     self._id = _mock.id
     self._mock = _mock
     _headers = [('server', 'swavan')]
     _config = Config(app=SwaVanHttp(_mock).app,
                      host="localhost",
                      headers=_headers,
                      port=int(_mock.port),
                      access_log=False)
     if _mock.enable_https:
         _key = full_path("data/__certs__/swavan.key")
         _crt = full_path("data/__certs__/swavan.crt")
         if _mock.use_default_cert:
             if os.path.isfile(_key) and os.path.isfile(_crt):
                 _config.ssl_keyfile = _key
                 _config.ssl_certfile = _crt
                 SwaVanLogRecorder.send_log(f"Using default cert")
         else:
             if os.path.isfile(_mock.ssl_key_file_url) and os.path.isfile(
                     _mock.ssl_cert_file_url):
                 _config.ssl_keyfile = _mock.ssl_key_file_url
                 _config.ssl_certfile = _mock.ssl_cert_file_url
                 SwaVanLogRecorder.send_log(f"Using custom cert")
     self._core_server = Server(config=_config)
Exemplo n.º 13
0
 async def delete(self, request):
     SwaVanLogRecorder.send_log(f"Delete request made")
     return await self.handler(request, "delete")
Exemplo n.º 14
0
 async def put(self, request):
     SwaVanLogRecorder.send_log(f"Put request made")
     return await self.handler(request, "put")
Exemplo n.º 15
0
 async def get(self, request: Request):
     SwaVanLogRecorder.send_log(f"Get request made")
     return await self.handler(request, "get")
Exemplo n.º 16
0
Arquivo: main.py Projeto: swavan/oneui
import os
import sys
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QApplication

from dashboad import SwaVanMainWindow
from shared.recorder import SwaVanLogRecorder
from shared.widgets.builder import full_path

if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setApplicationDisplayName("SwaVan")
    app.setApplicationName("SwaVan")
    app.setDesktopFileName("SwaVan")

    app.setWindowIcon(QIcon(full_path("assets/images/logo/swavan_one_ui.icns")))
    with open(full_path("assets/style/dark.qss"), 'r') as file:
        qss = file.read()
        app.setStyleSheet(qss)
        if os.path.exists(full_path("data/logs/swavan.log")):
            open(full_path("data/logs/swavan.log"), 'w').close()

    widget = SwaVanMainWindow()
    widget.show()
    SwaVanLogRecorder.init()
    sys.exit(app.exec())