Best Python code snippet using autotest_python
__init__.py
Source:__init__.py  
1import streamlit as st2from contextlib import contextmanager3from urllib.parse import urljoin, urlencode4import pandas as pd5import requests6import traceback7_BASE_URL = "https://discuss.streamlit.io"8_TTL = 1 * 60 * 60  # 1 hour9_ALLOWED_SORTS = ["latest", "likes", "views", "latest_topic"]10_ALLOWED_STATUSES = [11    "open",12    "closed",13    "public",14    "archived",15    "noreplies",16    "single_user",17    "solved",18    "unsolved",19]20@st.experimental_memo(ttl=_TTL, show_spinner=False)21def _fetch(path, **query):22    url = urljoin(_BASE_URL, path)23    if query:24        query_str = urlencode(query)25        url = "%s?%s" % (url, query_str)26    return requests.get(url)27@st.experimental_memo(ttl=_TTL, show_spinner=False)28def _fetch_search(q="", page=0):29    resp = _fetch("search.json", q=q, page=page)30    data = resp.json()31    if "topics" not in data:32        return None33    search_results = pd.DataFrame(data["topics"])34    search_results["created_at"] = pd.to_datetime(search_results["created_at"])35    search_results["last_posted_at"] = pd.to_datetime(search_results["last_posted_at"])36    return search_results37@st.experimental_memo(ttl=_TTL, show_spinner=False)38def _get_search_results_as_table(table):39    table = table.copy()40    table = table.drop_duplicates(subset=["id"])41    table["created_at"] = pd.to_datetime(table["created_at"])42    table["last_posted_at"] = pd.to_datetime(table["last_posted_at"])43    return table[44        [45            "title",46            "created_at",47            "last_posted_at",48            "id",49            "posts_count",50            "reply_count",51            "highest_post_number",52            "category_id",53            "has_accepted_answer",54        ]55    ].reset_index(drop=True)56@st.experimental_memo(ttl=_TTL, show_spinner=False)57def _fetch_all_topic_pages(q=""):58    posts_list = []59    page = 060    while True:61        batched_posts = _fetch_search(q=q, page=page)62        if batched_posts is None:63            break64        posts_list.append(batched_posts)65        page += 166    posts = pd.concat(posts_list)67    posts_table = _get_search_results_as_table(posts)68    return posts_table69def _get_data(etype, str_exception, top, criteria, sortby, status):70    # If the criteria is 'broad', search for topics with only71    # the exception name. e.g. 'ValueError'72    query = etype73    # Search for topics with the exception name and the exception74    # message. e.g. 'ValueError: invalid literal for int() with base 10: 'foo'75    if criteria == "narrow":76        query = query + ": " + str(str_exception)77    # TODO: Improve above search logic78    # See: https://docs.discourse.org/#tag/Search79    if sortby in _ALLOWED_SORTS:80        query = query + f" order:{sortby}"81    if status in _ALLOWED_STATUSES:82        query = query + f" status:{status}"83    try:84        result = _fetch_all_topic_pages(q=query)85    except Exception as e:86        return st.error(87            "[streamlit-forum] No topics found. Try setting criteria to 'broad'"88        )89    result = result.head(top)90    return result91def _format_result(result):92    links = []93    for topic_id, title, status in result[["id", "title", "has_accepted_answer"]].values:94        topic_url = _BASE_URL + "/t/" + str(topic_id)95        topic_url = f"- [{title}]({topic_url})"96        if status:97            topic_url += " [â
 Solved]"98        links.append(topic_url)99    return "\n".join(links)100@contextmanager101def forum(top=5, criteria="broad", sortby="relevance", status="any"):102    """Use in a `with` block to execute some code and display103    topics from Streamlit's community forum related to any exception.104    Parameters105    ----------106    top : int107        Number of topics to display. Default is 5.108    criteria : str109        Search criteria. Either 'broad' or 'narrow'. Default is 'broad'.110    sortby : str111        Sort criteria. Either 'relevance', 'views', 'likes', or 'latest_topic'.112        Default is 'relevance'.113    status : str114        Status of forum topic. Either 'open', 'closed', 'public', 'archived',115        'noreplies', 'single_user', 'solved', 'unsolved'. Default is 'any'.116    Examples117    --------118    >>> import streamlit as st119    >>> from streamlit_forum import forum120    ...121    >>> with forum():122    >>>     import streamlit as st123    >>>     # Your code that may raise an exception here. E.g.124    >>>     0/0125    """126    try:127        # Run the code in the `with` block.128        yield129    except Exception as e:130        etype = type(e).__name__  # e.g. 'ValueError', 'TypeError'131        # Get traceback from exception.132        # Filter out the first frame which displays this function's 'yield' statement.133        etraceback = traceback.format_tb(e.__traceback__)[1:]134        # Flatten traceback frame messages.135        # Remove the first two spaces of each line to fix markdown code block indentation.136        etraceback = (line[2:] for frame in etraceback for line in frame.splitlines())137        etraceback = "\n".join(etraceback)138        # Retrieve forum links.139        forum_links = _get_data(etype, e, top, criteria, sortby, status)140        forum_links = _format_result(forum_links)141        # Generate each part of our error message.142        msg_error = f"**{etype}**: {e}"143        msg_links = f"Related forum topics:\n\n{forum_links}"144        msg_traceback = f"Traceback:\n\n```\n{etraceback}\n```"145        # Build the final message.146        msg = "\n\n".join((msg_error, msg_links, msg_traceback))147        # Display it148        st.error(msg)149        with st.expander("Stuck ?"):150            st.markdown("""151            Don't see a relevant topic? Try changing the criteria to `narrow` 152            or tweaking the other parameters.153            """)154            if st.checkbox("View available parameters ð ï¸"):155                st.help(forum)156    157            if st.checkbox("Read Streamlit's docs ð"):158                st.components.v1.iframe(159                    "https://docs.streamlit.io/knowledge-base/", 160                    height=500,161                    scrolling=True162                )163            if st.button("Still need help? ð¤"):164                st.markdown("""165                If you still need help, please post on the [community forum](https://discuss.streamlit.io/). 166                We love to hear your questions, ideas, and help you work through your bugs â stop by today! ð167                """)168        # Stop the script...tap-unittest
Source:tap-unittest  
1#!/usr/bin/env python32#3# This is a TAP compiler for python unittest4#5# It hooks into python's standard unittest module, and produces TAP output.6#7# This produces the Test Anything Protocol (ie: TAP)8# https://metacpan.org/pod/release/PETDANCE/Test-Harness-2.64/lib/Test/Harness/TAP.pod9#10# Based on code from here:11# https://github.com/vit1251/unittest-tap-reporting12# 13import argparse14import imp15import os16import sys17import time18import traceback19import unittest20def write_line(format, *args):21    sys.stdout.write(format % args)22    sys.stdout.write("\n")23    sys.stdout.flush()24class TAPTestResult(unittest.result.TestResult):25    def __init__(self):26        unittest.result.TestResult.__init__(self)27        self.number = 028    def addSuccess(self, test):29        self.number += 130        write_line("ok %d %s", self.number, test.id())31    def addSkip(self, test, reason):32        self.number += 133        write_line("not ok %d # skip %s", self.number, test.id())34        write_line("# %s", reason)35    def addError(self, test, exc):36        (etype, evalue, etraceback) = exc37        traceback.print_exception(etype, evalue, etraceback, file=sys.stderr)38        self.number += 139        write_line("not ok %d %s", self.number, test.id())40    def addFailure(self, test, err):41        (etype, evalue, etraceback) = exc42        traceback.print_exception(etype, evalue, etraceback, limit=1, file=sys.stderr)43        self.number += 144        write_line("not ok %d %s", self.number, test.id())45class TAPTestRunner(object):46    def __init__(self):47        pass48    def run(self, test):49        write_line("1..%d", test.countTestCases())50        result = TAPTestResult()51        startTestRun = getattr(result, 'startTestRun', lambda : None)52        startTestRun()53        try:54            test(result)55        finally:56            stopTestRun = getattr(result, 'stopTestRun', lambda : None)57            stopTestRun()58        return result59def main(argv):60    parser = argparse.ArgumentParser(description='Python unittest TAP driver')61    parser.add_argument('module', nargs=1,62                        help="A unittest test module to run")63    args = parser.parse_args(argv[1:])64    (name, ext) = os.path.splitext(os.path.basename(args.module[0]))65    module = imp.load_source(name, args.module[0])66    loader = unittest.TestLoader()67    tests = loader.loadTestsFromModule(module)68    runner = TAPTestRunner()69    runner.run(tests)70if __name__ == "__main__":...test_errors.py
Source:test_errors.py  
1#!/usr/bin/env python2import pytest3from circuits import Event, Component4class test(Event):5    """test Event"""6class App(Component):7    def __init__(self):8        super(App, self).__init__()9        self.etype = None10        self.evalue = None11        self.etraceback = None12        self.handler = None13        self.fevent = None14    def test(self):15        return x  # NOQA16    def exception(self, etype, evalue, etraceback, handler=None, fevent=None):17        self.etype = etype18        self.evalue = evalue19        self.etraceback = etraceback20        self.handler = handler21        self.fevent = fevent22def reraise(e):23    raise e24@pytest.fixture25def app(request, manager, watcher):26    app = App().register(manager)27    watcher.wait("registered")28    def finalizer():29        app.unregister()30    request.addfinalizer(finalizer)31    return app32def test_main(app, watcher):33    e = test()34    app.fire(e)35    watcher.wait("exception")36    assert app.etype == NameError37    pytest.raises(NameError, lambda e: reraise(e), app.evalue)38    assert isinstance(app.etraceback, list)39    assert app.handler == app.test...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
