Example #1
0
 def test_create_single_file_nofile(self):
     '''Test create_single_file()
     '''
     rootdir = random_string(16)
     path_a = os.path.join(rootdir, 'a')
     with self.assertRaises(IOError):
         entree.utils.create_single_file(path_a, '', '')
Example #2
0
def authorize(client_id, client_secret, config):
    """
    A module method to authorize Spotify using a OAuth client ID and client
    secret.
    """
    state = util.random_string(14)
    scope = 'playlist-modify-private'
    authorization_url = '{}?client_id={}&response_type=code'.format(
        REQUEST_TOKEN_URL,
        client_id
    )
    authorization_url += '&redirect_uri={}&state={}&scope={}'.format(
        CALLBACK_URI,
        state,
        scope
    )

    if config.verbose:
        util.debug('Authorization URL constructed: {}'.format(authorization_url))

    # Prompt the user to authorize via a browser:
    util.info('Now opening a browser to authorize your Spotify account.')
    util.info('Once authorized, copy/paste the URL of that browser window here.')
    util.info('Finally, hit enter to complete the auhtorization process.')
    util.confirm('Do you want to continue?')
    util.open_url(authorization_url)

    # Deal with the return code:
    authorization_response = util.prompt('Enter the URL', None)
    parsed = urlparse.urlparse(authorization_response)
    authorization_args = urlparse.parse_qs(parsed.query)

    if config.verbose:
        util.debug('Authorization arguments: {}'.format(authorization_args))

    # Check to make sure the states between request and response match:
    if state == authorization_args.get('state')[0]:
        if 'code' in authorization_args:
            # The authorization succeeded:
            params = {
                'client_id': client_id,
                'client_secret': client_secret,
                'grant_type': 'authorization_code',
                'code': authorization_args.get('code')[0],
                'redirect_uri': CALLBACK_URI
            }
            r = requests.post(ACCESS_TOKEN_URL, data=params)

            if config.verbose:
                util.debug('Access response: {}'.format(r.content))

            return r.json()
        else:
            # The authorization failed:
            if 'error' in authorization_args:
                raise music_service.AuthorizationError(authorization_args.get('error')[0])
            else:
                raise music_service.AuthorizationError('unknown authorization error')
    else:
        raise SpotifyStateError()
Example #3
0
 def test_rootdir_doesntexist(self):
     '''`entree python -d blah -s blah.py`
     should raise an error if directory blah doesn't exist.
     '''
     rootdir = random_string(16)
     code = run_command('entree python -d {0} blah'.format(rootdir))
     self.assertEqual(code, 1)
 def test_rootdir_doesntexist(self):
     '''`entree python -d blah -s blah.py`
     should raise an error if directory blah doesn't exist.
     '''
     rootdir = random_string(16)
     code = run_command('entree python -d {0} blah'.format(rootdir))
     self.assertEqual(code, 1)
 def generante_storage_url_job(file_path, preferred_format, bot, user):
     try:
         secretUrl, file_id, owner_token = upload.send_file(
             'https://send.firefox.com/',
             open(file_path, 'rb'),
             ignoreVersion=False,
             fileName='{}.{}'.format(utils.random_string(32),
                                     preferred_format))
         delete_button = InlineKeyboardMarkup([[
             InlineKeyboardButton(
                 CronJobManager.lang[user.language_code]['delete_url'],
                 callback_data=str({
                     'cmd': CallbackCommand.remove_url.value,
                     'id': file_id,
                     'own': owner_token
                 }))
         ]])
         bot.send_message(chat_id=user.id,
             text=CronJobManager.lang[user.language_code]['url_send'] \
                 .format(secretUrl),
             disable_web_page_preview=True,
             parse_mode=ParseMode.HTML,
             reply_markup=delete_button
         )
     except:
         bot.send_message(chat_id=user.id,
             text=CronJobManager.lang[user.language_code] \
                 ['error_generate_url'].format(secretUrl),
         )
Example #6
0
def add_patient_answers(answers):
    """
    Inserts new answers from a patient.
    :param answers: patient answers
    :param session: current session
    :return: patient with anonymous name
    """

    session = init()

    new_answers = []

    for key in answers.keys():
        new_answers.append(answers[key])

    new_entity = Entity(name=random_string(get_all_entities()), type="patient")
    new_patient = Patient(date_of_birth="11.11.11", entity=new_entity)
    new_address = Address(post_code="1337", entity=new_entity)

    session.add(new_address)
    session.add(new_patient)
    session.add(new_entity)

    for answer in answers:
        q = session.query(Question).filter(Question.id == answer).first()
        if q is not None:
            try:
                new_score = Score(entity=new_entity, question=q, score=answers[answer])
                session.add(new_score)
                session.commit()
            except:
                session.rollback()
                print("Error: Could not save patient scores to database")

    return new_entity.name
Example #7
0
 def test_default_projtype_toomany_args(self):
     '''check status code of `entree blah blah`
     '''
     modname = random_string(16)
     code = run_command('entree {0} {0}'.format(modname))
     self.assertEqual(code, 6)
     if os.path.exists(modname):
         shutil.rmtree(modname)
 def test_no_projtype_single(self):
     '''check status code of `entree blah.py -s`
     '''
     modname = random_string(16)
     code = run_command('entree {0} -s'.format(modname))
     self.assertEqual(code, 0)
     if os.path.exists(modname):
         os.remove(modname)
Example #9
0
def make_payload(size):
    wrapper_overhead = len(json.dumps(minimum_payload))
    if size == 0:
        return zero_size_payload
    elif size <= wrapper_overhead:
        return minimum_payload
    else:
        return {"payload": random_string(length=size - wrapper_overhead - 7)}
Example #10
0
 def test_create_general_file_nofile(self):
     '''Test create_dirs()
     '''
     rootdir = random_string(16)
     path_a = os.path.join(rootdir, 'a')
     with self.assertRaises(IOError):
         entree.utils.create_general_file(path_a, "AAAAA")
     self.assertFalse(os.path.exists(path_a))
Example #11
0
 def test_default_projtype_toomany_args(self):
     '''check status code of `entree blah blah`
     '''
     modname = random_string(16)
     code = run_command('entree {0} {0}'.format(modname))
     self.assertEqual(code, 6)
     if os.path.exists(modname):
         shutil.rmtree(modname)
Example #12
0
 def test_no_projtype_single(self):
     '''check status code of `entree blah.py -s`
     '''
     modname = random_string(16)
     code = run_command('entree {0} -s'.format(modname))
     self.assertEqual(code, 0)
     if os.path.exists(modname):
         os.remove(modname)
Example #13
0
 def test_no_projtype_dir(self):
     '''check status code of `entree blah.py -d blah`
     '''
     with TMPFile() as rootdir:
         modname = random_string(16)
         code = run_command('entree {0} -d {1}'.format(modname, rootdir))
         self.assertEqual(code, 0)
         if os.path.exists(modname):
             os.remove(modname)
Example #14
0
 def test_simple(self):
     '''check status code of `entree python blah`
     '''
     for project_cls in CLSNAMES:
         modname = random_string(16)
         code = run_command('entree {0} {1}'.format(project_cls, modname))
         self.assertEqual(code, 0)
         if os.path.exists(modname):
             shutil.rmtree(modname)
Example #15
0
 def test_no_projtype_dir(self):
     '''check status code of `entree blah.py -d blah`
     '''
     with TMPFile() as rootdir:
         modname = random_string(16)
         code = run_command('entree {0} -d {1}'.format(modname, rootdir))
         self.assertEqual(code, 0)
         if os.path.exists(modname):
             os.remove(modname)
Example #16
0
 def test_simple(self):
     '''check status code of `entree python blah`
     '''
     for project_cls in CLSNAMES:
         modname = random_string(16)
         code = run_command('entree {0} {1}'.format(project_cls, modname))
         self.assertEqual(code, 0)
         if os.path.exists(modname):
             shutil.rmtree(modname)
Example #17
0
 def test_add(self):
     '''check status code of `entree python -a -d rootdir blah`
     '''
     for project_cls in CLSNAMES:
         modname = random_string(16)
         with TMPFile() as rootdir:
             cmd = 'entree {0} -a -d {1} {2}'.format(project_cls, rootdir,
                                                     modname)
             code = run_command(cmd)
             self.assertEqual(code, 0)
Example #18
0
 def test_add(self):
     '''check status code of `entree python -a -d rootdir blah`
     '''
     for project_cls in CLSNAMES:
         modname = random_string(16)
         with TMPFile() as rootdir:
             cmd = 'entree {0} -a -d {1} {2}'.format(
                 project_cls, rootdir, modname)
             code = run_command(cmd)
             self.assertEqual(code, 0)
Example #19
0
    def test_random_string(self):
        import string

        self.assertEqual(len(utilities.random_string(15)), 15)

        self.assertEqual(utilities.random_string(5, ['a']), 'aaaaa')

        # Verify distribution is reasonably random
        letter_frequencies = collections.defaultdict(lambda: 0)

        for _ in range(1, 10000):
            for letter in utilities.random_string(16):
                letter_frequencies[letter] += 1

        standard_deviation = self.__standard_deviation(
            letter_frequencies.values())

        self.assertLessEqual(
            standard_deviation, 100,
            "Standard deviation of letter frequency is too high!  Are you sure it is random?"
        )
Example #20
0
 def test_single(self):
     '''check status code of `entree python -s blah`
     '''
     for project_cls in CLASSES:
         clsname = project_cls.__name__.lower()
         modname = random_string(16)
         cmd = 'entree {0} -s {1}'.format(clsname, modname)
         if project_cls.single_file:
             code = run_command(cmd)
             self.assertEqual(code, 0)
         if os.path.exists(modname):
             os.remove(modname)
Example #21
0
 def test_single(self):
     '''check status code of `entree python -s blah`
     '''
     for project_cls in CLASSES:
         clsname = project_cls.__name__.lower()
         modname = random_string(16)
         cmd = 'entree {0} -s {1}'.format(clsname, modname)
         if project_cls.single_file:
             code = run_command(cmd)
             self.assertEqual(code, 0)
         if os.path.exists(modname):
             os.remove(modname)
Example #22
0
 def test_create_dirs_norootdir(self):
     '''Test create_dirs()
     '''
     rootdir = random_string(16)
     path_a = os.path.join(rootdir, 'a')
     path_b = os.path.join(rootdir, 'b')
     path_c = os.path.join(rootdir, 'c')
     with self.assertRaises(IOError):
         entree.utils.create_dirs(rootdir, path_a, path_b, path_c)
     self.assertFalse(os.path.exists(rootdir))
     self.assertFalse(os.path.exists(path_a))
     self.assertFalse(os.path.exists(path_b))
     self.assertFalse(os.path.exists(path_c))
def make_message_payload(size=64):
    """
    make a random message payload with the given size
    """
    wrapper_overhead = len(json.dumps({"payload": ""}))
    if size == 0:
        return zero_size_payload
    elif size <= wrapper_overhead:
        return minimum_payload
    else:
        return {
            "payload": utilities.random_string(length=size - wrapper_overhead)
        }
Example #24
0
 def test_partial2(self):
     '''check status code of `entree python -d dir -p partial blah`
     Status should be 1 if there is no `partial_builds` in the project
     config or if the partial name does not exist in `partial_builds`,
     should be 0 otherwise.
     '''
     for project_cls in CLASSES:
         clsname = project_cls.__name__.lower()
         modname = random_string(16)
         with TMPFile() as rootdir:
             config = project_cls.get_config()
             if 'partial_builds' in config:
                 cmd = 'entree {0} -d {1} -p {2} {2}'.format(
                     clsname, rootdir, modname)
                 code = run_command(cmd)
                 self.assertEqual(code, 1)
Example #25
0
 def test_partial2(self):
     '''check status code of `entree python -d dir -p partial blah`
     Status should be 1 if there is no `partial_builds` in the project
     config or if the partial name does not exist in `partial_builds`,
     should be 0 otherwise.
     '''
     for project_cls in CLASSES:
         clsname = project_cls.__name__.lower()
         modname = random_string(16)
         with TMPFile() as rootdir:
             config = project_cls.get_config()
             if 'partial_builds' in config:
                 cmd = 'entree {0} -d {1} -p {2} {2}'.format(
                     clsname, rootdir, modname
                 )
                 code = run_command(cmd)
                 self.assertEqual(code, 1)
Example #26
0
    def setUp(self):
        '''Create a fake file structure to test
        '''
        self.template_dir = random_string(16)
        os.makedirs(self.template_dir)

        self.path_a = os.path.join(self.template_dir, 'a')
        self.path_b = os.path.join(self.template_dir, 'b')
        self.path_c = os.path.join(self.template_dir, 'c')

        entree.utils.create_dirs(self.template_dir, self.path_a, self.path_b,
                                 self.path_c)

        self.file_a = os.path.join(self.path_a, 'a.txt')
        self.file_b = os.path.join(self.path_b, 'b.md')
        self.file_c = os.path.join(self.path_c, 'c_py.template')

        entree.utils.create_general_file(self.file_a, "My name is")
        entree.utils.create_general_file(self.file_b, "{{ name }}")
        entree.utils.create_general_file(self.file_c,
                                         "I'm {{ blah['age'] }} years old.")
Example #27
0
def test_string():
    return random_string("String1")
Example #28
0
 def setUp(self):
     '''Setting up
     '''
     self.modname = random_string(16)
 def blob_name(self):
     return utilities.random_string()
Example #30
0
 def setUp(self):
     '''Setting up
     '''
     self.modname = random_string(16)
Example #31
0
def next_random_string(prefix):
    global string_index
    string_index = string_index + 1
    return random_string("{} {}".format(prefix, string_index))
Example #32
0
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for
# full license information.

from utilities import random_string
import pytest
import json

string_1K = random_string(prefix="1K-chars", length=1024)
string_64K = random_string(prefix="64K-chars", length=64 * 1024)
object_with_3_layers = {
    "layer_1_string": random_string("1"),
    "layer_2": {
        "layer_2_string": random_string("2"),
        "layer3": {"fake_number": 3, "fake_real_number": 1.87},
    },
}

telemetry_test_objects = [
    pytest.param(string_1K, id="1K character string"),
    pytest.param(string_64K, id="64k character string"),
    pytest.param(object_with_3_layers, id="object with 3 layers"),
]
Example #33
0
def test_string_2():
    return random_string("String2")