def setUpClass(cls): here = os.path.dirname(__file__) localtest = os.path.join(here, '../../', 'test.local.ini') if os.path.isfile(localtest): cls.settings = appconfig('config:' + localtest) else: test = os.path.join(here, '../../', 'test.ini') cls.settings = appconfig('config:' + test) cls.engine = engine_from_config(cls.settings, 'sqlalchemy.')
def init_settings(): ini = os.environ.get( 'PYRAMID_SETTINGS', os.path.abspath(os.path.join(os.path.dirname(__file__), '../development.ini')) ) set_settings(appconfig('config:%s' % ini, 'settings'))
def initDatabase(): """Method to initialise the database""" log.debug("------- INITIALISE TESTING DATABASE ---------") #Setup and configure the code settings = appconfig('config:' + SETTINGS_PATH) #Setup the configurator config = Configurator(settings = settings) #Scan for all models config.scan("cogentviewer.models") engine = engine_from_config(settings, prefix="sqlalchemy.") log.debug("--> Database Engine Started: {0}".format(engine)) #Create the tables log.debug("--> Creating Tables") meta.Base.metadata.create_all(engine) log.debug("--> Configuring Session") meta.Session.configure(bind=engine) #log.debug("Initialising SQL") #meta.Base.metadata.bind = engine log.debug("--> Adding Initial Data") models.populateData.init_data()
class FunctionalTests(unittest.TestCase): INI_FILE = os.path.join(os.path.dirname(__file__), 'testing.ini') SETTINGS = appconfig('config:' + INI_FILE) @classmethod def setUpClass(cls): from sql_test.models import get_tm_session from sql_test import main app = main({}, **cls.SETTINGS) cls.testapp = webtest.TestApp(app) session_factory = app.registry['session_factory'] cls.engine = session_factory.kw['bind'] cls.session = get_tm_session(session_factory, transaction.manager) Base.metadata.drop_all(bind=cls.engine) # run initializedb script args = ['sql_test_initialize_db', cls.INI_FILE] log.warning(subprocess.check_output(args)) @classmethod def tearDownClass(cls): Base.metadata.drop_all(bind=cls.engine) cls.session.close() def test_root(self): res = self.testapp.get('/', status=200) self.assertIn(b'<h1>sql test</h1>', res.body)
def pytest_sessionstart(): """ Py.test setup """ from py.test import config # Only run database setup on master (in case of xdist/multiproc mode) if not hasattr(config, 'slaveinput'): from crmbase.models import initialize_sql from crmbase.models.model import * from pyramid.config import Configurator from paste.deploy.loadwsgi import appconfig from sqlalchemy import engine_from_config import os root_path = os.path.dirname(__file__) settings = appconfig('config:' + os.path.join(root_path, "../../", 'test.ini'), "crmbase") engine = engine_from_config(settings, prefix='sqlalchemy.') print 'Creating the tables on the test database %s' % engine config = Configurator(settings=settings) initialize_sql(engine, create=True)
def pytest_sessionstart(): from py.test import config from pyramid.config import Configurator from creme_fraiche.models import Base from creme_fraiche.models import insert_base from paste.deploy.loadwsgi import appconfig from sqlalchemy import engine_from_config import os ROOT_PATH = os.path.dirname(__file__) settings = appconfig( 'config:' + resource_filename( __name__, 'creme_fraiche/tests/test.ini' ) ) engine = engine_from_config(settings, prefix='sqlalchemy.') print('Creating the tables on the test database %s' % engine) config = Configurator(settings=settings) config.scan('creme_fraiche.models') Base.metadata.drop_all(engine) Base.metadata.create_all(engine) insert_base(engine)
def test_app_creation(): from paste.deploy.loadwsgi import appconfig from timtec import main settings = appconfig("config:" + resource_filename(__name__, "../development.ini")) app = main(config, **settings) assert isinstance(app, router.Router)
def setUpClass(cls): here = os.path.dirname(__file__) settings = appconfig( 'config:' + os.path.join(here, './', 'test.ini') ) from creme_fraiche import main cls.app = main({}, **settings)
def initDatabase(): """Method to initialise the database""" log.debug("------- INITIALISE TESTING DATABASE ---------") #Setup and configure the code settings = appconfig('config:' + SETTINGS_PATH) #Setup the configurator config = Configurator(settings=settings) #Scan for all models config.scan("cogentviewer.models") engine = engine_from_config(settings, prefix="sqlalchemy.") log.debug("--> Database Engine Started: {0}".format(engine)) #Create the tables log.debug("--> Creating Tables") meta.Base.metadata.create_all(engine) log.debug("--> Configuring Session") meta.Session.configure(bind=engine) #log.debug("Initialising SQL") #meta.Base.metadata.bind = engine log.debug("--> Adding Initial Data") models.populateData.init_data()
def setUpClass(cls): here = os.path.dirname(__file__) settings = appconfig( 'config:' + os.path.join(here, '../../../parts/etc/', 'test.ini') ) cls.engine = engine_from_config(settings, prefix='sqlalchemy.') cls.Session = sessionmaker()
def main(argv=sys.argv): """Script entry point.""" dist = pkg_resources.get_distribution("pyramid_couchauth_example") root = dist.location config = "config:" + os.path.join(root, "development.ini") settings = appconfig(config, "pyramid_couchauth_example") setup_app(settings)
def setUp(self): self.config = appconfig("config:development.ini", "pyramid", relative_to=".") from bccvl_visualiser import main app = main(None, **self.config) from webtest import TestApp self.testapp = TestApp(app)
def configure(ini=None): if not ini: ini = DEFAULT_INIFILE path = '%s.ini' % ini config_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', '..', path)) base, name = os.path.split(config_path) config = appconfig('config:%s' % name, name='rstlibrary', relative_to=base) return config
def setUp(self): self.config = appconfig('config:development.ini', 'pyramid', relative_to='.') from bccvl_visualiser import main app = main(None, **self.config) from webtest import TestApp self.testapp = TestApp(app)
def setUpClass(cls): """Class method, called each time this is initialised""" #cls.config = testing.setUp() #Load settings from Configuration file log.debug("Init Test Class Database for {0}".format(cls.__name__)) settings = appconfig('config:' + SETTINGS_PATH) cls.engine = engine_from_config(settings, prefix='sqlalchemy.') cls.Session = sessionmaker()
def _get_config_variables(cls, config_uri, buildout_dir, part_name): try: app_config = appconfig(config_uri, relative_to=buildout_dir) except (LookupError, ValueError, OSError), exc: raise BuildoutError( "Could not load variables from part '%s': %s" % ( part_name, exc, ), )
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ engine = engine_from_config(settings, "sqlalchemy.") DBSession.configure(bind=engine) # session, authentication, and authorization authn_policy = AuthTktAuthenticationPolicy(secret="supasecret") authz_policy = ACLAuthorizationPolicy() session_factory = UnencryptedCookieSessionFactoryConfig(settings["session.secret"]) # load secret stuff from secret.ini (not provided in repo) try: if os.environ.get("OPENSHIFT_DATA_DIR"): path = os.environ["OPENSHIFT_DATA_DIR"] else: path = "." from paste.deploy.loadwsgi import appconfig secret_config = appconfig("config:secret.ini", "charsheet", relative_to=path) except IOError: print "Failed to load secret.ini" return 0 settings.update( { "velruse.github.consumer_key": secret_config["velruse.github.consumer_key"], "velruse.github.consumer_secret": secret_config["velruse.github.consumer_secret"], } ) # configuration setup config = Configurator(settings=settings, session_factory=session_factory) # use Mako templates config.include("pyramid_mako") # static view setup config.add_static_view("static", "static", cache_max_age=3600) # velruse config.include("velruse.providers.github") config.add_github_login(settings["velruse.github.consumer_key"], settings["velruse.github.consumer_secret"]) # routes setup config.add_route("home", "/") config.add_route("submit", "/submit") config.add_route("handle_search", "/handle_search") config.add_route("charsheet", "/charsheet/{username}") config.add_route("stats", "/stats") config.add_route("login", "/login") config.add_route("logout", "/logout") config.add_route("verify_openid", pattern="/dologin.html") config.add_view(view="pyramid_openid.verify_openid", route_name="verify_openid") # TODO: make this service-agnostic config.scan() return config.make_wsgi_app()
def get_config(): """ Returns a global configuration object as a dictionnary Raise IOError if the config is not loaded and we can't fallback on pyramid.ini. """ global config if config is None: here = os.path.dirname(__file__) config = appconfig('config:' + os.path.join(here, '../', 'pyramid.ini')) return config
def setUpClass(cls): settings = appconfig('config:' + TEST_INI) cls.engine = engine_from_config(settings, prefix='sqlalchemy.') cls.session = sessionmaker(bind=cls.engine)() models.Base.metadata.create_all(cls.engine, checkfirst=True) transaction.commit() cls.name = "Yay or Nay?" cls.options = ["Yay", "Nay", "Maybe"] cls.options_str = ",".join(cls.options) cls.server = start_server()
def setUp(self): self.config = testing.setUp() # get the db ready root = os.path.dirname(__file__) settings = appconfig('config:' + os.path.join(root, '..', '..', 'test.ini')) config = Configurator(settings=settings) config.include('pyramid_chameleon') engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine Base.prepare(engine)
def setUp(self): from alembic.config import Config from alembic import command alembic_cfg = Config(os.path.join(here, '../../', 'alembic.ini'), ini_section = 'test') command.upgrade(alembic_cfg, "head") settings = appconfig('config:' + os.path.join(here, '../../', 'test.ini')) from domidooweb import main app = main({}, **settings) from webtest import TestApp self.testapp = TestApp(app)
def setUpClass(cls): settings = appconfig('config:' + TEST_INI) cls.engine = engine_from_config(settings, prefix='sqlalchemy.') models.Base.metadata.drop_all(cls.engine) models.Base.metadata.tables["poll"].create(bind=cls.engine) models.Base.metadata.tables["choice"].create(bind=cls.engine) models.Base.metadata.tables["response"].create(bind=cls.engine) transaction.commit() cls.name = "Yay or Nay?" cls.options = ["Yay", "Nay"] cls.ip_address = "192.168.1.1"
def sbetup(): from pyramid.config import Configurator from sqlalchemy import engine_from_config import os ROOT_PATH = os.path.dirname(__file__) settings = appconfig('config:' + os.path.join(ROOT_PATH, 'test.ini')) engine = engine_from_config(settings, prefix='sqlalchemy.') print('Creating the tables on the test database %s' % engine) config = Configurator(settings=settings)
def setUpClass(cls): here = os.path.dirname(os.path.realpath(__file__)) uri = 'config:' + os.path.join(here, "..", "..", "tests.ini") cls.settings = appconfig(uri, 'aybu-manager') cls.engine = engine_from_config(cls.settings, prefix="sqlalchemy.") cls.Session = sessionmaker() cls.log = logging.getLogger(cls.__name__) setup_metadata(cls.engine) create_tables() import_data(cls.engine, cls.Session) raise Exception()
def test_main_returns_wsgi_app(self): from pyramid.router import Router from paste.deploy.loadwsgi import appconfig from wwc import main pkgroot = pkg_resources.get_distribution('wwc').location test_ini_path = os.path.join(pkgroot, 'test.ini') settings = appconfig('config:{}'.format(test_ini_path)) wsgi_ = main({}, **settings) assert isinstance(wsgi_, Router)
def setUp(self): super(DbTestCase, self).setUp() from paste.deploy.loadwsgi import appconfig self.config = appconfig("config:test.ini", relative_to=conf_dir) from sqlalchemy import engine_from_config from fivecents.model import init_model, model_instance init_model(bind=engine_from_config(self.config, "sqlalchemy.")) self.model = model_instance() self.connection = self.model.engine.connect() self.db = self.model.session
def setUpClass(cls): settings = appconfig('config:' + TEST_INI) cls.engine = engine_from_config(settings, prefix='sqlalchemy.') models.Base.metadata.drop_all(cls.engine) models.Base.metadata.tables["poll"].create(bind=cls.engine) models.Base.metadata.tables["choice"].create(bind=cls.engine) models.Base.metadata.tables["response"].create(bind=cls.engine) transaction.commit() cls.name = "Yay or Nay?" cls.options = [ "Yay", "Nay" ] cls.ip_address = "192.168.1.1"
def setup(): """Prepare to execute tests by setting up the database. main does the db configuration. Then the tables need to be created. """ # Hush factory boy. logging.getLogger('factory').setLevel(logging.WARN) here = os.path.dirname(__file__) ini_path = os.path.abspath(os.path.join(here, '..', '..', 'test.ini')) settings = appconfig('config:' + ini_path) server.main(global_config={}, **settings) # Use Base from models to get the benefit of declaring all models. models.Base.metadata.create_all()
def main(): parser, subparsers, global_arguments = setup_parser() args = parser["root"].parse_args() # FIXME: Initialialising the testing modul is currently the only # known way to make the settings # available in the current_registry call (which is called # inside # ringo when loading the form). config = appconfig('config:%s' % args.config, "main", relative_to='.') name = config.context.distribution.project_name registry = Registry(name) registry.settings = config testing.setUp(registry) args.func(args)
def connect(self, cfg, customAppSettings={}, wrapper='StopableWSGIServer'): self.cfg = cfg # clear old connections # try: # DBSession.close() # DBSession.remove() # os.remove(self.cfg['app']['db']) # except: # pass # create appConfig from ini self.appSettings = appconfig( 'config:' + os.path.join( os.path.dirname(__file__), '../../', self.cfg['app']['ini'] ) ) # store some derived variables self.appSettings['sqlalchemy.url'] = 'sqlite:///'+self.cfg['app']['db'] # merge/override appConfig with custom settings in cfg self.appSettings.update(self.cfg['app']['appSettings']) # merge/override appConfig with individual custom settings self.appSettings.update(customAppSettings) # app engine = engine_from_config(self.appSettings) DBSession.configure(bind=engine) Base.metadata.create_all(engine) from c3smembership import main app = main({}, **self.appSettings) # create srv if wrapper == 'StopableWSGIServer': self.srv = StopableWSGIServer.create( app, host=self.cfg['app']['host'], port=self.cfg['app']['port'] ) # check srv if not self.srv.wait(): raise Exception('Server could not be fired up. Exiting ...') elif wrapper == 'TestApp': self.srv = TestApp(app) else: raise Exception('Wrapper could not be found. Exiting ...') # store some variables self.srv.db = DBSession self.srv.url = 'http://' + self.cfg['app']['host'] + ':' \ + self.cfg['app']['port'] + '/' # self.srv.lu = 'lu/' + self.cfg['member']['token'] + '/' \ # + self.cfg['member']['email'] return self.srv
def setUp(self): # init the web app in the constructor instead of setUp, to avoid overload. # currently the most time is spend by nosetest doing its stuffs, # not running the tests. # def __init__(self, *args, **kargs): # super(ViewTests, self).__init__(*args, **kargs) from paste.deploy.loadwsgi import appconfig from webtest import TestApp from web_backend import main # get settings settings = appconfig('config:development.ini', 'main', relative_to='.') # instanciate app app = main({'test_mode': True}, **settings) self.testapp = TestApp(app)
def main(): """Initialize a development database.""" here = os.path.dirname(__file__) ini_path = os.path.abspath(os.path.join(here, '..', '..', 'development.ini')) settings = appconfig('config:' + ini_path) # Show the SQL to see table creation output. settings['sqlalchemy.echo'] = True server.main(global_config={}, **settings) # # Use Base from models to get the benefit of declaring all models. models.Base.metadata.create_all() session = db.Session() session.add(models.Build(passes=42, fails=4, skips=1)) session.add(models.Build(passes=52, fails=2, skips=2)) session.add(models.Build(passes=62, fails=1, skips=3)) session.commit()
def setUp(self): pkgroot = pkg_resources.get_distribution('wwc').location test_ini = os.path.join(pkgroot, 'test.ini') settings = appconfig('config:{}'.format(test_ini)) engine = engine_from_config(settings, prefix="sqlalchemy.") connection = engine.connect() self.trans = connection.begin() Session = sessionmaker() self.session = Session(bind=connection) config = testing.setUp() from wwc import main app = main(config, **settings) from webtest import TestApp self.testapp = TestApp(app)
def setUpClass(self): from openwifi import main from webtest import TestApp self.config = testing.setUp() from sqlalchemy import create_engine from openwifi.models import DBSession DBSession.close_all() import os from .models import ( Base, DBSession, ) ROOT_PATH = os.path.dirname(__file__) settings = appconfig('config:' + os.path.join(ROOT_PATH, 'test.ini')) settings['openwifi.useAuth'] = 'true' settings['openwifi.offline'] = 'true' print(settings) self.app = main({}, **settings) self.app = TestApp(self.app) self.app.post_json('/login', {'login':'******', 'password':'******'}) resp = self.app.get('/users') self.admin_id = json.loads(resp.text)['admin'] self.app.post_json('/access', {'access_all_nodes': True, 'userid': self.admin_id}) example_config_path = os.path.join(ROOT_PATH, 'tests', 'exampleConfig.json') example_config = open(example_config_path).read() new_node_dict = {"name":"testnode", "address":"localhost", "distribution":"none", "version":"none", "login":"******", "password":"******"} resp = self.app.post_json('/nodes', new_node_dict) node_id = json.loads(resp.text) self.node_id = node_id self.app.post_json('/nodes/'+node_id, {'configuration':example_config}) resp = self.app.get('/masterConfig') master_confs = json.loads(resp.text) for m in master_confs: if m['assoc'] == [self.node_id]: self.mconf_id = str(m['id'])
class FunctionalTests(BaseTest): INI_FILE = os.path.join(os.path.dirname(__file__), 'testing.ini') SETTINGS = appconfig('config:' + INI_FILE) @classmethod def setUpClass(cls): super(FunctionalTests, cls).setUpClass() # run initializedb script stmnt = ' '.join(['sql_test_initialize_db', cls.INI_FILE]) log.warning(stmnt) os.system(stmnt) # start demo app from sql_test import main app = main({}, **cls.SETTINGS) from webtest import TestApp cls.testapp = TestApp(app) def test_home(self): res = self.testapp.get('/', status=200) self.assertIn(b'<h1>sql test</h1>', res.body) def test_home_urls(self): res = self.testapp.get('/', status=200) find_and_visit_local_urls(res) def test_jade(self): res = self.testapp.get('/jade_demo', status=200) self.assertIn(b'jade', res.body) def test_jade_urls(self): res = self.testapp.get('/jade_demo', status=200) find_and_visit_local_urls(res) def test_huisstijl(self): res = self.testapp.get('/bootstrap_demo', status=200) self.assertIn(b'Cras mattis consectetur purus sit amet fermentum.', res.body) def test_huisstijl_urls(self): res = self.testapp.get('/bootstrap_demo', status=200) find_and_visit_local_urls(res)
def command(self): if not self.args: raise BadCommand('You must give a configuration file.') file_name = self.args[0] if not file_name.startswith("/"): file_name = os.path.join(os.getcwd(), file_name) # Setup logging via the logging module's fileConfig function # with the specified 'config_file', if applicable. self.logging_file_config(file_name) config = appconfig('config:{}'.format(file_name)) engine = engine_from_config(config, 'sqlalchemy.') Base.metadata.bind = engine Base.metadata.drop_all() Base.metadata.create_all() command.stamp(Config(file_name.split('#')[0]), 'head') Session = sessionmaker(bind=engine) try: session = Session() init_session_events(session) source_ = pkg_resources.resource_stream('aybu.core.data', 'default_data.json') data = json.loads(source_.read()) add_default_data(session, data) user = User(username=config['default_user.username'], password=config['default_user.password']) session.merge(user) group = Group(name=u'admin') group.users.append(user) session.merge(group) session.flush() except: session.rollback() else: session.commit() finally: session.close() source_.close()
def setUp(self): from openwifi import main from webtest import TestApp self.config = testing.setUp() from sqlalchemy import create_engine import os #engine = create_engine('sqlite://') from .models import ( Base, DBSession, ) #DBSession.configure(bind=engine) #Base.metadata.create_all(engine) ROOT_PATH = os.path.dirname(__file__) settings = appconfig('config:' + os.path.join(ROOT_PATH, 'test.ini')) print(settings) self.app = main({}, **settings) self.app = TestApp(self.app)
def main(): """Initialize a development database.""" here = os.path.dirname(__file__) ini_path = os.path.abspath( os.path.join(here, '..', '..', 'development.ini')) settings = appconfig('config:' + ini_path) # Show the SQL to see table creation output. settings['sqlalchemy.echo'] = True server.main(global_config={}, **settings) # # Use Base from models to get the benefit of declaring all models. models.Base.metadata.create_all() session = db.Session() session.add(models.Build(passes=42, fails=4, skips=1)) session.add(models.Build(passes=52, fails=2, skips=2)) session.add(models.Build(passes=62, fails=1, skips=3)) session.commit()
def pytest_sessionstart(): from py.test import config # Only run database setup on master (in case of xdist/multiproc mode) if not hasattr(config, 'slaveinput'): from pyramid.config import Configurator from horus.tests.models import Base from paste.deploy.loadwsgi import appconfig from sqlalchemy import engine_from_config settings = appconfig( 'config:' + resource_filename(__name__, 'horus/tests/test.ini')) engine = engine_from_config(settings, prefix='sqlalchemy.') print('Creating the tables on the test database %s' % engine) config = Configurator(settings=settings) config.scan('horus.models') Base.metadata.drop_all(engine) Base.metadata.create_all(engine)
def setUp(self): super(BalanceFacadeTest, self).setUp() from sqlalchemy.orm import clear_mappers clear_mappers() from paste.deploy.loadwsgi import appconfig self.config = appconfig('config:test.ini', relative_to=conf_dir) from fivecents.lib.sqlalchemymanager import SQLAlchemyManager from authkit.users import sqlalchemy_04_driver from fivecents.model import setup_model self.manager = SQLAlchemyManager(None, self.config, [sqlalchemy_04_driver.setup_model, setup_model]) self.connection = self.manager.engine.connect() self.db = self.manager.session_maker(bind=self.connection) self.model = self.manager.model
def setUpClass(cls): """ New Setup Function, creates an app """ #super(BaseTestCase, cls).setUpClass() #Load settings from predefined .ini file settings = appconfig('config:' + SETTINGS_PATH) #cls.engine = engine_from_config(settings, prefix='sqlalchemy.') #cls.Session = sessionmaker() #cls.Session = meta.Session #print meta.Session #super(BaseTestCase, cls).setUp() from cogentviewer import main cls.app = main({}, **settings) from webtest import TestApp cls.testapp = TestApp(cls.app)
def connect(self, cfg, customAppSettings=None, wrapper='StopableWSGIServer'): if customAppSettings is None: customAppSettings = {} self.cfg = cfg self.app_settings = appconfig( 'config:' + os.path.join( os.path.dirname(__file__), '../../', self.cfg['app']['ini'] ) ) # store some derived variables self.app_settings['sqlalchemy.url'] = 'sqlite:///'+self.cfg['app']['db'] # merge/override appConfig with custom settings in cfg self.app_settings.update(self.cfg['app']['appSettings']) # merge/override appConfig with individual custom settings self.app_settings.update(customAppSettings) # app engine = engine_from_config(self.app_settings) DBSession.configure(bind=engine) Base.metadata.create_all(engine) from c3smembership import main app = main({}, **self.app_settings) # create srv if wrapper == 'StopableWSGIServer': self.srv = StopableWSGIServer.create( app, host=self.cfg['app']['host'], port=self.cfg['app']['port'] ) # check srv if not self.srv.wait(): raise Exception('Server could not be fired up. Exiting ...') elif wrapper == 'TestApp': self.srv = TestApp(app) else: raise Exception('Wrapper could not be found. Exiting ...') # store some variables self.srv.db = DBSession self.srv.url = 'http://' + self.cfg['app']['host'] + ':' \ + self.cfg['app']['port'] + '/' return self.srv
def pytest_sessionstart(): from py.test import config # Only run database setup on master (in case of xdist/multiproc mode) if not hasattr(config, 'slaveinput'): from pyramid.config import Configurator from pyramid_signup.models import Entity from paste.deploy.loadwsgi import appconfig from sqlalchemy import engine_from_config import os ROOT_PATH = os.path.dirname(__file__) settings = appconfig('config:' + os.path.join(ROOT_PATH, 'test.ini')) engine = engine_from_config(settings, prefix='sqlalchemy.') print 'Creating the tables on the test database %s' % engine config = Configurator(settings=settings) config.scan('pyramid_signup.models') Entity.metadata.drop_all(engine) Entity.metadata.create_all(engine)
class FunctionalTestsAdmin(BaseTest): INI_FILE = os.path.join(os.path.dirname(__file__), 'testing.ini') SETTINGS = appconfig('config:' + INI_FILE) @classmethod def setUpClass(cls): """Sign in.""" super(FunctionalTestsAdmin, cls).setUpClass() # run initializedb script stmnt = ' '.join(['henky_initialize_db', cls.INI_FILE]) log.warning(stmnt) os.system(stmnt) # start demo app from henky import main app = main({}, **cls.SETTINGS) from webtest import TestApp cls.testapp = TestApp(app) res = cls.testapp.get("/sign_in_local", status=200) f = res.forms["sign-in"] f.set("user_name", "admin") f.set("password", "admin") res = f.submit("submit") def tearDown(self): """Sign out.""" self.testapp.get("/sign_out") def test_home_urls(self): """Test urls from home.""" res = self.testapp.get("/", status=200) self.assertEqual(200, res.status_code) #find_and_visit_local_urls(res)
def settings(): _settings = appconfig('config:%s' % __current_test_ini_file(), "autonomie") _settings["autonomie.ftpdir"] = DATASDIR return _settings
def test_proxy(self): conf = loadwsgi.appconfig('egg:webobentrypoints#proxy') res = conf.context.object(conf.global_conf, address='http://webob.org/', suppress_http_headers=None)
def test_staticdir(self): conf = loadwsgi.appconfig('egg:webobentrypoints#staticdir') res = conf.context.object(conf.global_conf, path=os.path.dirname(__file__), index_page='index.html', hide_index_with_redirect=False)
""" AppTestCase is a subclass of unittest.TestCase for writing unit tests that will have access to a clean h database. """ from unittest import TestCase from paste.deploy.loadwsgi import appconfig from pyramid import testing from sqlalchemy import engine_from_config from sqlalchemy.orm import sessionmaker from h.models import Base from h import api settings = appconfig('config:test.ini', relative_to='.') class AppTestCase(TestCase): @classmethod def setUpClass(cls): cls.engine = engine_from_config(settings) cls.Session = sessionmaker(autoflush=False, autocommit=True) config = testing.setUp(settings=settings) def setUp(self): self.connection = self.engine.connect() self.db = self.Session(bind=self.connection) Base.metadata.bind = self.connection Base.metadata.create_all(self.engine) def tearDown(self):
from pyramid.authorization import ACLAuthorizationPolicy from pyramid_beaker import session_factory_from_settings from pyramid.response import Response from paste.deploy.loadwsgi import appconfig from sqlalchemy.orm import scoped_session from sqlalchemy.orm import sessionmaker from zope.sqlalchemy import ZopeTransactionExtension from mock import Mock import os from pyramid_signup.models import Entity from pyramid_signup.interfaces import ISUSession here = os.path.dirname(__file__) settings = appconfig('config:' + os.path.join(here, '../../', 'test.ini')) DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) class BaseTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.engine = engine_from_config(settings, prefix='sqlalchemy.') cls.Session = sessionmaker() def setUp(self): self.config = testing.setUp() self.connection = connection = self.engine.connect()
def setUpClass(cls): here = os.path.dirname(__file__) settings = appconfig( 'config:' + os.path.join(here, '../../../parts/etc/', 'test.ini')) cls.engine = engine_from_config(settings, prefix='sqlalchemy.') cls.Session = sessionmaker()
def get_appsettings(name): return appconfig('config:{0}'.format(name), 'main', relative_to=os.getcwd())
def get_settings(self, config_file='../../config-example.ini#webgnome_api'): here = os.path.dirname(__file__) return appconfig('config:%s' % config_file, relative_to=here)
import unittest from pyramid import testing from paste.deploy.loadwsgi import appconfig from webtest import TestApp from sqlalchemy import engine_from_config from sqlalchemy.orm import sessionmaker import os here = os.path.dirname(__file__) settings = appconfig('config:' + os.path.join(here, '../../', 'development.ini')) class BaseTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.engine = engine_from_config(settings, prefix='sqlalchemy.') cls.Session = sessionmaker() def setUp(self): connection = self.engine.connect() # begin a non-ORM transaction self.trans = connection.begin() from forms.models import DBSession self.session = DBSession def tearDown(self): # rollback - everything that happened with the # Session above (including calls to commit()) # is rolled back.