pytest-factoryboy register factory with custom name - error fixture not found - testing

using pytest-factoryboy in my conftest.py
import pytest
from pytest_factoryboy import register
from rest_framework.test import APIClient
from apps.api.factories import leadfactory, userfactory
#pytest.fixture
def client():
return APIClient()
#pytest.fixture
def staff(db):
return userfactory.StaffFactory()
register(leadfactory.OpenLeadFactory, "lead1")
pytest_lead.py
def test_leads_get(self, client, staff, lead1):
client.login(username=staff.username, password="staff")
url = reverse("lead_list")
response = client.get(url)
assert response.status_code == 200
after runnig pytest i'm getting error
________________________________________________ ERROR at setup of TestLeads.test_leads_get ________________________________________________
file C:\Users\suraj\Desktop\ShwetaSoftwares\Working\git\udimagic_project\apps\api\pytest\pytest_leads.py, line 38
def test_leads_get(self, client, staff, lead1):
file C:\Users\suraj\AppData\Local\Programs\Python\Python39\lib\site-packages\pytest_factoryboy\fixture.py, line 350
def model_fixture(request: SubRequest, factory_name: str) -> Any:
file C:\Users\suraj\AppData\Local\Programs\Python\Python39\lib\site-packages\pytest_factoryboy\fixture.py, line 503
def subfactory_fixture(request: SubRequest, factory_class: FactoryType) -> Any:
E fixture 'custom_user__first_name' not found
> available fixtures: _dj_autoclear_mailbox, _django_clear_site_cache, _django_db_helper, _django_db_marker, _django_set_urlconf, _django_setup_unittest, _fail_for_invalid_template_variable, _live_server_helper, _session_faker, _template_string_if_invalid_marker, admin_client, admin_user, affiliate, async_client, async_rf, cache, capfd, capfdbinary, caplog, capsys, capsysbinary, client, db, django_assert_max_num_queries, django_assert_num_queries, django_capture_on_commit_callbacks, django_db_blocker, django_db_createdb, django_db_keepdb, django_db_modify_db_settings, django_db_modify_db_settings_parallel_suffix, django_db_modify_db_settings_tox_suffix, django_db_modify_db_settings_xdist_suffix, django_db_reset_sequences, django_db_serialized_rollback, django_db_setup, django_db_use_migrations, django_mail_dnsname, django_mail_patch_dns, django_test_environment, django_user_model, django_username_field, doctest_namespace, factoryboy_request, faker, lead1, lead1__addresscountry, lead1__addressstate, lead1__billing_name, lead1__created_at, lead1__created_by, lead1__description, lead1__email, lead1__first_name, lead1__lead_status, lead1__mobile, lead1__owner, lead_data, live_server, mailoutbox, monkeypatch, normal, open_lead_factory, partner1, partner2, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, rf, settings, staff, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory, transactional_db
> use 'pytest --fixtures [testpath]' for help on them.
when i'm using it without custom name its working -
register(leadfactory.OpenLeadFactory)
help me, after using custom name where i'm making mistake

Related

Google people API returning empty / no results in Python

I'm trying to read contacts from my person gmail account and the instructions provided by Google from the People API is returning an empty list. I'm not sure why. I've tried another solution from a few years ago, but that doens't seem to work. I've pasted my code below. Any help troubleshooting this is appreciated!
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/contacts.readonly']
from google.oauth2 import service_account
SERVICE_ACCOUNT_FILE = '<path name hidden>.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
def main():
#Shows basic usage of the People API.
#Prints the name of the first 10 connections.
creds = None
service = build('people', 'v1', credentials=credentials)
# Call the People API
print('List 10 connection names')
results = service.people().connections().list(
resourceName='people/me',
pageSize=10,
personFields='names,emailAddresses').execute()
connections = results.get('connections', [])
request = service.people().searchContacts(pageSize=10, query="A", readMask="names")
results = service.people().connections().list(resourceName='people/me',personFields='names,emailAddresses',fields='connections,totalItems,nextSyncToken').execute()
for i in results:
print ('result', i)
for person in connections:
names = person.get('names', [])
if names:
name = names[0].get('displayName')
print(name)
if __name__ == '__main__':
main()

django rest framework test code self.client.delete problem

from rest_framework import status, response
from rest_framework.test import APITestCase
from lots.models import Lot
class LotsTestCase(APITestCase):
def setUp(self) -> None:
self.lot = Lot.objects.create(name="1",
address="Dont Know",
phone_num="010-4451-2211",
latitude=127.12,
longitude=352.123,
basic_rate=20000,
additional_rate=2000,
partnership=False,
section_count=3,)
def test_delete(self):
response = self.client.delete(f'api/lots/{self.lot["name"]}')
# response = self.client.delete(f'/api/users/{self.users[0].pk}')
# url = reverse(f'/api/lots/{self.lot}', kwargs={'pk': self.lot.pk})
# self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
self.assertEqual(self.lot.objects.filter(pk=self.lot.pk.count()))
I have problems with the test code above. Why doesn't it work? I know it has to do with calling dictionary values but I just can't figure it out. Thanks for your help.
Lot.objects.create(...) returns a Lot type so you access name by self.lot.name.

How can messages be retained in a Flask website?

I'm new to Flask and trying to understand how to retain variable values. To do this, I'm trying to write a small application that can accept message inputs, add them to a list and then print out that list. My code isn't working and I'm not sure why. I would appreciate guidance on this problem (and on any other obvious problems).
from flask import Flask
from flask import request
from flask import redirect
class Server(Flask):
def __init__(self, *args, **kwargs):
super(Server, self).__init__(*args, **kwargs)
self.messages = []
server = Server(__name__)
#server.route('/')
def form():
return "messages: " + server.messages
#server.route("/input_message")
def input_message():
return '<form action="/store_message" method="GET"><input name="input1"><input type="submit" value="enter message"></form>'
#server.route("/store_message")
def store_message():
server.messages.append(request.args.get('input1', ''))
return redirect("http://127.0.0.1:5000", code = 302)
if __name__ == "__main__":
server.run(
host = "127.0.0.1",
port = "5000"
)
In your example server.messages is a list, but you're treating it like a string so "messages:" + server.messages is going to lead to an error. You want something like "messages: " + ",".join(server.messages)

SoapUI API - Setting TestCase property

I'm trying to use SoapUI API in jython (modifying SoapUILibrary for Robot Framework) and somehow i am not able to find any way to set property of a Property TestStep.
Setting project, global and system properties is easy using
SoapUITestCaseRunner.setProjectProperties()
from com.eviware.soapui.tools import (SoapUITestCaseRunner)
from com.eviware.soapui.tools import (SoapUIMockServiceRunner)
from robot.api import logger
class SoapUILibrary2:
""" The main class of the library """
ROBOT_LIBRARY_SCOPE = 'TEST CASE'
ROBOT_LIBRARY_VERSION = '0.2'
def __init__(self):
self.__runner = None
self.__mockrunner = None
self._project_properties = []
def soapui_project(self, prj):
""" Initialize the runner and set the project string """
self.__runner = SoapUITestCaseRunner()
self.__runner.setProjectFile(prj)
def soapui_suite(self, s):
""" Set the suite string """
self.__runner.setTestSuite(s)
def soapui_case(self, c):
""" Set the test case string """
self.__runner.setTestCase(c)
def soapui_set_project_property(self, *properties):
""" Sets project properties for the current test run. (...)
"""
for prop in properties:
if len(prop.split('=')) == 2:
self._project_properties.append(prop)
else:
logger.warn("Skipping property: '%s'. Properties must be specified as: key=value" % prop)
try:
self.__runner.setProjectProperties(self._project_properties)
except AttributeError:
logger.warn('No project set. Cannot set project properties.')
SoapUITestCaseRunner class does not contain any way to access testSteps...
I found some examples how to solve this issue in groovy, however is it possible to set such properties using SoapUI API?
EDIT:
Adding whole code of the library. It's made to be imported in robot framework and used as its keywords.
http://tny.cz/34882261
In SOAPUI you can define properties for project, testCase and testSuite, it's also possible to generate a special type of testStep (Properties TestStep) but you can't define properties on a specific testStep (i.e on SOAP TestStep). You can see more info about here
However you can use a properties from project, testCase or testSuite in your testSteps so i.e you can define a property in a project level and then use it in your testStep. I can't give more specific info because I don't know exactly what you're trying to achieve.
EDIT:
I don't know the specific jython syntax but If you have the project file (as I see in your sample) you can access a specific testStep through com.eviware.soapui.impl.wsdl.WsdlProject, I give you a groovy script as example:
import com.eviware.soapui.impl.wsdl.WsdlProject;
import com.eviware.soapui.impl.wsdl.WsdlTestSuite;
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCase;
import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep
def prj = new WsdlProject(path_prj_file,null);
def tsuite = prj.getTestSuiteByName("TestSuiteName");
def tcase = tsuite.getTestCaseByName("TestCaseName");
def tstep = tcase.getTestStepByName("TestStep");
EDIT 2:
I download jython standalone version 2.5.3 and use soapui 5.0.0 and works for me:
hw.py
from com.eviware.soapui.tools import (SoapUITestCaseRunner)
from com.eviware.soapui.tools import (SoapUILoadTestRunner)
from com.eviware.soapui.tools import (SoapUIMockServiceRunner)
from com.eviware.soapui.impl.wsdl import (WsdlProject)
from com.eviware.soapui.impl.wsdl import (WsdlTestSuite)
from com.eviware.soapui.impl.wsdl.testcase import (WsdlTestCase)
from com.eviware.soapui.impl.wsdl.teststeps import (WsdlTestRequestStep)
import thread
class SoapUI2:
""" The main class of the library """
ROBOT_LIBRARY_SCOPE = 'TEST CASE'
ROBOT_LIBRARY_VERSION = '0.2'
def __init__(self):
self.__runner = None
self.__mockrunner = None
self._project_properties = []
self.__prj = WsdlProject('C:\soapui_project.xml', None)
self.__tsuite = self.__prj.getTestSuiteByName("myTestSuite")
self.__tcase = self.__tsuite.getTestCaseByName("myTestCase")
self.__tstep = self.__tcase.getTestStepByName("myTestStep")
t = self.__tstep.getPropertyValue("Value")
print "Works ok"
def soapui_project(self, prj):
""" Initialize the runner and set the project string """
self.__runner = SoapUITestCaseRunner()
self.__runner.setProjectFile(prj)
def soapui_multiproject(self, prj):
""" Initialize the runner and set the project string """
self.__runner = SoapUILoadTestRunner()
self.__runner.setProjectFile(prj)
def soapui_suite(self, s):
""" Set the suite string """
self.__runner.setTestSuite(s)
def soapui_case(self, c):
""" Set the test case string """
self.__runner.setTestCase(c)
def soapui_set_project_property(self, *properties):
""" Sets project properties for the current test run.
This assumes that you have already initialized the project via
the `SoapUI Project` keyword.
`properies` may contain multiple statements, and each must be specified as: key=value.
This is useful to data drive your existing SoapUI tests via property expansion.
For more information see: http://www.soapui.org/Scripting-Properties/property-expansion.html
Example:
| SoapUI Project | My Project |
| SoapUI Set Project Property | ServiceEndpoint=https://staging.company.com | # set a single property |
| SoapUI Set Project Property | CustomProperty=foo | AnotherProperty=bar | # or set multiple properties |
"""
for prop in properties:
if len(prop.split('=')) == 2:
self._project_properties.append(prop)
else:
logger.warn("Skipping property: '%s'. Properties must be specified as: key=value" % prop)
try:
self.__runner.setProjectProperties(self._project_properties)
except AttributeError:
logger.warn('No project set. Cannot set project properties.')
def soapui_set_multiproject_threads(self, t):
""" Sets number of threads to run in load test """
self.__runner.setThreadCount(long(t))
logger.info("Running with %s threads at once." % t)
def soapui_run(self):
""" Run the runner and report to Robot """
logger.info("Running with the following project properties set: %s" % self._project_properties)
if not self.__runner.run():
raise AssertionError('FAIL: failed to run')
if self.__runner == SoapUITestCaseRunner():
n = self.__runner.getFailedTests().size()
if n != 0:
raise AssertionError('FAIL: ' + str(n) + ' tests failed')
def soapui_start_mock_service(self, p, m):
""" Runs a mock service """
try:
self.__mockrunner = SoapUIMockServiceRunner()
self.__mockrunner.setProjectFile(p)
self.__mockrunner.setMockService(m)
self.__mockrunner.setBlock(False)
self.__mockrunner.run()
except Exception, e:
raise AssertionError('FAIL: Error running the mock service ' + m + '. Reason: ' + str(e))
def soapui_stop_mock_service(self):
""" Stops the mock service """
self.__mockrunner.stopAll()
def soapui_set_step_property(self, s, p,v):
testStep = self.__runner.testCase.getTestStepByName(s)
testStep.setPropertyValue(p,v)
if __name__ == "__main__":
SoapUI2().__init__()
cmd line execution:
java -classpath "jython-standalone-2.5.3.jar;C:\Programari\SoapUI-5.0.0\lib\*;C:\Programari\SoapUI-5.0.0\bin\*" org.python.util.jython hw.py
execution result:
2014-05-27 12:43:09,058 [main] WARN com.eviware.soapui.SoapUI - Could not find jfxrt.jar. Internal browser will be disabled.
12:43:09,589 WARN [SoapUI] Missing folder [C:\temp\ext] for external libraries
12:43:09,964 INFO [DefaultSoapUICore] initialized soapui-settings from [C:\Documents and Settings\aciffone\soapui-settings.xml]
12:43:09,995 INFO [HttpClientSupport$Helper] Initializing KeyStore
12:43:11,682 INFO [WsdlProject] Loaded project from [file:/C:/soapui_project.xml]
Works ok
Hope this helps,

tornado's AsyncHttpTestCase is not available outside self.fetch

I have an AsyncHttpTestCase and I want to access it from methods besides self.fetch. Specifically, I have a SockJS handler that I want a sockjs-client to attach too for my tests.
I've discovered that even though self.get_url('/foo') returns a valid url, that url does not respond to anything except for self.fetch(). What gives?
Is this just not possible with AsyncHttpTestCase? What is the best pattern for doing this?
Here's tests.py
import urllib2
from tornado.httpclient import AsyncHTTPClient
import tornado.testing
from tornado.testing import AsyncTestCase, AsyncHTTPTestCase
from app import DebugApp
class TestDebug(AsyncHTTPTestCase):
def get_app(self):
return DebugApp()
def test_foo(self):
response = self.fetch('/foo')
print response.body
assert response.body == 'derp'
def test_foo_from_urllib(self):
response = urllib2.urlopen(self.get_url('/foo'), None, 2)
print response
assert response.body == 'derp'
def runTest(self):
pass
and app.py
import tornado.httpserver
import tornado.ioloop
import tornado.web
from tornado.options import options
class FooHandler(tornado.web.RequestHandler):
def get(self):
self.write("derp")
url_patterns = [
(r"/foo", FooHandler),
]
class DebugApp(tornado.web.Application):
def __init__(self):
tornado.web.Application.__init__(self, url_patterns, debug=True, xsrf_cookies=False)
def main():
app = DebugApp()
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(6006)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
and runtest.py
#!/usr/bin/env python
import unittest
from os import path
import sys
import tornado.testing
PROJECT_PATH = path.dirname(path.abspath(__file__))
sys.path.append(PROJECT_PATH)
def all():
suite = unittest.defaultTestLoader.discover('./', 'tests.py', path.dirname(path.abspath(__file__)))
print suite
return suite
if __name__ == '__main__':
# Print a nice message so that we can differentiate between test runs
print ''
print '%s %s' % ('Debug app', '0.1.0')
print '\033[92m' + '-------------- Running Test Suite --------------' + '\033[0m'
print ''
tornado.testing.main()
The problem is that the IOLoop is not running when you call urlopen (and it cannot be, because urlopen is a blocking function). You must run the IOLoop (with either #gen_test, self.wait(), or indirectly via methods like self.fetch()) for the server to respond, and you can only interact with it via non-blocking functions (or if you must use blocking functions like urlopen, run them in a separate thread).