I started learning playwright and from documentation (https://playwright.dev/python/docs/intro) tried to to run the following sample code:
import re
from playwright.sync_api import Page, expect
def test_pp(page: Page):
page.goto("https://playwright.dev/")
# Expect a title "to contain" a substring.
expect(page).to_have_title(re.compile("Playwright"))
# create a locator
get_started = page.locator("text=Get Started")
# Expect an attribute "to be strictly equal" to the value.
expect(get_started).to_have_attribute("href", "/docs/intro")
# Click the get started link.
get_started.click()
# Expects the URL to contain intro.
expect(page).to_have_url(re.compile(".*intro"))
While running using command pytest, throwing following error:
file D:\play_wright\test\test_sample.py, line 5
def test_pp(page: Page):
E fixture 'page' not found
> available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
> use 'pytest --fixtures [testpath]' for help on them.
D:\play_wright\test\test_sample.py:5
pytest-playwright module (0.3.0) is installed. confirmed with pip list command
Restarted Widows Machine
playwright version - 1.27.1
pytest - 6.2.1 (tried with 7.* as well)
Still getting the issue. please help.
I had the same issue as well. I ran this command, then restarted my command line and it started working.
playwright install-deps
I hope this helps.
Try the following:
py.test test_.py
Related
I have a small Python3-script like this:
import speedtest
# Speedtest
test = speedtest.Speedtest() # <--- line 4
test.get_servers()
best = test.get_best_server()
print(f"Found: {best['host']} located in {best['country']}")
The first time I run it, it works and everything is fine; it outputs:
Found: speedtest.witcom.cloud:8080 located in Germany
Happy days.
The second time (and subsequel times) that I run the script, I get this error:
Traceback (most recent call last):
File "/Users/zeth/Code/pinger/pinger.py", line 4, in <module>
test = speedtest.Speedtest()
File "/usr/local/lib/python3.9/site-packages/speedtest.py", line 1095, in __init__
self.get_config()
File "/usr/local/lib/python3.9/site-packages/speedtest.py", line 1127, in get_config
raise ConfigRetrievalError(e)
speedtest.ConfigRetrievalError: HTTP Error 403: Forbidden
When Googling around, I saw that I could also call this module straight from the command line, but just running this:
$ speedtest-cli
That gives me the same kind of error:
Retrieving speedtest.net configuration...
Cannot retrieve speedtest configuration
ERROR: HTTP Error 403: Forbidden
But if I run the direct cli-command: speedtest-cli --secure ( docs for the --secure-flag ), then it goes through and outputs this:
Retrieving speedtest.net configuration...
Testing from Deutsche Telekom AG (212.185.228.168)...
Retrieving speedtest.net server list...
Selecting best server based on ping...
Hosted by hotspot.koeln (Cologne) [3.44 km]: 28.805 ms
Testing download speed................................................................................
Download: 30.01 Mbit/s
Testing upload speed......................................................................................................
Upload: 8.68 Mbit/s
The question
I can't figure out how to change this Python-line: test = speedtest.Speedtest() to use a --secure-flag (nor via HTTPS).
The documentation for speedtest-cli is scarce.
Other attempts
I found this solution here: Python Speedtest facing problems with certification _ssl.c:1056, that suggests manually approving the certificates.
But in this directory: /Volumes/Macintosh HD/Applications/ I don't have anything called Python3.9. I have python3.9 installed via Brew. And I'm on a Mac.
I could do this:
test = speedtest.Speedtest(secure=True)
I looked into the source code myself, in this directory:
vim /usr/local/lib/python3.9/site-packages/speedtest.py
Where I would see the function was defined like this:
class Speedtest(object):
"""Class for performing standard speedtest.net testing operations"""
def __init__(self, config=None, source_address=None, timeout=10,
secure=False, shutdown_event=None):
self.config = {}
self._source_address = source_address
self._timeout = timeout
self._opener = build_opener(source_address, timeout)
self._secure = secure
...
...
...
I am trying to use the pytester fixture, to create some files in the test directory, but I get the following error:
def test_something(pytester):
E fixture 'pytester' not found
> available fixtures: _configure_application, _monkeypatch_response_class, _push_request_context, accept_any, accept_json, accept_jsonp, accept_mimetype, cache, capfd, capfdbinary, caplog, capsys, capsysbinary, class_mocker, client, client_class, config, cov, doctest_namespace, live_server, mock_sparql_endpoint, mocker, module_mocker, monkeypatch, no_cover, package_mocker, pytestconfig, quotation_access_db_columns, quotation_access_db_path, record_property, record_testsuite_property, record_xml_attribute, recwarn, request_ctx, session_mocker, sparql_query1, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
> use 'pytest --fixtures [testpath]' for help on them.
The code I am trying to run, to create some python files in below, taken from the pytester documentation:
def test_something(pytester):
# Initial file is created test_something.py.
pytester.makepyfile("foobar")
# To create multiple files, pass kwargs accordingly.
pytester.makepyfile(custom="foobar")
# At this point, both 'test_something.py' & 'custom.py' exist in the test directory.
How can I use the pytester fixture to create some files in the test directory?
The link for the pytester documentation:
https://docs.pytest.org/en/6.2.x/reference.html#pytest.Pytester.path
Try adding this line in conftest.py (or in your test file) as documented.
pytest_plugins = "pytester"
Or if you already have any existing one, just make it a list:
pytest_plugins = [
...
"pytester",
]
Also, make sure that your version of pytest is >= 6.2 as it is the requirement based on the docs.
I am getting this error in pip search while studying python.
The picture is an error when I pip search. Can you tell me how to fix it?
$ pip search pdbx
ERROR: Exception:
Traceback (most recent call last):
File "*/lib/python3.7/site-packages/pip/_internal/cli/base_command.py", line 224, in _main
status = self.run(options, args)
File "*/lib/python3.7/site-packages/pip/_internal/commands/search.py", line 62, in run
pypi_hits = self.search(query, options)
File "*/lib/python3.7/site-packages/pip/_internal/commands/search.py", line 82, in search
hits = pypi.search({'name': query, 'summary': query}, 'or')
File "/usr/lib/python3.7/xmlrpc/client.py", line 1112, in __call__
return self.__send(self.__name, args)
File "/usr/lib/python3.7/xmlrpc/client.py", line 1452, in __request
verbose=self.__verbose
File "*/lib/python3.7/site-packages/pip/_internal/network/xmlrpc.py", line 46, in request
return self.parse_response(response.raw)
File "/usr/lib/python3.7/xmlrpc/client.py", line 1342, in parse_response
return u.close()
File "/usr/lib/python3.7/xmlrpc/client.py", line 656, in close
raise Fault(**self._stack[0])
xmlrpc.client.Fault: <Fault -32500: 'RuntimeError: This API has been temporarily disabled due to unmanageable load and will be deprecated in the near future. Please use the Simple or JSON API instead.'>
The pip search command queries PyPI's servers, and PyPI's maintainers have explained that the API endpoint that the pip search command queries is very resource intensive and too expensive for them to always keep open to the public. Consequently they sometimes throttle access and are actually planning to remove it completely soon.
See this GitHub issues thread ...
The solution I am using for now is to pip install pip-search (a utility created by GitHub user #victorgarric).
So, instead of 'pip search', I use pip_search. Definitely beats searching PyPI via a web browser
Follow the suggestion from JRK at the discussion at github (last comment) the search command is temporarily disabled, use your browser to search for packages meanwhile:
Check the thread on github and give him a thumb up ;)
search on website, https://pypi.org/,
then install the package you wanted
The error says
Please use the Simple or JSON API instead
You can try pypi-simple to query the pip repository
https://pypi.org/project/pypi-simple/
It gives an example too, I tried to use it here:
pypi-simple version 0.8.0 DistributionPackage' object has no attribute 'get_digest':
!/usr/bin/env python3
-*- coding: utf-8 -*-
"""
Created on Thu Nov 11 17:40:03 2020
#author: Pietro
"""
from pypi_simple import PyPISimple
def simple():
package=input('\npackage to be checked ')
try:
with PyPISimple() as client:
requests_page = client.get_project_page(package)
except:
print("\n SOMETHING WENT WRONG !!!!! \n\n",
"CHECK INTERNET CONNECTION OR DON'T KNOW WHAT HAPPENED !!!\n")
pkg = requests_page.packages[0]
print(pkg)
print(type(pkg))
print('\n',pkg,'\n')
print('\n'+pkg.filename+'\n')
print('\n'+pkg.url+'\n')
print('\n'+pkg.project+'\n')
print('\n'+pkg.version+'\n')
print('\n'+pkg.package_type+'\n')
#print('\n'+pkg.get_digest()+'\n','ENDs HERE !!!!') #wasnt working
if __name__ == '__main__':
simple()
got -4 so far for this answer don't know why , figureout I can try to check for a package with:
# package_name = input('insert package name : ')
package_name = 'numpy'
import requests
url = ('https://pypi.org/pypi/'+package_name+'/json')
r = requests.get(url)
try:
data = r.json()
for i in data:
if i == 'info':
print('ok')
for j in data[i]:
if j == 'name':
print((data[i])[j])
print([k for k in (data['releases'])])
except:
print('something went south !!!!!!!!!!')
I have created a simple HTTP trigger-based azure function in python which is calling another python script to create a sample file in azure data lake gen 1. My solution structure is given below: -
Requirements.txt contains the following imports: -
azure-functions
azure-mgmt-resource
azure-mgmt-datalake-store
azure-datalake-store
init.py
import logging, os, sys
import azure.functions as func
import json
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
name = req.params.get('name')
if not name:
try:
req_body = req.get_json()
except ValueError:
pass
else:
name = req_body.get('name')
if name:
full_path_to_script = os.path.join(os.path.dirname( __file__ ) + '/Test.py')
logging.info(f"Path: - {full_path_to_script}")
os.system(f"python {full_path_to_script}")
return func.HttpResponse(f"Hello {name}!")
else:
return func.HttpResponse(
"Please pass a name on the query string or in the request body",
status_code=400
)
Test.py
import json
from azure.datalake.store import core, lib, multithread
directoryId = ''
applicationKey = ''
applicationId = ''
adlsCredentials = lib.auth(tenant_id = directoryId, client_secret = applicationKey, client_id = applicationId)
adlsClient = core.AzureDLFileSystem(adlsCredentials, store_name = '')
with adlsClient.open('stage1/largeFiles/TestFile.json', 'rb') as input_file:
data = json.load(input_file)
with adlsClient.open('stage1/largeFiles/Result.json', 'wb') as responseFile:
responseFile.write(data)
Test.py is failing with an error that no module found azure.datalake.store
Why other required modules are not working for Test.py since it is inside the same directory?
pip freeze output: -
adal==1.2.2
azure-common==1.1.23
azure-datalake-store==0.0.48
azure-functions==1.0.4
azure-mgmt-datalake-nspkg==3.0.1
azure-mgmt-datalake-store==0.5.0
azure-mgmt-nspkg==3.0.2
azure-mgmt-resource==6.0.0
azure-nspkg==3.0.2
certifi==2019.9.11
cffi==1.13.2
chardet==3.0.4
cryptography==2.8
idna==2.8
isodate==0.6.0
msrest==0.6.10
msrestazure==0.6.2
oauthlib==3.1.0
pycparser==2.19
PyJWT==1.7.1
python-dateutil==2.8.1
requests==2.22.0
requests-oauthlib==1.3.0
six==1.13.0
urllib3==1.25.6
Problem
os.system(f"python {full_path_to_script}") from your functions project is causing the issue.
Azure Functions Runtime sets up the environment, along with modifying process level variables like os.path so that your function can load any dependencies you may have. When you create a sub-process like that, not all information will flow through. Additionally, you will face issues with logging -- logs from test.py would not show up properly unless explicitly handled.
Importing works locally because you have all your requirements.txt modules installed and available to test.py. This is not the case in Azure. After remotely building as part of publish, your modules are included as part of your code package published. It's not "installed" globally in the Azure environment per se.
Solution
You shouldn't have to run your script like that. In the example above, you could import your test.py from your __init__.py file, and that should behave like it was called python test.py (at least in the case above). Is there a reason you'd want to do python test.py in a sub-process over importing it?
Here's the official guide on how you'd want to structure your app to import shared code -- https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-python#folder-structure
Side-Note
I think once you get through the import issue, you may also face problems with adlsClient.open('stage1/largeFiles/TestFile.json', 'rb'). We recommend following the developer guide above to structure your project and using __file__ to get the absolute path (reference).
For example --
import pathlib
with open(pathlib.Path(__file__).parent / 'stage1' / 'largeFiles' /' TestFile.json'):
....
Now, if you really want to make os.system(f"python {full_path_to_script}") work, we have workarounds to the import issue. But, I'd rather not recommend such approach unless you have a really compelling need for it. :)
I'm trying to write a CMS content migration script that will create our pages for django-cms. However even with the default install of Django-cms, Django-treebeard keeps raising exceptions and it's not clear to me why.
For example, when this line is executed:
api.create_page(title="Hello world",
language='en',
parent=None)
My script always fails here (line 307-8) in mp_tree.py (v 4.1.0) from treebeard:
if newobj.pk:
raise NodeAlreadySaved("Attempted to add a tree node that is "\
"already in the database")
Does anyone have a very simple example on how to use the cms.api.create_page() method?
http://docs.django-cms.org/en/release-3.4.x/reference/api_references.html?highlight=create_page#cms.api.create_page
Pip freeze shows these versions:
aldryn-apphooks-config==0.2.7
aldryn-boilerplates==0.7.4
aldryn-common==1.0.4
aldryn-faq==1.2.2
aldryn-forms==2.1.3
aldryn-reversion==1.0.9
aldryn-search==0.3.0
aldryn-translation-tools==0.2.1
appdirs==1.4.3
boto==2.46.1
boto3==1.4.4
botocore==1.5.26
cmsplugin-filer==1.1.3
contextlib2==0.5.4
cssselect==1.0.0
cssutils==1.0.1
dj-database-url==0.4.1
Django==1.8.17
django-absolute==0.3
django-admin-sortable==2.0.21
django-admin-sortable2==0.6.6
django-appconf==1.0.2
django-appdata==0.1.6
django-cas-ng==3.5.6
django-classy-tags==0.8.0
django-cms==3.4.1
django-cors-headers==2.0.2
django-debug-toolbar==1.7
django-emailit==0.2.2
django-environ==0.4.1
django-extensions==1.7.7
django-filer==1.2.5
django-formtools==1.0
django-haystack==2.5.1
django-mptt==0.8.6
django-parler==1.6.5
django-polymorphic==0.8.1
django-reversion==1.10.2
django-sekizai==0.10.0
Django-Select2==4.3.2
django-simple-captcha==0.5.3
django-sizefield==0.9.1
django-sortedm2m==1.3.2
django-spurl==0.6.4
django-standard-form==1.1.1
-e git+https://github.com/jschneier/django-storages.git#043b91b10ebfebdf7e752d743ae630f0daa2c4f4#egg=django_storages
django-storages-redux==1.3.2
django-tablib==3.1.2
django-taggit==0.21.3
django-treebeard==4.1.0
djangocms-admin-style==1.2.6.2
djangocms-attributes-field==0.1.2
djangocms-column==1.7.0
djangocms-googlemap==1.0.1
djangocms-installer==0.9.3
djangocms-link==2.0.3
djangocms-rest-api==0.2.0
djangocms-snippet==1.9.2
djangocms-style==2.0.1
djangocms-text-ckeditor==3.3.1
djangocms-video==2.0.3
djangorestframework==3.4.7
docutils==0.13.1
easy-thumbnails==2.3
google-auth==0.8.0
google-auth-httplib2==0.0.2
google-cloud-core==0.23.1
google-cloud-storage==0.23.1
googleapis-common-protos==1.5.2
html5lib==0.9999999
httplib2==0.10.3
jmespath==0.9.0
lxml==3.7.0
mysqlclient==1.3.10
packaging==16.8
Pillow==3.4.2
premailer==3.0.1
protobuf==3.2.0
psycopg2==2.6.2
pyasn1==0.2.3
pyasn1-modules==0.0.8
pyparsing==2.2.0
python-cas==1.2.0
python-dateutil==2.6.0
python-slugify==1.2.0
pytz==2016.10
raven==6.0.0
requests==2.12.3
rsa==3.4.2
s3transfer==0.1.10
six==1.10.0
sqlparse==0.2.3
tablib==0.11.3
tzlocal==1.3
Unidecode==0.4.19
URLObject==2.4.2
YURL==0.13
So thanks to #dentemm and #paulo I was able to get this running in a Python shell as follows:
>>> from cms import constants
>>> from cms.constants import TEMPLATE_INHERITANCE_MAGIC
>>> from cms import api
>>> api.create_page(title="Hello World4",language='en',template=TEMPLATE_INHERITANCE_MAGIC,parent=None)
<cms.models.pagemodel.Page object at 0x102b674e0>
It was failing because I was not including the 'template' argument and the necessary imports.
I am unsure if it's the cause for your problems, but there is an error in your api.create_page() code above: parent=None shouldn't have spaces.