def usage_tail(pgm, usage, retcode=0): """Display help on command line options. Called from preparseargs() Display usage for all options recognised by this odesk Python API. Parameters: pgm - name of the python script/app usage - the usage statement specific to this script/app retcode - allows for statement such as: exit(usage_tail, usage, 1)) """ use=""" --auth <fn> Name of application authorization file. This is only needs to be given the first time the app is run. The file must contain the application key and secret. These will be stored to ~/.oDeskAPI/{0:s}/auth/app_auth --config <fn> Use <fn> instead of default oDeskAPI python library configuration file ~/.odapi.conf --debug This will cause XML returned from server to be captured to disk. The files will be named after the API function from which the query originates. --log-level n n = 'off', 'debug', 'info', 'warn', 'error', 'crit' = 0 , 1, 2, 3, 4, 5 --log-console Console logging on. Boolean [default= true] --log-disk File logging to on. Boolean [default= true] --no-log-console Turn off console logging. Boolean [default= false] --no-log-disk Turn off logging to file. Boolean [default= false] --name 'alias' Use alias as the name of the program. This is most use- ful for running tests. Once authorization is given for a program the application key and secret is stored to: ~/.oDeskAPI/{1:s}/auth/odesk_app If you are running a new test it will want you to specify the location of the authorization file. If you pass the name of something already run it will use that auth. It will also log to ~/.oDeskAPI/'alias'/logs/'alias'.log \n""" if not usage: usage = """ Usage: {0:s} [OPTIONS] {0:s} --help\n [OPTIONS] """.format(pgm,pgm) stdout(usage) else: stdout(usage) prompt = "\n<Enter> standard library options..." raw_input(prompt) stdout(use.format(pgm,pgm)) return retcode
return (popts, args) (pgm, ext) = path.splitext(path.basename(sys.argv[0])) (api, argv) = app_main(pgm, sys.argv[1:], usage) (popts, args) = parseargs(pgm, argv, usage) if not len(args) > 0: stderr('No provider key(s) given...\n') api.clean_exit(1) #print 'args:', args #api.clean_exit(1) provider_keys = "" for key in args: provider_keys += "{0:s} ".format(key) if popts['request']: req = strip_csv(popts['request']) request = req.split(',') else: request = None all_profiles = provider_profile(api, provider_keys, request=request, brief_listing=False, save_xml=api.debug) if not all_profiles or len(all_profiles) == 0: stderr('Failed to get profile data.\n') api.clean_exit(1) for n in range(len(all_profiles)): profile = all_profiles[n] hdr = '------ profile {0:2d} ------\n'.format(n+1) stdout(hdr) print_dict(stdout, profile) stdout('\n') api.clean_exit(0)
pylevel = toLogLevel(user_levels[n]) if pylevel != log_levels[n]: stderr("toLogLevel({0:s}) ({1:d}) failed, got {2:d} ({3:s})\n".format( user_levels[n], n, pylevel, user_levels[pylevel/10])) errors += 1 tests += 1 # convert 0..5 to logger levels pylevel = toLogLevel(n) if pylevel != log_levels[n]: stderr("toLogLevel({0:s}) ({1:d}) failed, got {2:d} ({3:s})\n".format( user_levels[n], n, pylevel, user_levels[pylevel/10])) errors += 1 tests += 1 stdout("tests converting back and forth between strings and integer log levels:\n") stdout("{0:d} tests, {1:d} failures\n\n".format(tests, errors)) stdout("initializing logging, level debug, console on, log file off.\n") initLogger(logLevel=1, logConsole=True, logDisk=False) stdout("should see debug message test 1\n") log.debug("log test 1") if test_fileobj('{0:s}'.format(pgm)) != 1: stdout('log file \"{0:s}\" should not have been created\n', pgm) errors += 1 else: stdout('Should see "Parameter not a file or file object."\n') tests += 1 print
api.clean_exit(1) log.debug("app_main() returning {0!s}".format(argv2)) return (api, argv2) # This is intended only for testing. if __name__ == '__main__': from odapi.logger import initLogger usage = """ usage: $ {0:s} [OPTIONS] [OPTIONS]""" initLogger(logLevel='debug',logDisk=False, logConsole=True) (api, argv) = app_main(sys.argv[0], sys.argv, usage) api.pprint() stdout("api.log_level = {0:d}\n".format(api.log_level)) setLogLevel("info", api) stdout('setLogLevel("info")\n') stdout("api.log_level = {0:d}\n".format(api.log_level)) log.debug("log debug test") log.info("log info test") log.warn("log warn test") log.error("log error test") stderr("remaining in argv:\n\t {0!s}\n".format(argv)) api.clean_exit(0)
res = test_fileobj(testfile) sres = fileErrors[res] if sres != 'none': print 'failed no error test(1), got', sres failed += 1 ntests += 1 f = open(testfile, "w") # Test zero length file with closed opject f.truncate() f.close() res = test_fileobj(f) sres = fileErrors[res] if sres != 'read': print 'failed closed file object test (zero length file): got', sres failed += 1 ntests += 1 f = open(testfile, "r") res = test_fileobj(f) sres = fileErrors[res] if sres != 'read': print 'failed zero-length test: got', sres failed += 1 ntests += 1 f.close() stdout("failed {0:d} of {1:d} tests\n".format(failed, ntests)) exit(failed)
(pgm, ext) = path.splitext(path.basename(sys.argv[0])) (api, argv) = app_main(pgm, sys.argv[1:], usage) (popts, args) = parse_request(pgm, argv, usage) if popts is None: api.clean_exit(1) if len(args) != 1: stderr ("\n ** Need team name **, quoted if necessary.\n") api.clean_exit(usage_tail(pgm, usage, 1)) team = args[0] if popts['request']: req = strip_csv(popts['request']) request = req.split(',') else: request = None userlist = team_users(api, team, request=request, eid=None, save_xml=api.debug) if len(userlist) == 0: log.error('failed to get user list for team {0:s}'.format(team)) api.clean_exit(1) hdr = '---- contractor {0:2d} of {1:2d} ----\n' total = len(userlist) stdout('------ Team {0:s} ---------\n'.format(team)) for n in range(total): header = hdr.format(n+1, total) stdout(header) print_dict_ordered(stdout, userlist[n], ['last_name', 'first_name', 'status', 'id', 'reference', 'is_provider', 'timezone', 'timezone_offset']) stdout('\n') api.clean_exit(0)
def show_result(r): stdout('{0!r}\n---------------\n'.format(r)) n = 0 for l in r: n += 1 stdout("line {0:02d}({1:02d}): {2:s}\n".format(n,len(l),l))
subcategory, title, visibility" Default is to return all of the above. """ (pgm, ext) = path.splitext(path.basename(sys.argv[0])) (api, argv) = app_main(pgm, sys.argv[1:], usage) (popts, args) = parse_request(pgm, argv, usage) if popts is None: api.clean_exit(1) if not args or not len(args) == 2: stderr ("\n **Need 'company name' 'team name' **, quoted if needed.\n") api.clean_exit(usage_tail(pgm, usage, 1)) company = args[0] team = args[1] if popts['request']: req = strip_csv(popts['request']) request = req.split(',') else: request = None (total, joblist) = jobs_managed(api, company, team, request=request, save_xml=api.debug) if total == 0: stderr("No jobs currently managed by {0:s}\n".format(company)) api.clean_exit(0) hdr = '----- Job {0:2d} of {1:d} ----\n' for n in range(total): header = hdr.format(n+1, total) job = joblist[n] stdout(header) print_dict(stdout, job) api.clean_exit(0)
[OPTIONS] -r, --request "list,of,info" list should be a comma-seperated list of parameters. This limits the information returned and should be a subset of: "affiliation_status, company__name, company__reference, engagement__reference, has_team_room_access, parent_team__id, parent_team__name, parent_team__reference, permission, reference, role, team__id, team__name, team__reference, user__first_name, user__id, user__is_provider, user__last_name, user__reference" Default is to return all of the above. """ (pgm, ext) = path.splitext(path.basename(sys.argv[0])) (api, argv) = app_main(pgm, sys.argv[1:], usage) (popts, args) = parse_request(pgm, argv, usage) if popts is None: api.clean_exit(1) if popts['request']: req = strip_csv(popts['request']) request = req.split(',') else: request = None roles = user_roles(api, request=request, save_xml=False) if not roles or len(roles) == 0: stderr('failed to fetch user roles\n') api.clean_exit(1) for role in roles: print_dict(stdout, role) stdout('\n') api.clean_exit(0)
from odapi.util import stdout, stderr class AppInitError(AppException): pass def show_result(r): stdout('{0!r}\n---------------\n'.format(r)) n = 0 for l in r: n += 1 stdout("line {0:02d}({1:02d}): {2:s}\n".format(n,len(l),l)) e = AppInitError('Testing appending text to AppException class instance.') explain = """This class allows for appending strings via '+' or '+='. This tests the formatting when appending a multi-line string to the class instance.""" e += explain stdout('string_truncate(80)\n') show_result(string_truncate(explain, 80)) print '----------------------------------------------------------------' stdout('string_truncate(60)\n') show_result(string_truncate(explain, 60)) print '-------------stdout(Exception) ----------------------' stdout(e) print '-------------raise Exception ----------------------' raise e
elif key == '-f' or key == '--filters' : optdct['filters'] = to_str(val) elif key == '-o' or key == '--out': optdct['out'] = to_str(val) elif key == '-x' or key == '--xml': optdct['xml'] = True elif key == '-t' or key == '--text': optdct['text'] = True else: e = "Unknown option '{0:s}'".format(key) raise AppOptionError(e) log.debug("{0:s}.py:parseargs() returning:\n\t{0!s}".format(pgm, optdct)) return optdct pgm = 'parse_request' usage = None # Need to construct a bogus argv; one with a 'request' and one without argv = [] for arg in ('-s', '3', '-j', 'jobcat', '-f', 'bogus/path', '-r', 'this,that, the next thing'): argv.append(arg) print stdout('argv: ') print argv (api, argv) = app_main(pgm, argv, usage) (popts, args) = parse_request(pgm, argv, usage) print popts print print args api.clean_exit(0)
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/ """Test odapi.query.organization.team_reference_IDs() query.""" import sys from os import path from odapi.main import app_main, usage_tail from odapi.util import stdout, stderr from odapi.query.organization import team_reference_IDs usage = """ Usage: {0:s} [OPTIONS] "team name" [OPTIONS] """ (pgm, ext) = path.splitext(path.basename(sys.argv[0])) (api, argv) = app_main(pgm, sys.argv[1:], usage) if not len(argv) == 1: stderr('** Need "team name" **\n') api.clean_exit(usage_tail(pgm, usage, 1)) team = argv[0] (team_ref, parent_team_ref, company_ref) = team_reference_IDs(api, team) stdout("team ref: {0:s}\n".format(team_ref)) stdout("parent ref: {0:s}\n".format(parent_team_ref)) stdout("company ref: {0:s}\n".format(company_ref)) api.clean_exit(0)
def pprint(self): from odapi.util import stdout for key in sorted(self.data.keys()): stdout("{0:20s} = {1!r}\n".format(key, self.data[key][0])) stdout("----\n")
#!/usr/bin/env python # -*- coding: utf-8 -*- from odapi.util import get_when, days_ago, stdout for i in range(1,32,5): d = days_ago(i) stdout('days_ago({0:d}) = {1!r}\n'.format(i, d)) stdout('get_when({0:d}) = {1!r}\n'.format(i, get_when(i))) when = str(d.month) + ':' + str(d.day) + ':' + str(d.year) stdout('get_when({0:s}) = {1!r}\n'.format(when, get_when(when)))
#!/usr/bin/env python # -*- coding: utf-8 -*- from odapi.util import limit_intrange, stdout low = (-200, 0, 200) high = (-200, 0, 200) val = (-201, -1, 0, 201) for v in val: for lo in low: for hi in high: try: res = limit_intrange(v, lo, hi) except ValueError, e: stdout(e) pass stdout('limit({0:d}, {1:d}, {2:d}) = {3:d}\n'.format(v,lo,hi,res))
(pgm, ext) = path.splitext(path.basename(sys.argv[0])) (api, argv) = app_main(pgm, sys.argv[1:], usage) (popts, args) = parse_request(pgm, argv, usage) if popts is None: api.clean_exit(1) if popts["request"]: req = strip_csv(popts["request"]) kwargs = str2kwargs(req) # request = req.split(',') else: # request = None kwargs = None # HERE # stdout('\nquery/test/providers.py: kwargs = {0!r}\n'.format(kwargs)) all_providers = provider_search(api, save_xml=api.debug, **kwargs) # HERE if not all_providers or len(all_providers) == 0: stderr("No providers returned.\n") print all_providers api.clean_exit(0) ######################################### for n in range(len(all_providers)): company = all_providers[n] hdr = "------ provider {0:2d} ------\n".format(n + 1) stdout(hdr) print_dict(stdout, company) stdout("\n") api.clean_exit(0)
def usage(pgm, retcode): use="""\n usage: $ {0:s} -i input.xml -t tag [-o output.txt] -t tag is the XML node name, or tag, to parse on\n\n""" stdout(use.format(pgm)) return retcode
# You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/ """Test odapi.query.organization.company_reference_IDs().""" import sys from os import path from odapi.main import app_main from odapi.util import stdout, stderr from odapi.query.organization import company_reference_IDs usage=""" Usage: {0:s} [OPTIONS] {0:s} --help For all companies the authorized user has access to the company name and reference Id is returned in a list of dictionary objects. The dict object keys are 'name' and 'reference'. """ (pgm, ext) = path.splitext(path.basename(sys.argv[0])) (api, argv) = app_main(pgm, sys.argv[1:], usage) cIds = company_reference_IDs(api) if not cIds or len(cIds) == 0: stderr('failed to fetch company reference ids\n') api.clean_exit(1) for n in range(len(cIds)): item = '{0:2d}: {1:40s} {2:s}\n'.format( n+1, cIds[n]['company'], cIds[n]['ref']) stdout(item) api.clean_exit(0)
Default is to return all of the above. """ (pgm, ext) = path.splitext(path.basename(sys.argv[0])) (api, argv) = app_main(pgm, sys.argv[1:], usage) (popts, args) = parse_request(pgm, argv, usage) if popts is None: api.clean_exit(1) if not len(args) == 1: stderr ("\n ** Need company name **, quoted if necessary.\n") api.clean_exit(usage_tail(pgm, usage, 1)) company = args[0] if popts['request']: req = strip_csv(popts['request']) request = req.split(',') else: request = None userlist = company_users(api, company, request=request, save_xml=api.debug) if len(userlist) == 0: stderr('failed to fetch user list for company {0:s}\n'.format(company)) api.clean_exit(1) display_order = ('last_name', 'first_name', 'id', 'status', 'reference', 'is_provider', 'timezone', 'timezone_offset') hdr = '---- contractor {0:2d} of {1:2d} ----\n' total = len(userlist) stdout('------- Company {0:s} --------\n'.format(company)) for n in range(total): header = hdr.format(n+1, total) stdout(header) print_dict_ordered(stdout, userlist[n], display_order) stdout('\n') api.clean_exit(0)