示例#1
0
def backup(email, password, path):
    heroku = Client(email, password)
    path = Path(path)
    if not path.exists():
        path.mkdir()

    for clip in heroku.get_all_dataclips():
        slug = clip['slug']
        print(clip['name'])

        destination_dir = path / slug
        destination_dir.mkdir()

        with (destination_dir / 'clip.json').open('w') as output_file:
            json.dump(clip, output_file)

        for version in heroku.get_dataclip_versions(slug):
            print(version['version_number'])

            version_dir = destination_dir / str(version['version_number'])
            version_dir.mkdir()

            with (version_dir / 'clip.json').open('w') as output_file:
                json.dump(version, output_file)

            with (version_dir / 'clip.sql').open('w') as output_file:
                output_file.write(version['sql'])
 def test_Registration_Value(self, amqcon):
     "Registration / JIRA CASE MT-909/ Registration Datatype "
     print("Message Body :", amqcon[1])
     print("Header :" , amqcon[0])
     with pytest.allure.step('Getting Registration Field  :'):
         registration=[message['MT5Account']['Registration'] for message in amqcon[1]]
     with pytest.allure.step('Getting registration time from db : '):
         registration_db=Client().check_login(amqcon[2])['Registration'].strftime("%Y-%m-%d %H:%M:%S")
     with pytest.allure.step('Comparing values : '):
         assert registration_db in registration
示例#3
0
def move_all(email, password, source_resource, destination_resource):
    heroku = Client(email, password)
    resources = {
        resource['resource_name']: resource['id']
        for resource in heroku.get_heroku_resources()
    }

    if source_resource not in resources:
        raise Exception('`source_resource` not a heroku resource')
    if destination_resource not in resources:
        raise Exception('`destination_resource` not a heroku resource')

    source_dataclips_slugs = [
        dataclip['slug']
        for dataclip in heroku.get_all_dataclips()
        if dataclip['heroku_resource_id'] == resources[source_resource]
    ]

    for source_dataclip_slug in source_dataclips_slugs:
        heroku.move_to_resource(source_dataclip_slug, resources[destination_resource])
示例#4
0
def checkClientMessage(clientThread, client_socket, message, addr):
    msg = message.split()
    if (msg[0] == 'AVAILABLE' and clientThread == None):
        client = Client(addr, client_socket)
        clientQueue.enqueue(client)
        print('[*] Cliente %s:%d disponível' % (addr[0], addr[1]))
        checkQueue()
        return client, False

    elif msg[0] == 'PLAYING':
        client_socket.close()
        print('[*] Fechando conexão com %s:%d' % (addr[0], addr[1]))
        return clientThread, True

    return clientThread, False
示例#5
0
def move_all(email, password, source_resource, destination_resource):
    heroku = Client(email, password)
    resources = {
        resource['resource_name']: resource['id']
        for resource in heroku.get_heroku_resources()
    }

    if source_resource not in resources:
        raise Exception('`source_resource` not a heroku resource')
    if destination_resource not in resources:
        raise Exception('`destination_resource` not a heroku resource')

    source_dataclips_slugs = [
        dataclip['slug'] for dataclip in heroku.get_all_dataclips()
        if dataclip['heroku_id'] == resources[source_resource]
    ]

    for source_dataclip_slug in source_dataclips_slugs:
        heroku.move_to_resource(source_dataclip_slug,
                                resources[destination_resource])
示例#6
0
#!/usr/bin/env python

import os
from api import Client

config = {}
execfile(os.path.join(os.getenv('HOME'), '.creds.py'), config)

creds = config['api_creds']['testing']
c = Client(creds['token'], creds['private_key'])


示例#7
0
def main():

    kwargs = {'vscale_dir': None }

    vs_api_token = None

    if os.path.exists(os.path.expanduser('~') + '/.vscale'):
        kwargs['vscale_dir'] = os.path.expanduser('~') + '/.vscale'

    if 'VSCALE_DIR' in os.environ:
        vscale_dir = os.environ['VSCALE_DIR']

    if 'VSCALE_API_TOKEN' in os.environ:
        vs_api_token = os.environ['VSCALE_API_TOKEN']

    VSCALE_DIR = kwargs.get('vscale_dir')

    import argparse

    argparser = argparse.ArgumentParser()
    subparsers = argparser.add_subparsers(help = 'available resources', dest = 'resource')

    subp_l = {}

    for resource in VSCALE_RESOURCES:
        subp_l[resource] = subparsers.add_parser(resource)

    # scalets

    scalets_sub = subp_l['scalets'].add_subparsers(help = 'scalets actions', dest = 'action')

    s_subs = {}

    # general operations

    for act in ['list', 'ls']:
        s_subs[act] = scalets_sub.add_parser(act, help = 'list scalets')
    for act in ['tasks', 'ps']:
        s_subs[act] = scalets_sub.add_parser(act, help = 'tasks scalets')
    for act in ['create', 'show', 'start', 'stop', 'restart', 'rebuild', 'delete', 'ssh']:
        s_subs[act] = scalets_sub.add_parser(act, help = '{0} scalets'.format(act))

    for act in ['show', 'start', 'stop', 'restart', 'rebuild', 'delete', 'ssh']:
        s_subs[act].add_argument('id', help = 'ctid or scalet name', action='store')

    # creation

    s_subs['create'].add_argument('-n', '--name', help = 'scalet name', action='store', dest='name', required = True)
    s_subs['create'].add_argument('-t', '--template', help = 'template name', dest = 'make_from', action='store', required = True)
    s_subs['create'].add_argument('-p', '--plan', help = 'plan name', dest = 'rplan', action='store', required = True)
    s_subs['create'].add_argument('-l', '--location', help = 'location name', dest = 'location', action='store', required = True)
    s_subs['create'].add_argument('-k', '--key', help = 'ssh key id', dest='keys', action='store', required = False)
    s_subs['create'].add_argument('-s', '--start', help = 'start after creation', action='store_true', dest='do_start', default = True)

    for act in ['create', 'start', 'stop', 'restart', 'rebuild', 'delete']:
        s_subs[act].add_argument('-b', '--batch', help = 'wait for task to complete', action='store_true', dest='batch', default = False)

    for act in ['create', 'start', 'restart', 'rebuild']:
        s_subs[act].add_argument('--ssh', help='start ssh after scalet operation', dest='ssh_start', action='store_true', default =False)

    # billing

    billing_sub = subp_l['billing'].add_subparsers(help = 'billing information', dest = 'info')

    billing_balance = billing_sub.add_parser('balance', help = 'show balance info')
    billing_payments = billing_sub.add_parser('payments', help = 'show payments info')
    billing_consumption = billing_sub.add_parser('consumption', help = 'show consumption info')
    billing_consumption.add_argument('-s', '--start', help='starting date, formatted YYYT-MM-DD', dest = 'start', action = 'store', required = True)
    billing_consumption.add_argument('-e', '--end', help='ending date, formatted YYYT-MM-DD', dest = 'end', action = 'store', required = True)

    args = argparser.parse_args()
    kwargs = args.__dict__

    # print kwargs

    def get_pretty_table(iterable, header):
        max_len = [len(x) for x in header]
        for row in iterable:
            row = [row] if type(row) not in (list, tuple) else row
            for index, col in enumerate(row):
                if max_len[index] < len(unicode(col)):
                    max_len[index] = len(unicode(col))
        output = ' ' + '-' * (sum(max_len) + 2 + int(len(header)*1.5) ) + '\n'
        output += '| ' + ''.join([h + ' ' * (l - len(h)) + '| ' for h, l in zip(header, max_len)]) + '\n'
        output += ' ' + '-' * (sum(max_len) + 2 + int(len(header)*1.5)) + '\n'
        for row in iterable:
            row = [row] if type(row) not in (list, tuple) else row
            output += '| ' + ''.join([unicode(c) + ' ' * (l - len(unicode(c))) + '| ' for c, l in zip(row, max_len)]) + '\n'
        output += ' ' + '-' * (sum(max_len) + 2 + int(len(header)*1.5)) + '\n'
        return output

    def scalet_by_name_id(vs, name_id):
        scalet = None

        is_name = False

        if not name_id.isdigit():
            is_name = True
        else:
            try:
                scalet = vs.scalets(name_id)
            except urllib2.HTTPError as e:
                if e.code != 404:
                    raise e

                # that means it probably name
                is_name = True
            else:
                is_name = False

        if is_name:
            scalets = vs.scalets()

            for s in scalets:
                if s['name'] == name_id:
                    scalet = s

        return scalet

    def start_ssh(vs, **kwargs):

        ip = kwargs.get('ip', None)
        ctid = kwargs.get('ctid', None)

        if ctid:
            s = vs.scalets(ctid)
            ip = s['public_address']['address']
        os.system('ssh %s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -l root' % ip)

    def wait_scalet_task(vs, **kwargs):
        ctid = int(kwargs.get('ctid'))
        s_task_exists = True

        while s_task_exists:
            tasks = vs.scalets_tasks()
            ctids = [ int(t['scalet']) for t in tasks ]
            if ctid not in ctids:
                s_task_exists = False
                break

            time.sleep(5)

    def save_cache(dir_path, resource, data):
        if dir_path is not None and os.path.exists(dir_path):
            with open('{0}/{1}'.format(dir_path, resource), 'w') as f:
                f.write(json.dumps(data))

    def load_cache(dir_path, resource):
        if os.path.exists('{0}/{1}'.format(dir_path, resource)):
            with open('{0}/{1}'.format(dir_path, resource), 'r') as f:
                return json.loads(f.read())

    def print_scalet(s):

        print '\n' + s['name'] + ': %s' % s['ctid']
        print get_pretty_table([[i, s[i].__str__()] for i in s], ['Attribute', 'Value'])

    def print_tasks(ts):
        if ts is not None and len(ts) > 0:
            print get_pretty_table([ t.values() for t in ts ], ts[0].keys())

    vs = Client(api_url = VSCALE_API_BASE_URL, api_token = vs_api_token)

    if kwargs['resource'] == 'account':
        info = vs[kwargs['resource']]['info']
        print get_pretty_table( [[i, info[i]] for i in info ], ['Attribute', 'Value'] )

    elif kwargs['resource'] not in ['billing', 'scalets', 'account']:
        rs = vs[kwargs['resource']]

        save_cache(VSCALE_DIR, kwargs['resource'], rs)

        if kwargs['resource'] in ['locations', 'images']:

            print get_pretty_table([[i['id'], i['active'], i['description'], ','.join(i['rplans'])] for i in rs], ['id','active','description','rplans'])
        elif kwargs['resource'] in ['rplans']:
            print get_pretty_table([[i['id'], i['disk'], i['memory'], i['cpus'],i['addresses'],','.join(i['locations'])] for i in rs], ['id','disk','memory','cpus','addresses','locations'])
        elif kwargs['resource'] in ['sshkeys']:
            print get_pretty_table([[i['id'], i['name'],i['key'][:50] + '..'] for i in rs], ['id','name','key'])

    elif kwargs['resource'] == 'billing':
        s = vs.billing(**kwargs)

        if kwargs['info'] == 'balance':
            print get_pretty_table([[i, s[i].__str__()] for i in s], ['Attribute', 'Value'])

        elif kwargs['info'] == 'payments':

            p = [ i.values() for i in s['items'] ]

            print get_pretty_table(p, s['items'][0].keys())

        elif kwargs['info'] == 'consumption':

            print get_pretty_table([[i, s[i]['summ']] for i in s], ['scalet id', 'summ'])

    elif kwargs['resource'] == 'scalets':

        if kwargs['action'] in ['ls', 'list']:
            scalets = vs.scalets()

            save_cache(VSCALE_DIR, 'scalets', scalets)

            for s in scalets:
                print_scalet(s)

        elif kwargs['action'] in ['start', 'stop', 'restart', 'rebuild', 'delete']:

            if 'ssh_start' not in kwargs:
                kwargs['ssh_start'] = False

            s = scalet_by_name_id(vs, kwargs['id'])

            if s:

                kwargs['ctid'] = s['ctid']
                func = vs.__getattribute__('scalets_{0}'.format(kwargs['action']))

                s = func(**kwargs)

                if kwargs['batch'] or kwargs['ssh_start']:
                    wait_scalet_task(vs, **s)

                print_scalet(s)

                if 'ssh_start' in kwargs and kwargs['ssh_start']:
                    start_ssh(vs, **{'ctid' : s['ctid']})

        elif kwargs['action'] == 'create':

            if 'keys' in kwargs and kwargs['keys'] is not None:
                kwargs['keys'] = [ int(i) for i in kwargs['keys'].split(',') ]

            s = vs.scalets_create(**kwargs)

            if kwargs['batch'] or kwargs['ssh_start']:
                wait_scalet_task(vs, **s)

            print_scalet(s)

            if kwargs['ssh_start']:
                start_ssh(vs, **{'ctid' : s['ctid']})

        elif kwargs['action'] == 'show':

            s = scalet_by_name_id(vs, kwargs['id'])

            if s:
                print_scalet(s)

        elif kwargs['action'] == 'ssh':

            s = scalet_by_name_id(vs, kwargs['id'])

            if s:
                start_ssh(vs, **s)

        elif kwargs['action'] in ['tasks', 'ps']:

            print_tasks(vs.scalets_tasks())
# Dependent packages
import sys
import pprint as pp

#Local packages for testing
sys.path.append("../")
import config
from api import Client


api_key = config.api_key
private_key = config.private_key
client = Client(api_key, private_key) 

instrument = 'XRP'
currency = 'AUD'
limit = 200
since_order = 1151816479
since_trade = 1151816492
orders = [610067267,610067457]


#Account balance
print('=== Account ==='*5)
response = client.account_balance()
pp.pprint(response)


# Order History
print('=== Order History ==='*5)
response = client.order_history(instrument,currency,limit,since_order)
# Dependent packages
import sys
import pprint as pp

#Local packages for testing
sys.path.append("../")
import config
from api import Client

api_key = config.api_key
private_key = config.private_key
client = Client(api_key, private_key) 

instrument = 'ETH'
currency = 'AUD'
limit = 200
since_order = 0
since_trade = 0
orders = [610067267,610067457]


#Account balance
print('=== Account ==='*5)
response = client.account_balance()
pp.pprint(response)

# Trading Fee
print('=== Trading Fee ==='*5)
response = client.account_trading_fee(instrument,currency)
pp.pprint(response)
示例#10
0
文件: main.py 项目: Samurais/LPan
def main():
    # load config
    config = load_config()
    _consumer_key = ""
    _consumer_secret = ""
    
    if config.has_section('client'):
        _consumer_key = config.get('client', '_consumer_key')
        _consumer_secret = config.get('client', '_consumer_secret')

    # init client
    client = Client(_consumer_key, _consumer_secret)
    
    # auth before use
    auth(client, config)

    if client.is_authed():
        global local_path
        global g_ind
        if config.has_section('sync'):
            local_path = config.get('sync', 'local_path')
        if not local_path:
            home_dir = os.path.expanduser('~')
            default_dir = os.path.join(home_dir, "kuaipan")
            is_create_default = False
            if not os.path.exists(default_dir):
                is_create_default = True
                os.mkdir(default_dir)
            
            dialog = gtk.FileChooserDialog(title="请选择快盘文件同步到本地存放的文件夹", parent=None,
                action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
                buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,gtk.RESPONSE_OK))
            dialog.set_current_folder(default_dir)

            filter = gtk.FileFilter()
            filter.set_name("所有文件夹")
            filter.add_pattern("*")
            dialog.add_filter(filter)            
                
            response = dialog.run()
            if response == gtk.RESPONSE_OK:
                print dialog.get_filename(), 'selected'
                local_path = dialog.get_filename()
                if is_create_default and local_path != default_dir:
                    os.rmdir(default_dir)
                config.add_section('sync')
                config.set('sync', 'local_path', local_path)
                fp = open(get_cfg_path(), 'w')
                config.write(fp)                    
            else:
                print 'Closed, no files selected'
            dialog.destroy()

        if not local_path:
            return

        ac_info = client.get_account_info()
        print('is authed')
        print(ac_info)
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        g_ind = init_indicator(ac_info, client)

        # start sync thread
        start_sync(client, local_path, g_ind)
        
        # start monitor thread
        start_monitor(client, local_path, g_ind)
        
        # start run application
        gtk.main()
    else:
        print('not authed')
示例#11
0
        api = config.get_api(globals.options.profile_name)
        globals.options.api = api

    if globals.options.username:
        username = globals.options.username
    else:
        username = config.get_username(globals.options.profile_name)
        globals.options.username = username

    if globals.options.password:
        password = globals.options.password
    else:
        password = config.get_password(globals.options.profile_name)
        globals.options.password = password

    client = Client(api, username, password, globals.options.insecure)

    entity_args = [] + globals.options.subentities

    if not globals.options.action is None:
        entity_args.append(globals.options.action)

    _dispatch(globals.options.entity, entity_args, client)

def _dispatch(entity, args, client):
    options = globals.options

    try:
        control.router.dispatch(entity, client, args)
        exit(0)
    except ControllerException as e:
示例#12
0
    def setUp(self):
        self.sclient = Client(SPREEDLY_AUTH_TOKEN_SECRET, SPREEDLY_SITE_NAME)

        # Remove all subscribers
        self.sclient.cleanup()
示例#13
0
class  TestCase(unittest.TestCase):
    def setUp(self):
        self.sclient = Client(SPREEDLY_AUTH_TOKEN_SECRET, SPREEDLY_SITE_NAME)

        # Remove all subscribers
        self.sclient.cleanup()

    def tearDown(self):
        # Remove all subscribers
        self.sclient.cleanup()

    def test_get_plans(self):
        keys = [
            'date_changed', 'terms', 'name', 'force_recurring', 'feature_level',
            'price', 'enabled', 'plan_type', 'force_renew', 'duration_units',
            'version', 'speedly_site_id', 'duration', 'created_at',
            'speedly_id', 'return_url', 'description'
        ]

        for plan in self.sclient.get_plans():
            self.assertEquals(plan.keys(), keys)

    def test_create_subscriber(self):
        keys = set([
            'token', 'active_until', 'trial_active', 'created_at',
            'active', 'lifetime', 'customer_id', 'date_changed',
            'trial_elegible', 'plan', 'card_expires_before_next_auto_renew'
        ])

        subscriber = self.sclient.create_subscriber(1, 'test')
        self.assertEquals(set(subscriber.keys()), keys)

        # Delete subscriber
        self.sclient.delete_subscriber(1)

    def test_subscribe(self):
        keys = set([
            'token', 'active_until', 'trial_active', 'created_at',
            'active', 'lifetime', 'customer_id', 'date_changed',
            'trial_elegible', 'plan', 'card_expires_before_next_auto_renew'
        ])

        # Create a subscriber first
        subscriber = self.sclient.create_subscriber(1, 'test')

        # Subscribe to a free trial
        subscription = self.sclient.subscribe(1, 1824, True)
        self.assertEquals(set(subscriber.keys()), keys)
        assert subscription['trial_active']

        # Delete subscriber
        #self.sclient.delete_subscriber(1)

    def test_delete_subscriber(self):
        self.sclient.create_subscriber(1, 'test')
        self.failUnlessEqual(self.sclient.delete_subscriber(1), 200)

    def test_get_info(self):
        keys = set([
            'token', 'active_until', 'trial_active', 'created_at',
            'active', 'lifetime', 'customer_id', 'date_changed',
            'trial_elegible', 'plan', 'card_expires_before_next_auto_renew'
        ])

        self.sclient.create_subscriber(1, 'test')
        subscriber = self.sclient.get_info(1)
        self.assertEquals(set(subscriber.keys()), keys)
        self.assertEquals(subscriber['email'], '')
        self.assertEquals(subscriber['screen_name'], 'test')
        
        
        self.sclient.set_info(1, email='*****@*****.**', screen_name='jb')
        subscriber = self.sclient.get_info(1)
        self.assertEquals(subscriber['email'], '*****@*****.**')
        self.assertEquals(subscriber['screen_name'], 'jb')

        
    def test_get_or_create(self):
        keys = set([
            'token', 'active_until', 'trial_active', 'created_at',
            'active', 'lifetime', 'customer_id', 'date_changed',
            'trial_elegible', 'plan', 'card_expires_before_next_auto_renew'
        ])
        #test non existent subscriber
        result = self.sclient.get_or_create_subscriber(123, 'tester')
        self.assertEquals(set(result.keys()), keys)
        
        #assure that we won't overwrite existing subscriber
        result2 = self.sclient.get_or_create_subscriber(123, 'tester2')
        self.assertEquals(result, result2)
        
        
    def test_comp_subscription(self):
        result = self.sclient.get_or_create_subscriber(123, 'tester')

        self.sclient.create_complimentary_subscription(123, 2, 'months', 'Pro')
示例#14
0
    if DEBUG:
        file_handler = logging.FileHandler('debug.log', encoding='utf-8')
        file_handler.setLevel(logging.DEBUG)
        file_formatter = logging.Formatter(
            '%(asctime)s %(name)-8s %(levelname)-8s %(message)s',
            datefmt='%d-%m-%y %H:%M:%S',
        )
        file_handler.setFormatter(file_formatter)
        logger.addHandler(file_handler)
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_formatter = logging.Formatter(
        '%(asctime)s %(levelname)-7s %(message)s',
        datefmt='%H:%M:%S',
    )
    console_handler.setFormatter(console_formatter)
    logger.addHandler(console_handler)

    client = Client(token)
    bot = Bot(client, steamid32)

    try:
        bot.run()
    except KeyboardInterrupt:
        print('exiting...')
        sys.exit(0)
示例#15
0
class ClientTestExceptions(unittest.TestCase):
    def setUp(self):
        start_server()
        self.client = Client('localhost:5001')

    def tearDown(self):
        stop_server()

    def test_server_up(self):
        r = self.client.get('/test')
        self.assertEqual(r, {'api': 'test', 'version': '1.0'})

    def test_server_down(self):
        self.tearDown()
        with self.assertRaises(requests.exceptions.ConnectionError):
            self.client.get('/test')

    def test_GET_401(self):
        with self.assertRaises(requests.exceptions.HTTPError):
            self.client.auth.get()

    def test_GET_404(self):
        with self.assertRaises(requests.exceptions.HTTPError):
            self.client.get('/nopage')

    def test_GET_CRUD_ResourceNotFound(self):
        with self.assertRaisesRegexp(requests.exceptions.HTTPError, 'ResourceNotFound'):
            self.client.users.get(1)

    def test_GET_CRUD_FilterInvalid(self):
        with self.assertRaisesRegexp(requests.exceptions.HTTPError, 'FilterInvalid'):
            self.client.users.get(match=['this is an invalid filter'])

    def test_CREATE_CRUD_NoPostData(self):
        with self.assertRaisesRegexp(requests.exceptions.HTTPError, 'NoPostData: No data in POST request.'):
            self.client.users.create()

    def test_CREATE_CRUD_SchemaValidationError(self):
        with self.assertRaisesRegexp(requests.exceptions.HTTPError, 'SchemaValidationError'):
            self.client.users.create(unknown='try')
            self.client.users.create(first_name='Owen')
            self.client.users.create(first_name='Owen', last_name='MacDonalds')

    def test_CREATE_CRUD_200(self):
        self.client.users.create([
            {
                'username': '******',
                'first_name': 'Frank',
                'last_name': 'Karal'
            },
            {
                'username': '******',
                'first_name': 'Owen',
                'last_name': "Mc Donald's"
            }
        ])

    def test_GET_CRUD_200(self):
        self.client.users.create([
            {
                'username': '******',
                'first_name': 'Frank',
                'last_name': 'Karal'
            },
        ])
        user = self.client.users.get('Frankie')
        self.assertEqual(user['username'], 'Frankie')
        self.assertEqual(user['first_name'], 'Frank')
        self.assertEqual(user['last_name'], 'Karal')
示例#16
0
 def setUp(self):
     start_server()
     self.client = Client('localhost:5001')
示例#17
0
class TestCase(unittest.TestCase):
    subscriber_keys = set([
        'active', 'active_until', 'card_expires_before_next_auto_renew',
        'created_at', 'customer_id', 'date_changed', 'email', 'first_name',
        'feature_level', 'gift', 'last_name', 'lifetime', 'name', 'recurring',
        'screen_name', 'token', 'trial_active', 'trial_eligible', #'plan',
    ])
    plans = []

    def setUp(self):
        self.sclient = Client(SPREEDLY_AUTH_TOKEN, SPREEDLY_SITE_NAME)

        # Remove all subscribers
        self.sclient.cleanup()

    def tearDown(self):
        # Remove all subscribers
        self.sclient.cleanup()

    def test_get_plans(self):
        keys = set([
            'date_changed', 'terms', 'name', 'force_recurring', 'feature_level',
            'price', 'enabled', 'plan_type', 'force_renew', 'duration_units',
            'version', 'spreedly_site_id', 'duration', 'created_at',
            'spreedly_id', 'return_url', 'description'
        ])

        for plan in self.sclient.get_plans():
            self.assertEquals(set(plan.keys()), keys)
            self.plans.append(plan)

    def test_create_subscriber(self):
        subscriber = self.sclient.create_subscriber(1, 'test')
        self.assertEquals(set(subscriber.keys()), self.subscriber_keys)

        # Delete subscriber
        self.sclient.delete_subscriber(1)

    def test_subscribe_free_trial(self):
        # Create a subscriber first
        subscriber = self.sclient.create_subscriber(1, 'test')

        # Subscribe to a free trial
        if not self.plans:
            self.plans = self.sclient.get_plans()
        for plan in self.plans:
            if plan['enabled'] and plan['plan_type'] == 'free_trial':
                break
        else:
            raise Exception("You need to set an active free-trial plan on your spreedly.com account.")
        plan_id = plan['spreedly_id']
        subscription = self.sclient.subscribe(1, plan_id, True)
        self.assertEquals(set(subscriber.keys()), self.subscriber_keys)
        assert subscription['trial_active']

        # Delete subscriber
        self.sclient.delete_subscriber(1)

    def test_delete_subscriber(self):
        self.sclient.create_subscriber(1, 'test')
        self.failUnlessEqual(self.sclient.delete_subscriber(1), 200)

    def test_get_info(self):
        self.sclient.create_subscriber(1, 'test')
        subscriber = self.sclient.get_info(1)
        self.assertEquals(set(subscriber.keys()), self.subscriber_keys)
        self.assertEquals(subscriber['email'], '')
        self.assertEquals(subscriber['screen_name'], 'test')

        self.sclient.set_info(1, email='*****@*****.**', screen_name='jb')
        subscriber = self.sclient.get_info(1)
        self.assertEquals(subscriber['email'], '*****@*****.**')
        self.assertEquals(subscriber['screen_name'], 'jb')

    def test_get_or_create(self):
        #test non existent subscriber
        result = self.sclient.get_or_create_subscriber(123, 'tester')
        self.assertEquals(set(result.keys()), self.subscriber_keys)

        #assure that we won't overwrite existing subscriber
        result2 = self.sclient.get_or_create_subscriber(123, 'tester2')
        self.assertEquals(result, result2)

    def test_comp_subscription(self):
        result = self.sclient.get_or_create_subscriber(123, 'tester')

        self.sclient.create_complimentary_subscription(123, 2, 'months', 'Pro')