Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Optimistaion] : Made the code block more efficient to understand in test_api.py file #343

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
The diff you're trying to view is too large. We only load the first 3000 changed files.
23 changes: 11 additions & 12 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

from torbot.modules.api import get_ip


def generate_mock_torproject_page(header: str, body: str) -> str:
doc, tag, text = Doc().tagtext()
with tag("html"):
Expand All @@ -13,24 +12,24 @@ def generate_mock_torproject_page(header: str, body: str) -> str:
text(header)
with tag("p"):
text(body)

return doc.getvalue()


@patch.object(httpx.Client, "get")
def test_get_ip(mock_get) -> None:
# generate HTML
mock_header = "TorProject Page"
mock_body = "You are connected to tor. IP 127.0.0.1"
mock_html_page = generate_mock_torproject_page(mock_header, mock_body)
# Generate mock HTML page
mock_html_page = generate_mock_torproject_page(
header="TorProject Page",
body="You are connected to tor. IP 127.0.0.1"
)

# define mock
# Define mock response
mock_response = Mock()
mock_get.return_value = mock_response
mock_response.text = mock_html_page
mock_get.return_value = mock_response

# attempt test
#added the perform test block for effiecient catch
# Perform test
with httpx.Client() as client:
resp = get_ip(client)
assert resp["header"] == mock_header
assert resp["body"] == mock_body
assert resp["header"] == "TorProject Page"
assert resp["body"] == "You are connected to tor. IP 127.0.0.1"
86 changes: 86 additions & 0 deletions torbot_venv/Include/site/python3.11/igraph/igraphmodule_api.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/* -*- mode: C -*- */
/* vim:set ts=2 sw=2 sts=2 et: */
/*
IGraph library.
Copyright (C) 2006-2012 Tamas Nepusz <[email protected]>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA

*/

#ifndef Py_IGRAPHMODULE_H
#define Py_IGRAPHMODULE_H

#ifdef __cplusplus
extern "C" {
#endif

/* C API functions */
#define PyIGraph_FromCGraph_NUM 0
#define PyIGraph_FromCGraph_RETURN PyObject*
#define PyIGraph_FromCGraph_PROTO (igraph_t *graph)

#define PyIGraph_ToCGraph_NUM 1
#define PyIGraph_ToCGraph_RETURN igraph_t*
#define PyIGraph_ToCGraph_PROTO (PyObject *graph)

/* Total number of C API pointers */
#define PyIGraph_API_pointers 2

#ifdef IGRAPH_MODULE
/* This section is used when compiling igraphmodule.c */
static PyIGraph_FromCGraph_RETURN PyIGraph_FromCGraph PyIGraph_FromCGraph_PROTO;
static PyIGraph_ToCGraph_RETURN PyIGraph_ToCGraph PyIGraph_ToCGraph_PROTO;
#else
/* This section is used in modules that use igraph's API */
static void** PyIGraph_API;
# define PyIGraph_FromCGraph \
(*(PyIGraph_FromCGraph_RETURN (*)PyIGraph_FromCGraph_PROTO) \
PyIGraph_API[PyIGraph_FromCGraph_NUM])
# define PyIGraph_ToCGraph \
(*(PyIGraph_ToCGraph_RETURN (*)PyIGraph_ToCGraph_PROTO) \
PyIGraph_API[PyIGraph_ToCGraph_NUM])

/* Return -1 and set exception on error, 0 on success */
static int import_igraph(void) {
PyObject *c_api_object;
PyObject *module;

module = PyImport_ImportModule("igraph._igraph");
if (module == 0)
return -1;

c_api_object = PyObject_GetAttrString(module, "_C_API");
if (c_api_object == 0) {
Py_DECREF(module);
return -1;
}

if (PyCObject_Check(c_api_object))
PyIGraph_API = (void**)PyCObject_AsVoidPtr(c_api_object);

Py_DECREF(c_api_object);
Py_DECREF(module);
return 0;
}

#endif

#ifdef __cplusplus
}
#endif

#endif /* !defined(Py_IGRAPHMODULE_H) */
67 changes: 67 additions & 0 deletions torbot_venv/Lib/site-packages/PyInstaller/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#-----------------------------------------------------------------------------
# Copyright (c) 2005-2023, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License (version 2
# or later) with exception for distributing the bootloader.
#
# The full license is in the file COPYING.txt, distributed with this software.
#
# SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
#-----------------------------------------------------------------------------

__all__ = ('HOMEPATH', 'PLATFORM', '__version__', 'DEFAULT_DISTPATH', 'DEFAULT_SPECPATH', 'DEFAULT_WORKPATH')

import os
import sys

from PyInstaller import compat
from PyInstaller.utils.git import get_repo_revision

# Note: Keep this variable as plain string so it could be updated automatically when doing a release.
__version__ = '5.13.1'

# Absolute path of this package's directory. Save this early so all submodules can use the absolute path. This is
# required for example if the current directory changes prior to loading the hooks.
PACKAGEPATH = os.path.abspath(os.path.dirname(__file__))

HOMEPATH = os.path.dirname(PACKAGEPATH)

# Update __version__ as necessary.
if os.path.exists(os.path.join(HOMEPATH, 'setup.py')):
# PyInstaller is run directly from source without installation, or __version__ is called from 'setup.py'...
if compat.getenv('PYINSTALLER_DO_RELEASE') == '1':
# Suppress the git revision when doing a release.
pass
elif 'sdist' not in sys.argv:
# and 'setup.py' was not called with 'sdist' argument. For creating source tarball we do not want git revision
# in the filename.
try:
__version__ += get_repo_revision()
except Exception:
# Write to stderr because stdout is used for eval() statement in some subprocesses.
sys.stderr.write('WARN: failed to parse git revision')
else:
# PyInstaller was installed by `python setup.py install'.
if compat.is_py38:
from importlib.metadata import version
else:
from importlib_metadata import version
__version__ = version('PyInstaller')
# Default values of paths where to put files created by PyInstaller. If changing these, do not forget to update the
# help text for corresponding command-line options, defined in build_main.

# Where to put created .spec file.
DEFAULT_SPECPATH = os.getcwd()
# Where to put the final frozen application.
DEFAULT_DISTPATH = os.path.join(os.getcwd(), 'dist')
# Where to put all the temporary files; .log, .pyz, etc.
DEFAULT_WORKPATH = os.path.join(os.getcwd(), 'build')

PLATFORM = compat.system + '-' + compat.architecture
# Include machine name in path to bootloader for some machines (e.g., 'arm'). Explicitly avoid doing this on macOS,
# where we keep universal2 bootloaders in Darwin-64bit folder regardless of whether we are on x86_64 or arm64.
if compat.machine and not compat.is_darwin:
PLATFORM += '-' + compat.machine
# Similarly, disambiguate musl Linux from glibc Linux.
if compat.is_musl:
PLATFORM += '-musl'
198 changes: 198 additions & 0 deletions torbot_venv/Lib/site-packages/PyInstaller/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
#-----------------------------------------------------------------------------
# Copyright (c) 2013-2023, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License (version 2
# or later) with exception for distributing the bootloader.
#
# The full license is in the file COPYING.txt, distributed with this software.
#
# SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
#-----------------------------------------------------------------------------
"""
Main command-line interface to PyInstaller.
"""
from __future__ import annotations

import argparse
import os
import platform
import sys
from collections import defaultdict

from PyInstaller import __version__
from PyInstaller import log as logging
# Note: do not import anything else until compat.check_requirements function is run!
from PyInstaller import compat

logger = logging.getLogger(__name__)

# Taken from https://stackoverflow.com/a/22157136 to format args more flexibly: any help text which beings with ``R|``
# will have all newlines preserved; the help text will be line wrapped. See
# https://docs.python.org/3/library/argparse.html#formatter-class.


# This is used by the ``--debug`` option.
class _SmartFormatter(argparse.HelpFormatter):
def _split_lines(self, text, width):
if text.startswith('R|'):
# The underlying implementation of ``RawTextHelpFormatter._split_lines`` invokes this; mimic it.
return text[2:].splitlines()
else:
# Invoke the usual formatter.
return super()._split_lines(text, width)


def run_makespec(filenames, **opts):
# Split pathex by using the path separator
temppaths = opts['pathex'][:]
pathex = opts['pathex'] = []
for p in temppaths:
pathex.extend(p.split(os.pathsep))

import PyInstaller.building.makespec

spec_file = PyInstaller.building.makespec.main(filenames, **opts)
logger.info('wrote %s' % spec_file)
return spec_file


def run_build(pyi_config, spec_file, **kwargs):
import PyInstaller.building.build_main
PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)


def __add_options(parser):
parser.add_argument(
'-v',
'--version',
action='version',
version=__version__,
help='Show program version info and exit.',
)


class _PyiArgumentParser(argparse.ArgumentParser):
def __init__(self, *args, **kwargs):
self._pyi_action_groups = defaultdict(list)
super().__init__(*args, **kwargs)

def _add_options(self, __add_options: callable, name: str = ""):
"""
Mutate self with the given callable, storing any new actions added in a named group
"""
n_actions_before = len(getattr(self, "_actions", []))
__add_options(self) # preserves old behavior
new_actions = getattr(self, "_actions", [])[n_actions_before:]
self._pyi_action_groups[name].extend(new_actions)

def _option_name(self, action):
"""
Get the option name(s) associated with an action

For options that define both short and long names, this function will
return the long names joined by "/"
"""
longnames = [name for name in action.option_strings if name.startswith("--")]
if longnames:
name = "/".join(longnames)
else:
name = action.option_strings[0]
return name

def _forbid_options(self, args: argparse.Namespace, group: str, errmsg: str = ""):
"""Forbid options from a named action group"""
options = defaultdict(str)
for action in self._pyi_action_groups[group]:
dest = action.dest
name = self._option_name(action)
if getattr(args, dest) is not self.get_default(dest):
if dest in options:
options[dest] += "/"
options[dest] += name

# if any options from the forbidden group are not the default values,
# the user must have passed them in, so issue an error report
if options:
sep = "\n "
bad = sep.join(options.values())
if errmsg:
errmsg = "\n" + errmsg
raise SystemExit(f"option(s) not allowed:{sep}{bad}{errmsg}")


def generate_parser() -> _PyiArgumentParser:
"""
Build an argparse parser for PyInstaller's main CLI.
"""

import PyInstaller.building.build_main
import PyInstaller.building.makespec
import PyInstaller.log

parser = _PyiArgumentParser(formatter_class=_SmartFormatter)
parser.prog = "pyinstaller"

parser._add_options(__add_options)
parser._add_options(PyInstaller.building.makespec.__add_options, name="makespec")
parser._add_options(PyInstaller.building.build_main.__add_options, name="build_main")
parser._add_options(PyInstaller.log.__add_options, name="log")

parser.add_argument(
'filenames',
metavar='scriptname',
nargs='+',
help="Name of scriptfiles to be processed or exactly one .spec file. If a .spec file is specified, most "
"options are unnecessary and are ignored.",
)

return parser


def run(pyi_args: list | None = None, pyi_config: dict | None = None):
"""
pyi_args allows running PyInstaller programmatically without a subprocess
pyi_config allows checking configuration once when running multiple tests
"""
compat.check_requirements()

import PyInstaller.log

try:
parser = generate_parser()
args = parser.parse_args(pyi_args)
PyInstaller.log.__process_options(parser, args)

# Print PyInstaller version, Python version, and platform as the first line to stdout. This helps us identify
# PyInstaller, Python, and platform version when users report issues.
logger.info('PyInstaller: %s' % __version__)
logger.info('Python: %s%s', platform.python_version(), " (conda)" if compat.is_conda else "")
logger.info('Platform: %s' % platform.platform())

# Skip creating .spec when .spec file is supplied.
if args.filenames[0].endswith('.spec'):
parser._forbid_options(
args, group="makespec", errmsg="makespec options not valid when a .spec file is given"
)
spec_file = args.filenames[0]
else:
spec_file = run_makespec(**vars(args))

run_build(pyi_config, spec_file, **vars(args))

except KeyboardInterrupt:
raise SystemExit("Aborted by user request.")
except RecursionError:
from PyInstaller import _recursion_too_deep_message
_recursion_too_deep_message.raise_with_msg()


def _console_script_run():
# Python prepends the main script's parent directory to sys.path. When PyInstaller is ran via the usual
# `pyinstaller` CLI entry point, this directory is $pythonprefix/bin which should not be in sys.path.
if os.path.basename(sys.path[0]) in ("bin", "Scripts"):
sys.path.pop(0)
run()


if __name__ == '__main__':
run()
Loading