Best Python code snippet using pytest
main.py
Source: main.py
1# IMPORTANT - DO NOT RENAME COLUMN TITLES ON AIRTABLE ~ code will break!! 2import os3import requests4from dotenv import load_dotenv5load_dotenv(".env")6# All id/key/name info is in .env file, but just leaving it in here as comments7# AIRTABLE_BASE_ID= 'apph59FEIK9tFsbeP'8AIRTABLE_BASE_ID = os.environ.get("AIRTABLE_BASE_ID")9# AIRTABLE_API_KEY = 'keyMvIhftiZpciEpD'10AIRTABLE_API_KEY = os.environ.get("AIRTABLE_API_KEY")11# AIRTABLE_TABLE_NAME = 'table1'12AIRTABLE_TABLE_NAME = os.environ.get("AIRTABLE_TABLE_NAME")13# print(os.environ.get("AIRTABLE_API_KEY"))14endpoint= f'https://api.airtable.com/v0/{AIRTABLE_BASE_ID}/{AIRTABLE_TABLE_NAME}'15# trying to see if you can manually enter data - this setup works!16# python requests headers17# headers = {18# "Authorization": f"Bearer {AIRTABLE_API_KEY}",19# "Content-Type": "application/json"20# }21# data = {22# "records": [23# {24# "fields": {25# "Name": "test",26# "Link": "test",27# "Approx_Start_Date": "2021-06-01",28# "Funding_Sources": "Government",29# "Approx_End_Date": "2021-06-01",30# "Funders": "test",31# "End_Users": "test",32# "Use_Case": "test",33# "Death_Cause": "Funding",34# "Post_Mortem": "Donated",35# "Successor_Projects": [36# "recmn3SCh7CRkAMy9"37# ],38# "Life_Proof": "test"39# }40# },41# {42# "fields": {43# "Name": "test2",44# "Link": "test2",45# "Approx_Start_Date": "2021-06-02",46# "Funding_Sources": "Donations",47# "Approx_End_Date": "2021-06-02",48# "Funders": "test2",49# "End_Users": "test2",50# "Use_Case": "test2",51# "Death_Cause": "Adoption",52# "Post_Mortem": "Closed",53# "Successor_Projects": [54# "recyBax45uBSEj0Z3"55# ],56# "Life_Proof": "test2"57# }58# }59# ]60# }61# HTTP Methods62# "create" -> POST, "update" -> PATCH, "delete" -> DELETE63# r = requests.post(endpoint, json=data, headers=headers)64# print(r.json())65# print(r.status_code)66# if this results in 200, yay! if it's 401, there might be error with API Key67# look at HTTP status codes for more help68# Automating the process using a method - method doesn't work yet69def add_record(Name = None, Link = "", Approx_Start_Date = "", Approx_End_Date = "", Funding_Sources = "", Funders = "", End_Users = "", Use_Case = "", Death_Cause = "", Post_Mortem = "", Successor_Projects = "", Life_Proof = ""):70 if Name is None:71 return72 headers = {73 "Authorization": f"Bearer {AIRTABLE_API_KEY}",74 "Content-Type": "application/json"75 }76 data = {77 "records": [78 {79 "fields": {80 "Name": name,81 "Link": link,82 "Approx_Start_Date": approx_start_date,83 "Funding_Sources": funding_sources,84 "Approx_End_Date": approx_end_date,85 "Funders": funders,86 "End_Users": end_users,87 "Use_Case": use_case,88 "Death_Cause": death_cause,89 "Post_Mortem": post_mortem,90 "Successor_Projects": successor_projects, 91 "Life_Proof": life_proof92 }93 } 94 ]95 }96 r = requests.post(endpoint, json=data, headers=headers)97 return r.status_code == 200 #checks to see if everything got added properly98# making it more user friendly :)99name = input("What is the name of the organization?\n")100link = input("Org's website link?\n")101approx_start_date = input("Org's approximate start date?\n")102funding_sources = input("Org's funding sources?\n")103approx_end_date = input("Org's approximate end date?\n")104funders = input("Org's funders?\n")105end_users = input("Org's end users?\n")106use_case = input("Org's use cases?\n")107death_cause = input("Org's death cause?\n")108post_mortem = input("Org's post mortem?\n")109successor_projects = input("Org's successor projects?\n")110life_proof = input("Org's life proof?\n")111# function call with hard-coded manual inputs (uncomment to test):112# add_record(Name = "blah", Link = "blah", Approx_Start_Date = "blah", Approx_End_Date = "blah", Funding_Sources = "blah", Funders = "blah", End_Users = "blah", Use_Case = "blah", Death_Cause = "blah", Post_Mortem = "blah", Successor_Projects = "blah", Life_Proof = "blah")113# something is wrong with this add_record method, Error: Line 93, NameError: name 'name' is not defined114# this has to be fixed, also data types have to be considered for some of the variables - not all are stings115# function call with user inputs (lines 113 - 124) (uncomment to test):116# add_record(Name = name, Link = link, Approx_Start_Date = approx_start_date, Approx_End_Date = approx_end_date, Funding_Sources = funding_sources, Funders = funders, End_Users = end_users, Use_Case = use_case, Death_Cause = death_cause, Post_Mortem = post_mortem, Successor_Projects = successor_projects, Life_Proof = life_proof)117# same issue here118 ...
pdb.py
Source: pdb.py
...50 for line in str(excrepr).split("\n"):51 sys.stderr.write("INTERNALERROR> %s\n" %line)52 sys.stderr.flush()53 tb = _postmortem_traceback(excinfo)54 post_mortem(tb)55def _enter_pdb(node, excinfo, rep):56 # XXX we re-use the TerminalReporter's terminalwriter57 # because this seems to avoid some encoding related troubles58 # for not completely clear reasons.59 tw = node.config.pluginmanager.getplugin("terminalreporter")._tw60 tw.line()61 tw.sep(">", "traceback")62 rep.toterminal(tw)63 tw.sep(">", "entering PDB")64 tb = _postmortem_traceback(excinfo)65 post_mortem(tb)66 rep._pdbshown = True67 return rep68def _postmortem_traceback(excinfo):69 # A doctest.UnexpectedException is not useful for post_mortem.70 # Use the underlying exception instead:71 from doctest import UnexpectedException72 if isinstance(excinfo.value, UnexpectedException):73 return excinfo.value.exc_info[2]74 else:75 return excinfo._excinfo[2]76def _find_last_non_hidden_frame(stack):77 i = max(0, len(stack) - 1)78 while i and stack[i][0].f_locals.get("__tracebackhide__", False):79 i -= 180 return i81def post_mortem(t):82 class Pdb(pdb.Pdb):83 def get_stack(self, f, t):84 stack, i = pdb.Pdb.get_stack(self, f, t)85 if f is None:86 i = _find_last_non_hidden_frame(stack)87 return stack, i88 p = Pdb()89 p.reset()...
debug_utils.py
Source: debug_utils.py
...28 >> with debug_on(AssertionError):29 .. assert False30 """31 pass32 def post_mortem(self):33 try:34 traceback.print_exc()35 tb = sys.exc_info()[2]36 if self.force_ipdb or is_ipython():37 # https://github.com/gotcha/ipdb/blob/master/ipdb/__main__.py38 from IPython.terminal.interactiveshell import (39 TerminalInteractiveShell40 )41 p = TerminalInteractiveShell().debugger_cls()42 p.botframe = sys._getframe().f_back # I do not know why this43 # is nessesary, but without this hack it does not work44 p.interaction(None, tb)45 else:46 pdb.post_mortem(tb)47 except Exception as e:48 print('#'*40)49 print('debug_on does not alwais work with sacred. '50 'Use -D for sacred applications')51 print('#'*40)52 raise e53 def __exit__(self, exctype, excinst, exctb):54 ret = super().__exit__(exctype, excinst, exctb)55 if ret is True:56 self.post_mortem()57 return False58 else:59 return ret60 def __call__(self, f):61 """62 >> @debug_on(AssertionError)63 .. def foo():64 .. assert False65 >> foo()66 """67 # https://stackoverflow.com/a/12690039/576693468 @functools.wraps(f)69 def wrapper(*args, **kwargs):70 try:71 return f(*args, **kwargs)72 except self._exceptions:73 # traceback.print_exc()74 # pdb.post_mortem(sys.exc_info()[2])75 self.post_mortem()76 raise...
test_publisherhttpserver.py
Source: test_publisherhttpserver.py
...6 def test_application_calls_debugger(self):7 from zope.server.http import wsgihttpserver8 import six9 pm_called = []10 def post_mortem(exc_info):11 pm_called.append(True)12 six.reraise(*exc_info)13 class PublishException(Exception):14 pass15 def publish(*args, **kwargs):16 self.assertFalse(kwargs.get('handle_errors', True))17 raise PublishException()18 orig_post = wsgihttpserver.PMDBWSGIHTTPServer.post_mortem19 orig_publish = publisherhttpserver._publish20 wsgihttpserver.PMDBWSGIHTTPServer.post_mortem = staticmethod(21 post_mortem)22 publisherhttpserver._publish = publish23 class Request(object):24 def __init__(self, *args):...
Can I make the pytest doctest module ignore a file?
Python2: Get longest Common Prefix path
How do I check if a string represents a number (float or int)?
How to pass multiple arguments in pytest using command line?
How to link PyCharm with PySpark?
Python order Dict with a pre-defined order
Is there a way to specify which pytest tests to run from a file?
What are metaclasses in Python?
Closing a file so I can delete it on Windows in Python?
Eclipse (with Pydev) keeps throwing SyntaxError
As MasterAndrey has mentioned, pytest_ignore_collect
should do the trick. Important to note that you should put conftest.py
to root folder (the one you run tests from).
Example:
import sys
def pytest_ignore_collect(path):
if sys.version_info[0] > 2:
if str(path).endswith("__py2.py"):
return True
else:
if str(path).endswith("__py3.py"):
return True
Since pytest v4.3.0 there is also --ignore-glob
flag which allows to ignore by pattern. Example:
pytest --doctest-modules --ignore-glob="*__py3.py" dir/
Check out the latest blogs from LambdaTest on this topic:
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on WebDriverIO Tutorial.
It has been around a year since we went live with the first iteration of LambdaTest Platform. We started off our product offering manual cross browser testing solutions and kept expanding our platform. We were asked many feature requests, and we implemented quite a lot of them. However, the biggest demand was to bring automation testing to the platform. Today we deliver on this feature.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium Python Tutorial.
There are many software products that are built for a global audience. In my tenure as a developer, I have worked on multiple web (website or web app) projects that supported different languages. Though the Selenium framework was used for automation testing, using Internationalization in Selenium WebDriver Tutorial posed a huge challenge.
Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.
Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.
https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP
Get 100 minutes of automation test minutes FREE!!