How to use roundup method in Robotframework

Best Python code snippet using robotframework

ZRoundup.py

Source:ZRoundup.py Github

copy

Full Screen

1# Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)2# This module is free software, and you may redistribute it and/or modify3# under the same terms as Python, so long as this copyright message and4# disclaimer are retained in their original form.5#6# IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR7# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING8# OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE9# POSSIBILITY OF SUCH DAMAGE.10#11# BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,12# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS13# FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"14# BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,15# SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.16# 17''' ZRoundup module - exposes the roundup web interface to Zope18This frontend works by providing a thin layer that sits between Zope and the19regular CGI interface of roundup, providing the web frontend with the minimum20of effort.21This means that the regular CGI interface does all authentication quite22independently of Zope. The roundup code is kept in memory though, and it23runs in the same server as all your other Zope stuff, so it does have _some_24advantages over regular CGI :)25'''26import urlparse27from Globals import InitializeClass, HTMLFile28from OFS.SimpleItem import Item29from OFS.PropertyManager import PropertyManager30from Acquisition import Explicit, Implicit31from Persistence import Persistent32from AccessControl import ClassSecurityInfo33from AccessControl import ModuleSecurityInfo34modulesecurity = ModuleSecurityInfo()35import roundup.instance36from roundup.cgi import client37modulesecurity.declareProtected('View management screens',38 'manage_addZRoundupForm')39manage_addZRoundupForm = HTMLFile('dtml/manage_addZRoundupForm', globals())40modulesecurity.declareProtected('Add Z Roundups', 'manage_addZRoundup')41def manage_addZRoundup(self, id, instance_home, REQUEST):42 """Add a ZRoundup product """43 # validate the instance_home44 roundup.instance.open(instance_home)45 self._setObject(id, ZRoundup(id, instance_home))46 return self.manage_main(self, REQUEST)47class RequestWrapper:48 '''Make the Zope RESPONSE look like a BaseHTTPServer49 '''50 def __init__(self, RESPONSE):51 self.RESPONSE = RESPONSE52 self.wfile = self.RESPONSE53 def send_response(self, status):54 self.RESPONSE.setStatus(status)55 def send_header(self, header, value):56 self.RESPONSE.addHeader(header, value)57 def end_headers(self):58 # not needed - the RESPONSE object handles this internally on write()59 pass60 def start_response(self, headers, response):61 self.send_response(response)62 for key, value in headers:63 self.send_header(key, value)64 self.end_headers()65class FormItem:66 '''Make a Zope form item look like a cgi.py one67 '''68 def __init__(self, value):69 self.value = value70 if hasattr(self.value, 'filename'):71 self.filename = self.value.filename72 self.value = self.value.read()73class FormWrapper:74 '''Make a Zope form dict look like a cgi.py one75 '''76 def __init__(self, form):77 self.__form = form78 def __getitem__(self, item):79 entry = self.__form[item]80 if isinstance(entry, type([])):81 entry = map(FormItem, entry)82 else:83 entry = FormItem(entry)84 return entry85 def __iter__(self):86 return iter(self.__form)87 def getvalue(self, key, default=None):88 if self.__form.has_key(key):89 return self.__form[key]90 else:91 return default92 def has_key(self, item):93 return self.__form.has_key(item)94 def keys(self):95 return self.__form.keys()96 def __repr__(self):97 return '<ZRoundup.FormWrapper %r>'%self.__form98class ZRoundup(Item, PropertyManager, Implicit, Persistent):99 '''An instance of this class provides an interface between Zope and100 roundup for one roundup instance101 '''102 meta_type = 'Z Roundup'103 security = ClassSecurityInfo()104 def __init__(self, id, instance_home):105 self.id = id106 self.instance_home = instance_home107 # define the properties that define this object108 _properties = (109 {'id':'id', 'type': 'string', 'mode': 'w'},110 {'id':'instance_home', 'type': 'string', 'mode': 'w'},111 )112 property_extensible_schema__ = 0113 # define the tabs for the management interface114 manage_options= PropertyManager.manage_options + (115 {'label': 'View', 'action':'index_html'},116 ) + Item.manage_options117 icon = "misc_/ZRoundup/icon"118 security.declarePrivate('roundup_opendb')119 def roundup_opendb(self):120 '''Open the roundup instance database for a transaction.121 '''122 tracker = roundup.instance.open(self.instance_home)123 request = RequestWrapper(self.REQUEST['RESPONSE'])124 env = self.REQUEST.environ125 # figure out the path components to set126 url = urlparse.urlparse( self.absolute_url() )127 path = url[2]128 path_components = path.split( '/' )129 # special case when roundup is '/' in this virtual host,130 if path == "/" :131 env['SCRIPT_NAME'] = "/"132 env['TRACKER_NAME'] = ''133 else :134 # all but the last element is the path135 env['SCRIPT_NAME'] = '/'.join( path_components[:-1] )136 # the last element is the name137 env['TRACKER_NAME'] = path_components[-1]138 form = FormWrapper(self.REQUEST.form)139 if hasattr(tracker, 'Client'):140 return tracker.Client(tracker, request, env, form)141 return client.Client(tracker, request, env, form)142 security.declareProtected('View', 'index_html')143 def index_html(self):144 '''Alias index_html to roundup's index145 '''146 # Redirect misdirected requests -- bugs 558867 , 565992147 # PATH_INFO, as defined by the CGI spec, has the *real* request path148 orig_path = self.REQUEST.environ['PATH_INFO']149 if orig_path[-1] != '/' : 150 url = urlparse.urlparse( self.absolute_url() )151 url = list( url ) # make mutable152 url[2] = url[2]+'/' # patch153 url = urlparse.urlunparse( url ) # reassemble154 RESPONSE = self.REQUEST.RESPONSE155 RESPONSE.setStatus( "MovedPermanently" ) # 301156 RESPONSE.setHeader( "Location" , url )157 return RESPONSE158 client = self.roundup_opendb()159 # fake the path that roundup should use160 client.split_path = ['index']161 return client.main()162 def __getitem__(self, item):163 '''All other URL accesses are passed throuh to roundup164 '''165 return PathElement(self, item).__of__(self)166class PathElement(Item, Implicit):167 def __init__(self, zr, path):168 self.zr = zr169 self.path = path170 def __getitem__(self, item):171 ''' Get a subitem.172 '''173 return PathElement(self.zr, self.path + '/' + item).__of__(self)174 def index_html(self, REQUEST=None):175 ''' Actually call through to roundup to handle the request.176 '''177 try:178 client = self.zr.roundup_opendb()179 # fake the path that roundup should use180 client.path = self.path181 # and call roundup to do something 182 client.main()183 return ''184 except client.NotFound:185 raise 'NotFound', REQUEST.URL186 pass187 except:188 import traceback189 traceback.print_exc()190 # all other exceptions in roundup are valid191 raise192InitializeClass(ZRoundup)193modulesecurity.apply(globals())...

Full Screen

Full Screen

setup.py

Source:setup.py Github

copy

Full Screen

1#! /usr/bin/env python2# -*- coding: utf-8 -*-3#4# Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)5# This module is free software, and you may redistribute it and/or modify6# under the same terms as Python, so long as this copyright message and7# disclaimer are retained in their original form.8#9# IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR10# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING11# OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE12# POSSIBILITY OF SUCH DAMAGE.13#14# BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,15# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS16# FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"17# BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,18# SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.19#20from roundup.dist.command.build_doc import build_doc21from roundup.dist.command.build_scripts import build_scripts22from roundup.dist.command.build import build, list_message_files23from roundup.dist.command.bdist_rpm import bdist_rpm24from roundup.dist.command.install_lib import install_lib25# FIXME: setuptools breaks the --manifest-only option to setup.py and26# doesn't seem to generate a MANIFEST file. Since I'm not familiar with27# the way setuptools handles the files to include I'm commenting this28# for now -- Ralf Schlatterbeck29#try:30# from setuptools import setup31#except ImportError:32from distutils.core import setup33import sys, os34from glob import glob35# patch distutils if it can't cope with the "classifiers" keyword36from distutils.dist import DistributionMetadata37if not hasattr(DistributionMetadata, 'classifiers'):38 DistributionMetadata.classifiers = None39 DistributionMetadata.download_url = None40def include(d, e):41 """Generate a pair of (directory, file-list) for installation.42 'd' -- A directory43 'e' -- A glob pattern"""44 return (d, [f for f in glob('%s/%s'%(d, e)) if os.path.isfile(f)])45def mapscript(path):46 """ Helper for building a list of script names from a list of47 module files.48 """49 module = os.path.splitext(os.path.basename(path))[0]50 script = module.replace('_', '-')51 return '%s = roundup.scripts.%s:run' % (script, module)52def main():53 # template munching54 packages = [55 'roundup',56 'roundup.anypy',57 'roundup.cgi',58 'roundup.cgi.PageTemplates',59 'roundup.cgi.TAL',60 'roundup.cgi.ZTUtils',61 'roundup.backends',62 'roundup.scripts',63 ]64 # build list of scripts from their implementation modules65 scripts = [mapscript(f) for f in glob('roundup/scripts/[!_]*.py')]66 data_files = [67 ('share/roundup/cgi-bin', ['frontends/roundup.cgi']),68 ]69 # install man pages on POSIX platforms70 if os.name == 'posix':71 data_files.append(include('share/man/man1', '*'))72 # add the templates to the data files lists73 from roundup.init import listTemplates74 templates = [t['path']75 for t in listTemplates('share/roundup/templates').values()]76 for tdir in templates:77 for idir in '. detectors extensions html html/layout static'.split():78 data_files.append(include(os.path.join(tdir, idir), '*'))79 # add message files80 for (_dist_file, _mo_file) in list_message_files():81 data_files.append((os.path.dirname(_mo_file),82 [os.path.join("build", _mo_file)]))83 # add docs84 data_files.append(include('share/doc/roundup/html', '*'))85 data_files.append(include('share/doc/roundup/html/_images', '*'))86 data_files.append(include('share/doc/roundup/html/_sources', '*'))87 data_files.append(include('share/doc/roundup/html/_static', '*'))88 # perform the setup action89 from roundup import __version__90 # long_description may not contain non-ascii characters. Distutils91 # will produce an non-installable installer on linux *and* we can't92 # run the bdist_wininst on Linux if there are non-ascii characters93 # because the distutils installer will try to use the mbcs codec94 # which isn't available on non-windows platforms. See also95 # http://bugs.python.org/issue1094596 long_description=open('doc/announcement.txt').read().decode('utf8')97 try:98 long_description = long_description.encode('ascii')99 except UnicodeEncodeError, cause:100 print >> sys.stderr, "doc/announcement.txt contains non-ascii: %s" \101 % cause102 sys.exit(42)103 setup(name='roundup',104 version=__version__,105 author="Richard Jones",106 author_email="richard@users.sourceforge.net",107 maintainer="Ralf Schlatterbeck",108 maintainer_email="rsc@runtux.com",109 description="A simple-to-use and -install issue-tracking system"110 " with command-line, web and e-mail interfaces. Highly"111 " customisable.",112 long_description=long_description,113 url='http://www.roundup-tracker.org',114 download_url='http://pypi.python.org/pypi/roundup',115 classifiers=['Development Status :: 5 - Production/Stable',116 'Environment :: Console',117 'Environment :: Web Environment',118 'Intended Audience :: End Users/Desktop',119 'Intended Audience :: Developers',120 'Intended Audience :: System Administrators',121 'License :: OSI Approved :: MIT License',122 'Operating System :: MacOS :: MacOS X',123 'Operating System :: Microsoft :: Windows',124 'Operating System :: POSIX',125 'Programming Language :: Python',126 'Topic :: Communications :: Email',127 'Topic :: Office/Business',128 'Topic :: Software Development :: Bug Tracking',129 ],130 # Override certain command classes with our own ones131 cmdclass= {'build_doc': build_doc,132 'build_scripts': build_scripts,133 'build': build,134 'bdist_rpm': bdist_rpm,135 'install_lib': install_lib,136 },137 packages=packages,138 entry_points={139 'console_scripts': scripts140 },141 data_files=data_files)142if __name__ == '__main__':143 os.chdir(os.path.dirname(__file__) or '.')144 main()...

Full Screen

Full Screen

stat.py

Source:stat.py Github

copy

Full Screen

...6from django.apps import apps7from bank.services.dwolla_api import DwollaApi8from decimal import *9class StatManager(models.Manager):10 def get_collected_roundup(self, user_id):11 """12 Roundup total, that collected13 but not sent to Donkies yet.14 """15 Transaction = apps.get_model('finance', 'Transaction')16 TransferPrepare = apps.get_model('finance', 'TransferPrepare')17 TransferStripe = apps.get_model('ach', 'TransferStripe')18 sum1 = Transaction.objects\19 .filter(account__item__user_id=user_id, is_processed=False)\20 .aggregate(Sum('roundup'))['roundup__sum']21 sum2 = TransferPrepare.objects\22 .filter(account__item__user_id=user_id, is_processed=False)\23 .aggregate(Sum('roundup'))['roundup__sum']24 sum3 = TransferStripe.objects\25 .filter(account__item__user_id=user_id, paid=False)\26 .aggregate(Sum('amount'))['amount__sum']27 sum1 = sum1 if sum1 is not None else 028 sum2 = sum2 if sum2 is not None else 029 sum3 = sum3 if sum3 is not None else 030 return sum1 + sum2 + sum331 def get_to_stripe_amount(self, user_id):32 """33 Returns total roundup transferred to Stripe.34 """35 TransferStripe = apps.get_model('ach', 'TransferStripe')36 sum = TransferStripe.objects\37 .filter(account__item__user_id=user_id, paid=True)\38 .aggregate(Sum('amount'))['amount__sum']39 if sum is not None:40 return sum41 return 042 def get_to_user_amount(self, user_id):43 """44 Returns total roundup transferred to User.45 """46 TransferDebt = apps.get_model('ach', 'TransferDebt')47 sum = TransferDebt.objects\48 .filter(account__item__user_id=user_id, is_processed=True)\49 .aggregate(Sum('amount'))['amount__sum']50 if sum is not None:51 return sum52 return 053 def get_available_amount(self, user_id):54 """55 Dwolla implementation.56 Returns total amount available to transfer.57 """58 TransferStripe = apps.get_model('ach', 'TransferStripe')59 qs = TransferStripe.objects.get_user_queryset(user_id)60 sum = qs\61 .aggregate(Sum('amount'))['amount__sum']62 if sum is not None:63 return sum64 return 065 def get_payments_count(self, user_id):66 TransferDebt = apps.get_model('ach', 'TransferDebt')67 return TransferDebt.objects\68 .filter(account__item__user_id=user_id, is_processed=True)\69 .count()70 def get_roundup_since_signup(self, user_id):71 Transaction = apps.get_model('finance', 'Transaction')72 User = apps.get_model('web', 'User')73 user = User.objects.get(id=user_id)74 sum = Transaction.objects.filter(75 account__item__user=user, date__gte=user.created_at76 ).aggregate(Sum('roundup'))['roundup__sum']77 if not sum:78 return 079 return sum80 def get_daily_average_roundup(self, user_id):81 """82 Average daily roundup since first available transaction.83 Returns total roundup/num_days84 """85 Transaction = apps.get_model('finance', 'Transaction')86 sum = Transaction.objects\87 .filter(account__item__user_id=user_id)\88 .aggregate(Sum('roundup'))['roundup__sum']89 if not sum:90 return 091 first_transaction = Transaction.objects.filter(92 account__item__user_id=user_id).earliest('date')93 dt = first_transaction.date94 delta = datetime.date.today() - dt95 return sum / delta.days96 def get_monthly_average_roundup(self, user_id):97 return self.get_daily_average_roundup(user_id) * 3098 def get_yearly_average_roundup(self, user_id):99 return self.get_daily_average_roundup(user_id) * 365100 def get_funds_in_coinstash(self, user_id):101 User = apps.get_model('web', 'User')102 Customer = apps.get_model('bank', 'Customer')103 user = User.objects.get(id=user_id)104 customer_user = user105 if user.is_parent:106 customer_user = user.childs.first()107 customer = get_object_or_404(Customer, user=customer_user)108 dw = DwollaApi()109 customer_url = "{}customers/{}/funding-sources".format(110 dw.get_api_url(), customer.dwolla_id)111 funding_sources = dw.token.get(customer_url)112 balance_url = None113 for i in funding_sources.body['_embedded']['funding-sources']:114 if "balance" in i['_links'].keys():115 balance_url = i['_links']['balance']['href']116 try:117 balance = dw.token.get(balance_url)118 balance_value = balance.body['balance']['value']119 except AttributeError:120 balance_value = 0121 return balance_value122 def get_applied_funds(self, user_id):123 User = apps.get_model('web', 'User')124 TransferCalculation = apps.get_model('finance', 'TransferCalculation')125 user = User.objects.get(id=user_id)126 tr, created = TransferCalculation.objects.get_or_create(user=user)127 return tr.applied_funds128 def get_json(self, user_id):129 return {130 'roundup_since_signup': self.get_roundup_since_signup(user_id),131 'monthly_average_roundup': self.get_monthly_average_roundup(user_id),132 'yearly_average_roundup': self.get_yearly_average_roundup(user_id),133 'funds_in_coinstash': self.get_funds_in_coinstash(user_id),134 'applied_funds': self.get_applied_funds(user_id)135 }136class Stat(models.Model):137 """138 In future consider periodically cache all stat139 to database and serve from database.140 """141 objects = StatManager()142 class Meta:143 app_label = 'finance'144 verbose_name = 'stat'145 verbose_name_plural = 'stat'146 ordering = ['id']...

Full Screen

Full Screen

test_misc.py

Source:test_misc.py Github

copy

Full Screen

...5 def test_basics(self):6 for number in range(1000):7 for extra in range(5):8 extra /= 10.09 assert_equal(roundup(number + extra), number, +extra)10 assert_equal(roundup(number - extra), number, -extra)11 assert_equal(roundup(number + 0.5), number+1)12 def test_negative(self):13 for number in range(1000):14 number *= -115 for extra in range(5):16 extra /= 10.017 assert_equal(roundup(number + extra), number)18 assert_equal(roundup(number - extra), number)19 assert_equal(roundup(number - 0.5), number-1)20 def test_ndigits_below_zero(self):21 assert_equal(roundup(7, -1), 10)22 assert_equal(roundup(77, -1), 80)23 assert_equal(roundup(123, -2), 100)24 assert_equal(roundup(-1234, -2), -1200)25 assert_equal(roundup(9999, -2), 10000)26 def test_ndigits_above_zero(self):27 assert_equal(roundup(0.1234, 1), 0.1)28 assert_equal(roundup(0.9999, 1), 1.0)29 assert_equal(roundup(0.9876, 3), 0.988)30 def test_round_even_up(self):31 assert_equal(roundup(0.5), 1)32 assert_equal(roundup(5, -1), 10)33 assert_equal(roundup(500, -3), 1000)34 assert_equal(roundup(0.05, 1), 0.1)35 assert_equal(roundup(0.49951, 3), 0.5)36 def test_round_even_down_when_negative(self):37 assert_equal(roundup(-0.5), -1)38 assert_equal(roundup(-5, -1), -10)39 assert_equal(roundup(-5.0, -1), -10)40 assert_equal(roundup(-500, -3), -1000)41 assert_equal(roundup(-0.05, 1), -0.1)42 assert_equal(roundup(-0.49951, 3), -0.5)43 def test_return_type(self):44 for n in [1, 1000, 0.1, 0.001]:45 for d in [-3, -2, -1, 0, 1, 2, 3]:46 assert_equal(type(roundup(n, d)), float if d > 0 else int)47 assert_equal(type(roundup(n, d, return_type=int)), int)48 assert_equal(type(roundup(n, d, return_type=float)), float)49 def test_problems(self):50 assert_equal(roundup(59.85, 1), 59.9) # This caused #287251 if not IRONPYTHON:52 assert_equal(roundup(1.15, 1), 1.1) # 1.15 is actually 1.49999..53 else:54 assert_equal(roundup(1.15, 1), 1.2) # but ipy still rounds it up55class TestSeg2Str(unittest.TestCase):56 def _verify(self, input, expected, **config):57 assert_equal(seq2str(input, **config), expected)58 def test_empty(self):59 for seq in [[], (), set()]:60 self._verify(seq, '')61 def test_one_or_more(self):62 for seq, expected in [(['One'], "'One'"),63 (['1', '2'], "'1' and '2'"),64 (['a', 'b', 'c', 'd'], "'a', 'b', 'c' and 'd'"),65 ([u'Unicode', u'ASCII'], "'Unicode' and 'ASCII'")]:66 self._verify(seq, expected)67 def test_non_ascii_unicode(self):68 self._verify([u'hyv\xe4'], u"'hyv\xe4'")...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Robotframework automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful