Exemplo n.º 1
0
 def test_raise_exception_purchase_insert_SQLAlchemy_session(self):
     """Tests Exception raise of Purchase instance insertion without a referenced Foreign Key
     Takes a dummy purchase and inserts it in the db
     :return:
     """
     test_purchase = get_dummy_purchase()
     db.session.add(test_purchase)
     TestCase.assertRaises(self, IntegrityError, db.session.commit)
Exemplo n.º 2
0
    def tearDownClass(cls):
        if cls.TEST_INSTANCE_PATH:
            tmp_dir = Path(cls.TEST_INSTANCE_PATH)
            basename = tmp_dir.name
            if tmp_dir.is_dir() and basename.startswith('tmp-py-unittest'):
                shutil.rmtree(cls.TEST_INSTANCE_PATH)
                cls.TEST_INSTANCE_PATH = None

        TestCase.tearDownClass()
Exemplo n.º 3
0
  def tearDownClass(cls):
    if cls.TEST_INSTANCE_PATH:
      tmp_dir = Path(cls.TEST_INSTANCE_PATH)
      basename = tmp_dir.name
      if tmp_dir.is_dir() and basename.startswith('tmp-py-unittest'):
        shutil.rmtree(cls.TEST_INSTANCE_PATH)
        cls.TEST_INSTANCE_PATH = None

    TestCase.tearDownClass()
Exemplo n.º 4
0
 def test_raise_exception_purchase_foreign_key_purchase_item_insert(self):
     """Tests Exception raise in Purchase Item instance insertion
     Takes a dummy purchase item and inserts it in the db without any referenced Foreign Key on Purchase.
     :return:
     """
     test_purchase_item = get_dummy_purchase_item()
     test_product = get_dummy_product()
     db.session.add(test_product)
     db.session.add(test_purchase_item)
     TestCase.assertRaises(self, IntegrityError, db.session.commit)
Exemplo n.º 5
0
  def setUpClass(cls):
    TestCase.setUpClass()

    if not isinstance(cls.SERVICES, tuple):
      if isinstance(cls.SERVICES, string_types):
        cls.SERVICES = (cls.SERVICES,)
      else:
        cls.SERVICES = tuple(cls.SERVICES)

    tmp_dir = Path(tempfile.mkdtemp(prefix='tmp-py-unittest-',
                                    suffix='-' + cls.__name__,))
    cls.TEST_INSTANCE_PATH = str(tmp_dir)
    for p in (tmp_dir/'tmp', tmp_dir/'cache', tmp_dir/'data'):
      p.mkdir()

    sa_warn = 'error' if cls.SQLALCHEMY_WARNINGS_AS_ERROR else 'default'
    warnings.simplefilter(sa_warn, SAWarning)
Exemplo n.º 6
0
    def tearDown(self):
        for svc in self.SERVICES:
            svc = self.app.services[svc]
            if svc.running:
                svc.stop()

        self.db.session.remove()

        with self.db.engine.connect() as conn:
            if self.db.engine.name == 'postgresql':
                username = self.db.engine.url.username or getpass.getuser()
                with self.db.engine.connect() as conn:
                    with conn.begin():
                        conn.execute(
                            'ALTER ROLE {username} SET search_path TO public'
                            ''.format(username=username))
                        conn.execute('SET search_path TO public')
                        conn.execute('DROP SCHEMA IF EXISTS {} CASCADE'.format(
                            self.__pg_schema))
                    conn.execute('COMMIT')
                del self.__pg_schema
            else:
                if self.db.engine.name == 'sqlite':
                    # core.extension.sqlalchemy performs a 'PRAGMA foreign_keys=ON' on a
                    # connection listener.
                    #
                    # We must revert it to perform drop_all without ever encounting a
                    # foreign key error
                    conn.execute("PRAGMA foreign_keys=OFF;")

                self.db.metadata.drop_all(bind=conn)

        self.db.engine.dispose()
        self.app.services['session_repository'].stop()
        self.app.services['repository'].stop()

        User.__password_strategy__ = _DEFAULT_PWD

        # Resets babel extension
        babel = self.app.extensions['babel']
        babel.locale_selector_func = None
        babel.timezone_selector_func = None

        TestCase.tearDown(self)
Exemplo n.º 7
0
    def tearDown(self):
        self._stop_services()

        self.db.session.remove()

        with self.db.engine.connect() as conn:
            if self.db.engine.name == 'postgresql':
                username = self.db.engine.url.username or getpass.getuser()
                with self.db.engine.connect() as conn2:
                    with conn2.begin():
                        conn2.execute(
                            'ALTER ROLE {username} SET search_path TO public'
                            ''.format(username=username), )
                        conn2.execute('SET search_path TO public')
                        conn2.execute(
                            'DROP SCHEMA IF EXISTS {} CASCADE'.format(
                                self.__pg_schema, ))
                    conn2.execute('COMMIT')
                del self.__pg_schema
            else:
                if self.db.engine.name == 'sqlite':
                    # core.extension.sqlalchemy performs a 'PRAGMA foreign_keys=ON' on a
                    # connection listener.
                    #
                    # We must revert it to perform drop_all without ever encounting a
                    # foreign key error
                    conn.execute("PRAGMA foreign_keys=OFF;")

                self.db.metadata.drop_all(bind=conn)

        self.db.engine.dispose()
        self.app.services['session_repository'].stop()
        self.app.services['repository'].stop()

        User.__password_strategy__ = _DEFAULT_PWD

        self._reset_babel_extension()

        TestCase.tearDown(self)
Exemplo n.º 8
0
    def setUp(self):
        TestCase.setUp(self)

        User.__password_strategy__ = _CLEAR_PWD if self.CLEAR_PASSWORDS else _DEFAULT_PWD

        if not self.TESTING_BUILD_ASSETS:
            extensions = self.app.jinja_env.extensions
            assets_ext = extensions['webassets.ext.jinja2.AssetsExtension']
            assets_ext.BundleClass = NullBundle

        # session_repository must be started before session is created, as it must
        # receive all transactions events. It also requires 'repository'.
        self.app.services['repository'].start()
        self.app.services['session_repository'].start()
        self.session = self.db.session()

        if self.db.engine.name == 'postgresql':
            # ensure we are on a clean DB: let's use our own schema
            self.__pg_schema = 'test_{}'.format(str(time()).replace('.', '_'))
            username = self.db.engine.url.username or getpass.getuser()
            with self.db.engine.connect() as conn:
                with conn.begin():
                    conn.execute('DROP SCHEMA IF EXISTS {} CASCADE'.format(
                        self.__pg_schema))
                    conn.execute('CREATE SCHEMA {}'.format(self.__pg_schema))
                    conn.execute('SET search_path TO {}'.format(
                        self.__pg_schema))
                    conn.execute(
                        'ALTER ROLE {username} SET search_path TO {schema}'
                        ''.format(
                            username=username, schema=self.__pg_schema))
                conn.execute('COMMIT')

        self.app.create_db()

        for svc in self.SERVICES:
            svc = self.app.services[svc]
            if not svc.running:
                svc.start()
Exemplo n.º 9
0
  def tearDown(self):
    for svc in self.SERVICES:
      svc = self.app.services[svc]
      if svc.running:
        svc.stop()

    self.db.session.remove()

    with self.db.engine.connect() as conn:
      if self.db.engine.name == 'postgresql':
        username = self.db.engine.url.username
        with self.db.engine.connect() as conn:
          with conn.begin():
            conn.execute('ALTER ROLE {username} SET search_path TO public'
                         ''.format(username=username))
            conn.execute('SET search_path TO public')
            conn.execute('DROP SCHEMA IF EXISTS {} CASCADE'.format(self.__pg_schema))
          conn.execute('COMMIT')
        del self.__pg_schema
      else:
        if self.db.engine.name == 'sqlite':
          # core.extension.sqlalchemy performs a 'PRAGMA foreign_keys=ON' on a
          # connection listener.
          #
          # We must revert it to perform drop_all without ever encounting a
          # foreign key error
          conn.execute("PRAGMA foreign_keys=OFF;")

        self.db.metadata.drop_all(bind=conn)

    self.db.engine.dispose()
    self.app.services['session_repository'].stop()
    self.app.services['repository'].stop()

    User.__password_strategy__ = _DEFAULT_PWD

    TestCase.tearDown(self)
Exemplo n.º 10
0
  def setUp(self):
    TestCase.setUp(self)

    User.__password_strategy__ = _CLEAR_PWD if self.CLEAR_PASSWORDS else _DEFAULT_PWD

    if not self.TESTING_BUILD_ASSETS:
      extensions = self.app.jinja_env.extensions
      assets_ext = extensions['webassets.ext.jinja2.AssetsExtension']
      assets_ext.BundleClass = NullBundle

    # session_repository must be started before session is created, as it must
    # receive all transactions events. It also requires 'repository'.
    self.app.services['repository'].start()
    self.app.services['session_repository'].start()
    self.session = self.db.session()

    if self.db.engine.name == 'postgresql':
      # ensure we are on a clean DB: let's use our own schema
      self.__pg_schema = 'test_{}'.format(str(time()).replace('.', '_'))
      username = self.db.engine.url.username
      with self.db.engine.connect() as conn:
        with conn.begin():
          conn.execute('DROP SCHEMA IF EXISTS {} CASCADE'.format(self.__pg_schema))
          conn.execute('CREATE SCHEMA {}'.format(self.__pg_schema))
          conn.execute('SET search_path TO {}'.format(self.__pg_schema))
          conn.execute(
            'ALTER ROLE {username} SET search_path TO {schema}'
            ''.format(username=username, schema=self.__pg_schema))
        conn.execute('COMMIT')

    self.app.create_db()

    for svc in self.SERVICES:
      svc = self.app.services[svc]
      if not svc.running:
        svc.start()
Exemplo n.º 11
0
 def test_redirect_shortlink_ok(self):
     self.setUp()
     import app.models.dynamo_db as dynamo_db  # pylint: disable=import-outside-toplevel
     with patch.object(dynamo_db,
                       'get_dynamodb_table',
                       return_value=self.__fake_get_dynamo_db()):
         for shortid, url in self.uuid_to_url_dict.items():
             response = self.app.get(
                 f"/v4/shortlink/shortlinks/{shortid}?redirect=true",
                 content_type="text/html",
                 headers={"Origin": "map.geo.admin.ch"})
             self.assertEqual(response.status_code, 301)
             self.assertEqual(response.content_type,
                              "text/html; charset=utf-8")
             TestCase().assertRedirects(response, url)
Exemplo n.º 12
0
 def __init__(self, *args, **kwargs):
     TestCase.__init__(self, *args, **kwargs)
Exemplo n.º 13
0
        for i in range(num):
            # 随机生成key
            name = "".join(random.sample(string.ascii_letters, 8))
            type = "".join(random.sample(string.ascii_letters, 8))
            resp = self.client.post(url_for('admin.createkey'),
                                    data={
                                        'appname': name,
                                        'apptype': type
                                    })
            self.assert200(resp, message='create key fail')
            res = json.loads(resp.data)
            self.assertEqual('kiton', res['user'])
            keys.append(res)
        return keys

    # 随机产生一个curl命令
    def random_createcmd(self, keys):
        choice_key = random.choice(keys)
        command = "curl -o /dev/null -s "
        out_format = "-w %{time_connect},%{time_total} "
        test_url = "http://localhost:12480/image/v1/mean "
        value = "-F 'api_key={key}' -F 'api_secret={secret}' -F 'image={img}'".format(
            key=choice_key.get('api_key'),
            secret=choice_key.get('api_secret'),
            img='./darnet/data/dog.jpg')
        return command + out_format + test_url + value


if __name__ == '__main__':
    TestCase.main()
Exemplo n.º 14
0
 def __init__(self, *args, specification_dir: str,
              requested_logging_path: str, **kwargs):
     TestCase.__init__(self, *args, **kwargs)
     self._specification_dir = specification_dir
     self.__requested_logging_path = requested_logging_path
Exemplo n.º 15
0
 def setUp(self):
     BaseTestCase.setUp(self)
     os.environ.update(self._set_environ())
Exemplo n.º 16
0
 def setUp(self):
     TestCase.setUp(self)
     db.create_all()
Exemplo n.º 17
0
 def tearDown(self):
     TestCase.tearDown(self)
     db.session.remove()
     db.drop_all()
Exemplo n.º 18
0
 def __init__(self, *args, **kwargs):
     TestCase.__init__(self, *args, **kwargs)