Try to make simple test admin page via python-requests
import requests
from django.urls import reverse
def test_admin():
resp = requests.get(reverse('admin:index'))
assert resp.status_code == 200
but got unexpected error
def test_admin():
> resp = requests.get(reverse('admin:index'))
src/users/tests/test_user_admin.py:6:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
venv1/lib/python3.5/site-packages/requests/api.py:72: in get
return request('get', url, params=params, **kwargs)
venv1/lib/python3.5/site-packages/requests/api.py:58: in request
return session.request(method=method, url=url, **kwargs)
venv1/lib/python3.5/site-packages/requests/sessions.py:494: in request
prep = self.prepare_request(req)
venv1/lib/python3.5/site-packages/requests/sessions.py:437: in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
venv1/lib/python3.5/site-packages/requests/models.py:305: in prepare
self.prepare_url(url, params)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
> raise MissingSchema(error)
E requests.exceptions.MissingSchema: Invalid URL '/admin/': No schema supplied. Perhaps you meant http:///admin/?
venv1/lib/python3.5/site-packages/requests/models.py:379: MissingSchema
List of installed packages
pytest==3.3.2
requests==2.18.4
pytest-django==3.1.2
django==1.10.2
Read a lot of docs and manual but can't find solution.
Test with different pytest.ini, manage.py, wsgi.py and settings.py
Simple tests assert 200==200 work properly.
Where is the problem?
Use request.build_absolute_uri():
resp = requests.get(request.build_absolute_uri(reverse('admin:index')))
As the error suggests, requests requires a url with schema (http, https, ftp etc).
The problem is that reverse returns a relative path (eg /admin/index) but requests needs a full url including a schema (eg http://localhost/admin/index).
If you insist on using reverse('admin:index') rather than hardcoding the full url in the test, you will need to prepend http://localhost:<port>/ (or whatever is the correct host in your case) to whatever reverse('admin:index') returns.
Related
I am converting my unittest test cases to pytest.
While running my py file, the script does its function fine (device reboot) but my test script shows the following failure:
================================================================================================ FAILURES =================================================================================================
_________________________________________________________________________________________ TestReboot.test_reboot __________________________________________________________________________________________
../../custom_xmlrunner/custom_unittest_runner.py:245: in run
self.write_result(result)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <device_reboot.TestReboot testMethod=test_reboot>, result = <TestCaseFunction test_reboot>
def write_result(self, result):
"""
Write the result of the test-case, like:
-----------------------
TESTCASE: my_test_case
RESULT: PASS
-----------------------
This too is implicitly called at the end of the test-case.
"""
self.write_log('-' * 60)
self.write_log('TESTCASE: {0}'.format(self._testMethodName))
> if result.wasSuccessful():
E AttributeError: 'TestCaseFunction' object has no attribute 'wasSuccessful'
../../custom_xmlrunner/custom_unittest_runner.py:292: AttributeError
I created below function and it's working fine but i am struggling with creating unittest for this function.
Here's my function:
def put_config_file_on_device(device, config_backup=None):
try:
runn_config = config_backup
runn_config_database = running_config_from_database(device)
if runn_config:
raw_config = runn_config
else:
raw_config = runn_config_database
new_file, filename = tempfile.mkstemp()
os.write(new_file, raw_config.encode('utf-8'))
ssh = SSHClient()
ssh.set_missing_host_key_policy(AutoAddPolicy())
ssh.load_system_host_keys()
handler = get_handler(device)
passwd = handler._get_admin_passwords()[1][0]
ssh.connect(device, username='root', password=get_cred('root'),
look_for_keys=False)
vendor = str(handler)
if 'Juniper' in vendor:
remote_path = f'/var/tmp/{device}.cfg'
if 'Cisco' in vendor:
remote_path = f'harddisk:/{device}.cfg'
scp = SCPClient(ssh.get_transport())
file_path = f'{filename}'
scp.put(file_path, remote_path, recursive=False)
scp.close()
os.remove(filename)
return True, f"File store successfully on the device {remote_path}"
except Exception as err:
return False, f"Failed to store config on Exception: {err}"
I created below unittest but it's not working. I am getting error while tetsinh the UT.
i have mocked all the dependencies but not sure what's wrong with the code. I get Attribute error for <class 'paramiko.client.SSHClient.
#pytest.mark.parametrize('mock_config_backup', ['someconfig\r\n'])
#patch("test.scripts.script.get_cred")
#patch("test.scripts.script.os")
#patch("test.scripts.script.SSHClient.")
#patch("test.scripts.script.SCPClient")
#patch("test.scripts.script.tempfile.mkstemp")
#patch("test.scripts.script.get_device_handler")
def test_put_config_file_on_device(mock_handler, mock_temp, mock_os, mock_ssh, mock_scp, mock_cred, mock_config_backup):
conf = 'someconfig\r\n'
mock_temp.return_value = new_file, filename
mock.os.write(new_file, conf.encode('utf-8'))
remote_path = '/var/tmp/devA.cfg'
file_path = f'{filename}'
mock_cred.return_value = 'xyz'
ret = MagicMock()
ret.connect('devA', username='root', password='xyz', look_for_keys=False)
mock_ssh.return_value = ret
mock_scp.put = (file_path, remote_path)
scp.close()
mock.os.remove(filename)
status, out = test.scripts.script.put_config_file_on_device(device, mock_config_backup)
assert status and out == 'File store successfully on the device /var/tmp/devA.cfg'
getting below error.
=============================================================================================== FAILURES ===============================================================================================
____________________________________________________________________________ test_put_config_file_on_device[someconfig\r\n] ____________________________________________________________________________
args = (), keywargs = {'mock_config_backup': 'someconfig\r\n'}
#wraps(func)
def patched(*args, **keywargs):
with self.decoration_helper(patched,
args,
> keywargs) as (newargs, newkeywargs):
/home/lib/python3.6/site-packages/mock/mock.py:1368:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/usr/lib/python3.6/contextlib.py:81: in __enter__
return next(self.gen)
/home/lib/python3.6/site-packages/mock/mock.py:1334: in decoration_helper
arg = patching.__enter__()
/home/lib/python3.6/site-packages/mock/mock.py:1437: in __enter__
original, local = self.get_original()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <mock.mock._patch object at 0x7f0e60450240>
def get_original(self):
target = self.getter()
name = self.attribute
original = DEFAULT
local = False
try:
original = target.__dict__[name]
except (AttributeError, KeyError):
original = getattr(target, name, DEFAULT)
else:
local = True
if name in _builtins and isinstance(target, ModuleType):
self.create = True
if not self.create and original is DEFAULT:
raise AttributeError(
> "%s does not have the attribute %r" % (target, name)
)
E AttributeError: <class 'paramiko.client.SSHClient'> does not have the attribute ''
/home/lib/python3.6/site-packages/mock/mock.py:1411: AttributeError
===================================================================================== 1 failed, 6 passed in 5.67s
My project implementation is to capture details from CLI to determine the environment, to generate the token in that environment and to return the token and the application URL.
Here is the code in conftest.py file
def pytest_addoption(parser):
parser.addoption('--env',
dest='testenv',
choices=["qa","aws","prod"],
default='qa',
help='Specify environment: "qa", "aws", "prod".')
#pytest.fixture(scope='session')
#def conftest_setup(request):
# env = request.config.getoption("--env")
def conftest_setup(request):
env = request.config.getoption("--env")
print(env)
if (env =='aws'):
url='AWSURL'
elif ( env =='prod'):
url='prodURL'
else:
url='QAURL'
token = requests.post(auth=HTTPBasicAuth(clientID, secret),headers=tokenheaders, data=payload)
auth = token.json()['access_token']
return auth,url
test_service.py has
auth1=''
url1=''
def initialCall(conftest_setup):
auth1=conftest_setup[1] # Pretty sure this is wrong, but couldnt get a way to retrieve this
url1=conftest_setup[2]
# Now I want to use the auth1 and url1 obtained from above method to the below method
def response():
print("auth is " ,auth1)
print("URL is " ,url1)
headers = {'content-type': 'application/json',
'Authorization' : auth1}
response=
(requests.post(url1,data=json.dumps(data1),headers=headers)).json()
Currently, I get this exception
request = <FixtureRequest for <Function
> ???
test\test_service_1.py:41:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
..\..\software\python\lib\site-packages\pytest_bdd\scenario.py:195: in _execute_scenario
_execute_step_function(request, scenario, step, step_func)
..\..\software\python\lib\site-packages\pytest_bdd\scenario.py:136: in _execute_step_function
step_func(**kwargs)
..\..\software\python\lib\site-packages\pytest_bdd\steps.py:164: in step_func
result = request.getfixturevalue(func.__name__)
..\..\software\python\lib\site-packages\_pytest\fixtures.py:478: in getfixturevalue
return self._get_active_fixturedef(argname).cached_result[0]
..\..\software\python\lib\site-packages\_pytest\fixtures.py:501: in _get_active_fixturedef
self._compute_fixture_value(fixturedef)
..\..\software\python\lib\site-packages\_pytest\fixtures.py:586: in _compute_fixture_value
fixturedef.execute(request=subrequest)
..\..\software\python\lib\site-packages\_pytest\fixtures.py:895: in execute
return hook.pytest_fixture_setup(fixturedef=self, request=request)
..\..\software\python\lib\site-packages\pluggy\hooks.py:289: in __call__
return self._hookexec(self, self.get_hookimpls(), kwargs)
..\..\software\python\lib\site-packages\pluggy\manager.py:68: in _hookexec
return self._inner_hookexec(hook, methods, kwargs)
..\..\software\python\lib\site-packages\pluggy\manager.py:62: in <lambda>
firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
..\..\software\python\lib\site-packages\_pytest\fixtures.py:937: in pytest_fixture_setup
result = call_fixture_func(fixturefunc, request, kwargs)
..\..\software\python\lib\site-packages\_pytest\fixtures.py:794: in call_fixture_func
res = fixturefunc(**kwargs)
***test\test_service_1.py:40: in testws_response
response=(requests.post(url1,data=json.dumps(data1),headers=headers)).json()***
..\..\software\python\lib\site-packages\requests\api.py:116: in post
return request('post', url, data=data, json=json, **kwargs)
..\..\software\python\lib\site-packages\requests\api.py:60: in request
return session.request(method=method, url=url, **kwargs)
..\..\software\python\lib\site-packages\requests\sessions.py:519: in request
prep = self.prepare_request(req)
..\..\software\python\lib\site-packages\requests\sessions.py:462: in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
..\..\software\python\lib\site-packages\requests\models.py:313: in prepare
self.prepare_url(url, params)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <PreparedRequest [POST]>, url = '', params = OrderedDict()
def prepare_url(self, url, params):
"""Prepares the given HTTP URL."""
#: Accept objects that have string representations.
#: We're unable to blindly call unicode/str functions
#: as this will include the bytestring indicator (b'')
#: on python 3.x.
#: https://github.com/requests/requests/pull/2238
if isinstance(url, bytes):
url = url.decode('utf8')
else:
url = unicode(url) if is_py2 else str(url)
# Remove leading whitespaces from url
url = url.lstrip()
# Don't do any URL preparation for non-HTTP schemes like `mailto`,
# `data` etc to work around exceptions from `url_parse`, which
# handles RFC 3986 only.
if ':' in url and not url.lower().startswith('http'):
self.url = url
return
# Support for unicode domain names and paths.
try:
scheme, auth, host, port, path, query, fragment = parse_url(url)
except LocationParseError as e:
raise InvalidURL(*e.args)
if not scheme:
error = ("Invalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?")
error = error.format(to_native_string(url, 'utf8'))
> raise MissingSchema(error)
E requests.exceptions.MissingSchema: Invalid URL '': No schema supplied. Perhaps you meant http://?
..\..\software\python\lib\site-packages\requests\models.py:387: MissingSchema
No console output observed for print(env) in conftest.py file while
auth is None
URL IS None
are observed for print statements in test_service
CLI execution throws error when I pass pytest -s --env='qa' but is acceptable for pytest -s --env=qa. So the CLI arguments are captured.
Please help me to capture the auth and url from conftest.py across the test file.
Also, is there a way I can use this auth,url returned from conftest.py to use across multiple test files?
Many thanks to #hoefling for providing valuable insights.
I've added/updated the fixture in the following places and declared auth1 and url1 as global inside initialcall method. It now works as expected.
test_service.py has
#pytest.fixture(autouse=True, scope='session')
def initialCall(conftest_setup):
global auth1,AN_API1
auth1 = conftest_setup[0]
AN_API1=conftest_setup[1]
conftest.py has
#pytest.fixture(autouse=True,scope='session')
def conftest_setup(request):
I'm using Python 3.4.6.
Here is the factory:
def create_parser():
""" Create argument parser """
# Input configuration parameters
_parser = argparse.ArgumentParser(description='Segments Engine')
# Application only parameters
_parser.add_argument(
'-V', '--version', version='%(prog)s ' + __version__,
action='version')
_pasrser.add_argument(
'-d', '--debug', action='store_true')
return _parser
The test case is as follows:
class TestCli(unittest.TestCase):
""" Test the cli.py module """
def __init__(self, *args, **kwargs):
""" Initialize Unit Test """
super(TestCli, self).__init__(*args, **kwargs)
def setup(self):
""" Setup before each test case """
setup_config(app)
setup_logging(app)
def teardown(self):
""" Tear down after each test case """
pass
def test_version(self):
parser = create_parser()
with pytest.raises(SystemExit):
args = vars(parser.parse_args(['', '-V']))
assert args.version == __version__
def test_debug(self):
parser = create_parser()
args = parser.parse_args(['-d'])
assert args.debug
Then I execute as follows:
pytest tests/test_cli.py
I get the following errors, what am I doing wrong?
======================================================================================= test session starts =========================================================================================
platform darwin -- Python 3.4.6, pytest-3.1.3, py-1.4.34, pluggy-0.4.0
rootdir: /Users/francisco.benavides/Documents/src/segments-engine, inifile:
collected 1 item s
tests/test_cli.py F
self = <tests.test_cli.TestCli testMethod=test_version>
def test_version(self):
parser = create_parser()
> args = vars(parser.parse_args(['', '-V']))
tests/test_cli.py:29:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
../../../.pyenv/versions/3.4.6/lib/python3.4/argparse.py:1728: in parse_args
args, argv = self.parse_known_args(args, namespace)
../../../.pyenv/versions/3.4.6/lib/python3.4/argparse.py:1760: in parse_known_args
namespace, args = self._parse_known_args(args, namespace)
../../../.pyenv/versions/3.4.6/lib/python3.4/argparse.py:1966: in _parse_known_args
start_index = consume_optional(start_index)
../../../.pyenv/versions/3.4.6/lib/python3.4/argparse.py:1906: in consume_optional
take_action(action, args, option_string)
../../../.pyenv/versions/3.4.6/lib/python3.4/argparse.py:1834: in take_action
action(self, namespace, argument_values, option_string)
../../../.pyenv/versions/3.4.6/lib/python3.4/argparse.py:1043: in __call__
parser.exit()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = ArgumentParser(prog='pytest', usage=None, description='Segments Engine', formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True), status = 0, message = None
def exit(self, status=0, message=None):
if message:
self._print_message(message, _sys.stderr)
> _sys.exit(status)
E SystemExit: 0
../../../.pyenv/versions/3.4.6/lib/python3.4/argparse.py:2373: SystemExit
---------------------------------------------------------------------------------------- Captured stdout call ----------------------------------------------------------------------------------------
pytest 0.0.1
I have tried several ways I found googling, but so far nothing has helped me.
Just a guess since you haven't shown us your create_parser implementation:
-V is a "version" type command (?), if you read the docs version is to
"[print] version information and [exit] when invoked".
You'll want to capture the exit, here's one way:
with pytest.raises(SystemExit):
parser.parse_args(['', '-V'])
# maybe use `capsys` to verify that the version was printed
out, err = capsys.readouterr()
# ...
I just wrote a function for making a move in Tic-Tac-Toe. I wanted to push pattern matching. So I wrote 9 makeAMove clauses. Each has a Tic-Tac-Toe board with a different space designated by an Empty symbol. It looks something like this.
makeAMove [[E, m12, m13],
[m21, m22, m23],
[m31, m32, m33]] X 1 1 = ...
This clause would put an X in the upper left corner of the board. X, O, and E are defined as Marks.
data Mark = X | O | E deriving (Eq, Show)
When I load the file I get this warning message.
warning:
Pattern match checker exceeded (2000000) iterations in
an equation for ‘mov1’. (Use -fmax-pmcheck-iterations=n
to set the maximun number of iterations to n)
My question is one of curiosity. What sort of iterations is the pattern matcher doing? And why are so many required?
When I limit the number of clauses to, say, 5 and put the rest in another function that is linked to by a default case, there is no problem.
Here's a MCVE:
{-# OPTIONS -Wall #-}
data T = O | A | B | C | D | E
f :: T -> T -> T -> T -> T -> T -> T -> T -> T -> ()
f O _ _ _ _ _ _ _ _ = ()
f _ O _ _ _ _ _ _ _ = ()
f _ _ O _ _ _ _ _ _ = ()
f _ _ _ O _ _ _ _ _ = ()
f _ _ _ _ O _ _ _ _ = ()
f _ _ _ _ _ O _ _ _ = ()
f _ _ _ _ _ _ O _ _ = ()
f _ _ _ _ _ _ _ O _ = ()
f _ _ _ _ _ _ _ _ O = ()
Result:
ExhaustivePattern3.hs:5:5: warning:
Pattern match checker exceeded (2000000) iterations in
an equation for ‘f’. (Use -fmax-pmcheck-iterations=n
to set the maximun number of iterations to n)
I guess the checker is trying to generate the counterexamples too eagerly: there are many unmatched patterns, exponentially growing with the number of arguments.
Indeed, after the first match the unmatched cases are
A _ _ _ _ _ _ _ _
B _ _ _ _ _ _ _ _
...
E _ _ _ _ _ _ _ _
Then after the second one, this expands to:
A A _ _ _ _ _ _ _
A ...
A E _ _ _ _ _ _ _
B A _ _ _ _ _ _ _
B ...
B E _ _ _ _ _ _ _
...
E A _ _ _ _ _ _ _
E ...
E E _ _ _ _ _ _ _
And so on. This grows exponentially.