code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
class cls(object):
def __init__(self, x):
self.x = x
def one(x):
return x+3
def nottwo():
pass
| Python |
import py
from py.__.initpkg import initpkg
initpkg(__name__,
description="test package",
exportdefs = {
'pak.mod.one': ('./pak/mod.py', 'one'),
'pak.mod.two': ('./pak/mod.py', 'nottwo'),
'notpak.notmod.notclass': ('./pak/mod.py', 'cls'),
'somenamespace': ('./pak/so... | Python |
""" magic - some operations which helps to extend PDB with some magic data.
Actually there is only explicit tracking of data, might be extended to
automatic at some point.
"""
# some magic stuff to have singleton of DocStorage, but initialised explicitely
import weakref
import py
from py.__.apigen.tracer.docstorage... | Python |
import py
html = py.xml.html
# HTML related stuff
class H(html):
class Content(html.div):
def __init__(self, *args):
super(H.Content, self).__init__(id='apigen-content', *args)
class Description(html.div):
pass
class NamespaceDescription(Description):
pass
cl... | Python |
""" this contains the code that actually builds the pages using layout.py
building the docs happens in two passes: the first one takes care of
collecting contents and navigation items, the second builds the actual
HTML
"""
import py
from layout import LayoutPage
class Project(py.__.doc.confrest.Project):... | Python |
import re
import sys
import parser
d={}
# d is the dictionary of unittest changes, keyed to the old name
# used by unittest.
# d[old][0] is the new replacement function.
# d[old][1] is the operator you will substitute, or '' if there is none.
# d[old][2] is the possible number of arguments to the unittest
# func... | Python |
#
| Python |
#
| Python |
import py
from py.__.process.cmdexec import ExecutionFailed
font_to_package = {"times": "times", "helvetica": "times",
"new century schoolbock": "newcent", "avant garde": "newcent",
"palatino": "palatino",
}
sans_serif_fonts = {"helvetica": True,
... | Python |
import py
from py.__.rest import rst
from py.xml import html
class RestTransformer(object):
def __init__(self, tree):
self.tree = tree
self._titledepths = {}
self._listmarkers = []
def parse(self, handler):
handler.startDocument()
self.parse_nodes(self.tree.children, ha... | Python |
# XXX this file is messy since it tries to deal with several docutils versions
import py
from py.__.rest.convert import convert_dot, latexformula2png
import sys
import docutils
from docutils import nodes
from docutils.parsers.rst import directives, states, roles
from docutils.parsers.rst.directives import images
if ... | Python |
import py
from py.__.process.cmdexec import ExecutionFailed
# utility functions to convert between various formats
format_to_dotargument = {"png": "png",
"eps": "ps",
"ps": "ps",
"pdf": "ps",
}
def ps2eps(ps):
# X... | Python |
""" reStructuredText generation tools
provides an api to build a tree from nodes, which can be converted to
ReStructuredText on demand
note that not all of ReST is supported, a usable subset is offered, but
certain features aren't supported, and also certain details (like how links
are generated,... | Python |
import py
import sys
class File(object):
""" log consumer wrapping a file(-like) object
"""
def __init__(self, f):
assert hasattr(f, 'write')
assert isinstance(f, file) or not hasattr(f, 'open')
self._file = f
def __call__(self, msg):
""" write a message to the log... | Python |
#
| Python |
"""
py lib's basic logging/tracing functionality
EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL (especially the dispatching)
WARNING: this module is not allowed to contain any 'py' imports,
Instead, it is very self-contained and should not depend on
CPython/stdlib versions, either. One reason for t... | Python |
class Message(object):
def __init__(self, processor, *args):
self.content = args
self.processor = processor
self.keywords = (processor.logger._ident,
processor.name)
def strcontent(self):
return " ".join(map(str, self.content))
def strprefix(sel... | Python |
""" logging API ('producers' and 'consumers' connected via keywords) """
| Python |
import py
class Directory(py.test.collect.Directory):
# XXX see in which situations/platforms we want
# run tests here
#def recfilter(self, path):
# if py.std.sys.platform == 'linux2':
# if path.basename == 'greenlet':
# return False
# return super(Directory, s... | Python |
from distutils.core import setup
from distutils.extension import Extension
setup ( name = "greenlet",
version = "0.1",
ext_modules=[Extension(name = 'greenlet',
sources = ['greenlet.c'])]
)
| Python |
import thread, sys
__all__ = ['greenlet', 'main', 'getcurrent']
class greenlet(object):
__slots__ = ('run', '_controller')
def __init__(self, run=None, parent=None):
if run is not None:
self.run = run
if parent is not None:
self.parent = parent
def switch(self, *... | Python |
# -*- coding: utf-8 -*-
"""
the py lib is a development support library featuring
py.test, ad-hoc distributed execution, micro-threads
and svn abstractions.
"""
from initpkg import initpkg
version = "0.9.1-alpha"
initpkg(__name__,
description = "py lib: agile development and test support library",
... | Python |
from struct import pack, unpack, calcsize
def message(tp, *values):
strtype = type('')
typecodes = ['']
for v in values:
if type(v) is strtype:
typecodes.append('%ds' % len(v))
elif 0 <= v < 256:
typecodes.append('B')
else:
typecodes.append('l')
... | Python |
#import os
import struct
from collections import deque
class InvalidPacket(Exception):
pass
FLAG_NAK1 = 0xE0
FLAG_NAK = 0xE1
FLAG_REG = 0xE2
FLAG_CFRM = 0xE3
FLAG_RANGE_START = 0xE0
FLAG_RANGE_STOP = 0xE4
max_old_packets = 256 # must be <= 256
class PipeLayer(object):
timeout = 1
headersiz... | Python |
""" This is a base implementation of thread-like network programming
on top of greenlets. From API available here it's quite unlikely
that you would like to use anything except wait(). Higher level interface
is available in pipe directory
"""
import os, sys
try:
from stackless import greenlet
except ImportError:
... | Python |
from py.__.green import greensock2
import socket, errno, os
error = socket.error
class _delegate(object):
def __init__(self, methname):
self.methname = methname
def __get__(self, obj, typ=None):
result = getattr(obj._s, self.methname)
setattr(obj, self.methname, result)
return... | Python |
from py.__.green.pipe.common import BufferedInput
class MeetingPointInput(BufferedInput):
def __init__(self, accepter):
self.accepter = accepter
def wait_input(self):
while not self.in_buf:
self.in_buf = self.accepter.accept()
def shutdown_rd(self):
self.accepter.clo... | Python |
from py.__.green import greensock2
VERBOSE = True
if VERBOSE:
def log(msg, *args):
print '*', msg % args
else:
def log(msg, *args):
pass
class BufferedInput(object):
in_buf = ''
def recv(self, bufsize):
self.wait_input()
buf = self.in_buf[:bufsize]
self.in_bu... | Python |
import os
from py.__.green import greensock2
class FDInput(object):
def __init__(self, read_fd, close=True):
self.read_fd = read_fd
self._close = close # a flag or a callback
def shutdown_rd(self):
fd = self.read_fd
if fd is not None:
self.read_fd = None
... | Python |
""" This is a higher level network interface based on top
of greensock2. Objects here are ready to use, specific examples
are listed in tests (test_pipelayer and test_greensock2).
The limitation is that you're not supposed to use threads + blocking
I/O at all.
"""
| Python |
import BaseHTTPServer
from py.__.green import greensock2
from py.__.green.pipe.gsocket import GreenSocket
class GreenMixIn:
"""Mix-in class to handle each request in a new greenlet."""
def process_request_greenlet(self, request, client_address):
"""Same as in BaseServer but as a greenlet.
In ... | Python |
""" This is an implementation of an execnet protocol on top
of a transport layer provided by the greensock2 interface.
It has the same semantics, but does not use threads at all
(which makes it suitable for specific enviroments, like pypy-c).
There are some features lacking, most notable:
- callback support for chan... | Python |
#
| Python |
import os
import sys
import py
class FDCapture:
""" Capture IO to/from a given os-level filedescriptor. """
def __init__(self, targetfd, tmpfile=None):
self.targetfd = targetfd
if tmpfile is None:
tmpfile = self.maketmpfile()
self.tmpfile = tmpfile
self._sa... | Python |
import os
import sys
import py
try: from cStringIO import StringIO
except ImportError: from StringIO import StringIO
class Capture(object):
def call(cls, func, *args, **kwargs):
""" return a (res, out, err) tuple where
out and err represent the output/error output
during function ... | Python |
""" input/output helping """
| Python |
#
| Python |
import os
def dupfile(f, mode=None, buffering=0, raising=False):
""" return a new open file object that's a duplicate of f
mode is duplicated if not given, 'buffering' controls
buffer size (defaulting to no buffering) and 'raising'
defines whether an exception is raised when an incompat... | Python |
import httplib, mimetypes
"""Copied from the cookbook
see ActiveState's ASPN
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
"""
def post_multipart(host, selector, fields, files):
"""
Post fields and files to an http host as multipart/form-data.
fields is a sequence of (name, val... | Python |
import py
import re
from exception import *
from post_multipart import post_multipart
#import css_checker
def check_html(string):
"""check an HTML string for wellformedness and validity"""
tempdir = py.test.ensuretemp('check_html')
filename = 'temp%s.html' % (hash(string), )
tempfile = tempdir.join(fil... | Python |
class CSSError(Exception):
"""raised when there's a problem with the CSS"""
class HTMLError(Exception):
"""raised when there's a problem with the HTML"""
| Python |
import py
#
# main entry point
#
def main(args=None):
warn_about_missing_assertion()
if args is None:
args = py.std.sys.argv[1:]
config = py.test.config
config.parse(args)
session = config.initsession()
try:
failures = session.main()
if failures:
raise Sys... | Python |
"""
Collect test items at filesystem and python module levels.
Collectors and test items form a tree. The difference
between a collector and a test item as seen from the session
is smalll. Collectors usually return a list of child
collectors/items whereas items usually return None
indicating a successful test ru... | Python |
import py
from inspect import isclass, ismodule
from py.__.test.outcome import Skipped, Failed, Passed
_dummy = object()
class SetupState(object):
""" shared state for setting up/tearing down tests. """
def __init__(self):
self.stack = []
def teardown_all(self):
while self.stack:
... | Python |
import py
from py.__.test.outcome import Outcome, Failed, Passed, Skipped
class Session(object):
"""
A Session gets test Items from Collectors, # executes the
Items and sends the Outcome to the Reporter.
"""
def __init__(self, config):
self._memo = []
self.config = config
... | Python |
import py
class DoctestText(py.test.collect.Item):
def _setcontent(self, content):
self._content = content
#def buildname2items(self):
# parser = py.compat.doctest.DoctestParser()
# l = parser.get_examples(self._content)
# d = {}
# globs = {}
# locs
# for i,... | Python |
import py
def deprecated_call(func, *args, **kwargs):
""" assert that calling func(*args, **kwargs)
triggers a DeprecationWarning.
"""
l = []
oldwarn = py.std.warnings.warn_explicit
def warn_explicit(*args, **kwargs):
l.append(args)
oldwarn(*args, **kwargs)
... | Python |
""" reporter - different reporter for different purposes ;-)
Still lacks:
1. Hanging nodes are not done well
"""
import py
from py.__.test.terminal.out import getout
from py.__.test.rsession import repevent
from py.__.test.rsession import outcome
from py.__.misc.terminal_helper import ansi_print, get_te... | Python |
""" web server for py.test
"""
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import thread, threading
import re
import time
import random
import Queue
import os
import sys
import socket
import py
from py.__.test.rsession.rsession import RSession
from py.__.test.rsession import repevent
from py.__.te... | Python |
import sys, os
import py
import time
import thread, threading
from py.__.test.rsession.master import MasterNode
from py.__.test.rsession.slave import setup_slave
from py.__.test.rsession import repevent
class HostInfo(object):
""" Class trying to store all necessary attributes
for host
"""
_hostname2... | Python |
""" javascript source for py.test distributed
"""
import py
from py.__.test.rsession.web import exported_methods
try:
from pypy.translator.js.modules import dom
from pypy.translator.js.helper import __show_traceback
except ImportError:
py.test.skip("PyPy not found")
def create_elem(s):
return dom.doc... | Python |
import string
import types
## json.py implements a JSON (http://json.org) reader and writer.
## Copyright (C) 2005 Patrick D. Logan
## Contact mailto:patrickdlogan@stardecisions.com
##
## This library is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser Genera... | Python |
""" Rest reporting stuff
"""
import py
import sys
from StringIO import StringIO
from py.__.test.rsession.reporter import AbstractReporter
from py.__.test.rsession import repevent
from py.__.rest.rst import *
class RestReporter(AbstractReporter):
linkwriter = None
def __init__(self, *args, **kwargs):
... | Python |
""" local-only operations
"""
import py
from py.__.test.rsession.executor import BoxExecutor, RunExecutor,\
ApigenExecutor
from py.__.test.rsession import repevent
from py.__.test.rsession.outcome import ReprOutcome
# XXX copied from session.py
def startcapture(session):
if not session.config.option.nocaptu... | Python |
""" Reporter classes for showing asynchronous and synchronous status events
"""
import py
import time
def basic_report(msg_type, message):
print msg_type, message
#def report(msg_type, message):
# pass
##def report_error(excinfo):
## if isinstance(excinfo, py.test.collect.Item.Skipped):
## # we nee... | Python |
""" boxing - wrapping process with another process so we can run
a process inside and see if it crashes
"""
import py
import os
import sys
import marshal
from py.__.test import config as pytestconfig
PYTESTSTDOUT = "pyteststdout"
PYTESTSTDERR = "pyteststderr"
PYTESTRETVAL = "pytestretval"
import tempfile
import ite... | Python |
""" some example for running box stuff inside
"""
import sys
import py, os
def boxf1():
print "some out"
print >>sys.stderr, "some err"
return 1
def boxf2():
os.write(1, "someout")
os.write(2, "someerr")
return 2
def boxseg():
os.kill(os.getpid(), 11)
def boxhuge():
os.write(1, " "... | Python |
def f1():
f2()
def f2():
pass
def g1():
g2()
def g2():
raise ValueError()
| Python |
""" Support module for running tests
"""
import py
def func_source():
import py
import time
def funcpass():
pass
def funcfail():
raise AssertionError("hello world")
def funcskip():
py.test.skip("skipped")
def funcprint():
print "samfing"
def funcprintf... | Python |
#
| Python |
""" Remote session base class
"""
import os
import py
import sys
import re
import time
from py.__.test.rsession import repevent
from py.__.test.rsession.master import MasterNode, dispatch_loop, itemgen
from py.__.test.rsession.hostmanage import HostInfo, HostManager
from py.__.test.rsession.local import local_loop, ... | Python |
""" Remote executor
"""
import py, os, sys
from py.__.test.rsession.outcome import Outcome, ReprOutcome
from py.__.test.rsession.box import Box
from py.__.test.rsession import repevent
from py.__.test.outcome import Skipped, Failed
class RunExecutor(object):
""" Same as in executor, but just running run
"""
... | Python |
"""
Node code for Master.
"""
import py
from py.__.test.rsession.outcome import ReprOutcome
from py.__.test.rsession import repevent
class MasterNode(object):
def __init__(self, channel, reporter):
self.channel = channel
self.reporter = reporter
self.pending = []
channel.setcallbac... | Python |
""" Classes for representing outcomes on master and slavenode sides
"""
# WARNING! is_critical is debugging flag which means something
# wrong went on a different level. Usually that means
# internal bug.
import sys
import py
class Outcome(object):
def __init__(self, setupfailure=False, excinf... | Python |
#
| Python |
"""
Node code for slaves.
"""
import py
from py.__.test.rsession.executor import RunExecutor, BoxExecutor, AsyncExecutor
from py.__.test.rsession.outcome import Outcome
from py.__.test.outcome import Skipped
import thread
import os
class SlaveNode(object):
def __init__(self, config, executor):
#self.root... | Python |
from __future__ import generators
import py
from py.__.test.session import Session
from py.__.test.terminal.out import getout
from py.__.test.outcome import Failed, Passed, Skipped
def checkpyfilechange(rootdir, statcache={}):
""" wait until project files are changed. """
def fil(p):
return p.ext in (... | Python |
from __future__ import generators
import sys
import os
import py
from py.__.misc import terminal_helper
class Out(object):
tty = False
fullwidth = terminal_helper.terminal_width
def __init__(self, file):
self.file = py.io.dupfile(file)
def sep(self, sepchar, title=None, fullwidth=None):
... | Python |
import py
from time import time as now
from py.__.test.terminal.out import getout
from py.__.test.representation import Presenter
from py.__.test.outcome import Skipped, Passed, Failed
def getrelpath(source, dest):
base = source.common(dest)
if not base:
return None
# with posix local paths '/... | Python |
#
| Python |
from __future__ import generators
import py
from conftesthandle import Conftest
from py.__.test.defaultconftest import adddefaultoptions
optparse = py.compat.optparse
# XXX move to Config class
basetemp = None
def ensuretemp(string, dir=1):
""" return temporary directory path with
the given string as th... | Python |
import py
Module = py.test.collect.Module
DoctestFile = py.test.collect.DoctestFile
Directory = py.test.collect.Directory
Class = py.test.collect.Class
Generator = py.test.collect.Generator
Function = py.test.collect.Function
Instance = py.test.collect.Instance
conf_iocapture = "fd" # overridable from conftest.py
#... | Python |
import py
defaultconftestpath = py.magic.autopath().dirpath('defaultconftest.py')
class Conftest(object):
""" the single place for accessing values and interacting
towards conftest modules from py.test objects.
Note that triggering Conftest instances to import
conftest.py files may resu... | Python |
import shared_lib
| Python |
"""
Just a dummy module
"""
| Python |
from package import shared_lib
| Python |
#
| Python |
#
| Python |
import py
def setup_module(mod):
mod.datadir = setupdatadir()
mod.tmpdir = py.test.ensuretemp(mod.__name__)
def setupdatadir():
datadir = py.test.ensuretemp("datadir")
names = [x.basename for x in datadir.listdir()]
for name, content in namecontent:
if name not in names:
datad... | Python |
""" This file intends to gather all methods of representing
failures/tracebacks etc. which should be used among
all terminal-based reporters. This methods should be general,
to allow further use outside the pylib
"""
import py
from py.__.code import safe_repr
class Presenter(object):
""" Class used for presentat... | Python |
""" File defining possible outcomes of running
"""
class Outcome:
def __init__(self, msg=None, excinfo=None):
self.msg = msg
self.excinfo = excinfo
def __repr__(self):
if self.msg:
return self.msg
return "<%s instance>" %(self.__class__.__name__,)
__str__ ... | Python |
""" versatile unit-testing tool + libraries """
| Python |
import sys
import py
from py.__.test.outcome import ExceptionFailure
def raises(ExpectedException, *args, **kwargs):
""" raise AssertionError, if target code does not raise the expected
exception.
"""
assert args
__tracebackhide__ = True
if isinstance(args[0], str):
expr, = args
... | Python |
import sys
if '_stackless' in sys.builtin_module_names:
# when running on top of a pypy with stackless support
from _stackless import greenlet
else:
# regular CPython (or pypy without stackless support, and then crash :-)
import py
gdir = py.path.local(py.__file__).dirpath()
path = gdir.join('c... | Python |
from compiler import parse, ast, pycodegen
import py
import __builtin__, sys
passthroughex = (KeyboardInterrupt, SystemExit, MemoryError)
class Failure:
def __init__(self, node):
self.exc, self.value, self.tb = sys.exc_info()
self.node = node
#import traceback
#traceback.print_exc(... | Python |
import __builtin__, sys
import py
from py.__.magic import exprinfo
BuiltinAssertionError = __builtin__.AssertionError
class AssertionError(BuiltinAssertionError):
def __init__(self, *args):
BuiltinAssertionError.__init__(self, *args)
if args:
self.msg = str(args[0])
else:
... | Python |
import py
import __builtin__ as cpy_builtin
def invoke(assertion=False, compile=False):
""" invoke magic, currently you can specify:
assertion patches the builtin AssertionError to try to give
more meaningful AssertionErrors, which by means
of deploying a mini-inter... | Python |
#
| Python |
import os, sys
from py.path import local
from py.__.path.common import PathStr
def autopath(globs=None, basefile='__init__.py'):
""" return the (local) path of the "current" file pointed to by globals
or - if it is none - alternatively the callers frame globals.
the path will always point to a .py... | Python |
patched = {}
def patch(namespace, name, value):
""" rebind the 'name' on the 'namespace' to the 'value',
possibly and remember the original value. Multiple
invocations to the same namespace/name pair will
remember a list of old values.
"""
nref = (namespace, name)
orig = getat... | Python |
""" some nice, slightly magic APIs """
| Python |
"""
The View base class for view-based programming.
A view of an object is an extension of this existing object.
This is useful to *locally* add methods or even attributes to objects
that you have obtained from elsewhere.
"""
from __future__ import generators
import inspect
class View(object):
"""View base class.... | Python |
"""
Lazy functions in PyPy.
To run on top of the thunk object space with the following command-line:
py.py -o thunk fibonacci2.py
This is a typical Functional Programming Languages demo, computing the
Fibonacci sequence as nested 2-tuples.
"""
import pprint
try:
from __pypy__ import lazy
except ImportError:... | Python |
"""
Standard Library usage demo.
Uses urllib and htmllib to download and parse a web page.
The purpose of this demo is to remind and show that almost all
pure-Python modules of the Standard Library work just fine.
"""
url = 'http://www.python.org/'
html = 'python.html'
import urllib
content = urllib.u... | Python |
"""This is an example that uses the (prototype) Logic Object Space. To run,
you have to set USE_GREENLETS in pypy.objspace.logic to True and do:
$ py.py -o logic uthread.py
newvar creates a new unbound logical variable. If you try to access an unbound
variable, the current uthread is blocked, until the variable... | Python |
"""
Of historical interest: we computed the food bill of our first Gothenburg
sprint with PyPy :-)
"""
slips=[(1, 'Kals MatMarkn', 6150, 'Chutney for Curry', 'dinner Saturday'),
(2, 'Kals MatMarkn', 32000, 'Spaghetti, Beer', 'dinner Monday'),
(2, 'Kals MatMarkn', -810, 'Deposit on Beer Bottles', 'various... | Python |
"""
An old-time classical example, and one of our first goals.
To run on top of PyPy.
"""
import dis
dis.dis(dis.dis)
| Python |
"""
Thunk (a.k.a. lazy objects) in PyPy.
To run on top of the thunk object space with the following command-line:
py.py -o thunk fibonacci.py
This is a typical Functional Programming Languages demo, computing the
Fibonacci sequence by using an infinite lazy linked list.
"""
try:
from __pypy__ import thunk ... | Python |
"""SQL injection example with holes fixed using the taint space.
Needs gadfly (sf.net/projects/gadfly) to be on the python path.
Use populate.py to create the example db.
Passwords are the reverse of user names :).
Query is the number of a calendar month, purchases
for the user with the password sinc... | Python |
"""SQL injection example
Needs gadfly (sf.net/projects/gadfly) to be on the python path.
Use populate.py to create the example db.
Passwords are the reverse of user names :).
Query is the number of a calendar month, purchases
for the user with the password since including that month
are shown.
... | Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.