# Path: tasks/util.py
# def shell(cmd, encoding='utf-8'):
#     '''
#     Run a shell command, uses :py:func:`subprocess.check_output(cmd,
#     shell=True)` under the hood.
# 
#     Returns the ``STDOUT`` output, and raises an error if there is a
#     none-zero exit code.
#     '''
#     try:
#         return subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT).decode(encoding)
#     except subprocess.CalledProcessError as err:
#         LOGGER.error(err.output)
#         raise
# 
# Path: tasks/us/census/tiger.py
# class GeoidColumns(ColumnsTask):
#     '''
#     Used for external dependencies on Tiger.
# 
#     This creates two different geoid columns
#     (GEOID_SUMLEVEL_COLUMN for the SumLevels geometries and
#     GEOID_SHORELINECLIPPED_COLUMN for the ShorelineClipped geometries).
# 
#     This allows external tables to depend on both shoreline clipped and non-shoreline clipped geometries.
#     '''
# 
#     year = IntParameter()
# 
#     def version(self):
#         return 8
# 
#     def requires(self):
#         return {
#             'raw': GeomColumns(year=self.year),
#             'clipped': ClippedGeomColumns(year=self.year)
#         }
# 
#     def columns(self):
#         cols = OrderedDict()
#         clipped = self.input()['clipped']
#         for colname, coltarget in self.input()['raw'].items():
#             col = coltarget._column
#             cols[colname + GEOID_SHORELINECLIPPED_COLUMN] = OBSColumn(
#                 type='Text',
#                 name=col.name + ' Geoids',
#                 weight=0,
#                 targets={
#                     clipped[colname + '_clipped']._column: GEOM_REF
#                 }
#             )
#             cols[colname + GEOID_SUMLEVEL_COLUMN] = OBSColumn(
#                 type='Text',
#                 name=col.name + ' Geoids',
#                 weight=0,
#                 targets={
#                     col: GEOM_REF,
#                 }
#             )
# 
#         return cols
# 
# class GeomColumns(ColumnsTask):
#     year = IntParameter()
# 
#     def version(self):
#         return 18
# 
#     def requires(self):
#         return {
#             'sections': SectionTags(),
#             'subsections': SubsectionTags(),
#             'source': TigerSourceTags(),
#             'license': LicenseTags(),
#             'boundary': BoundaryTags(),
#         }
# 
#     def _generate_desc(self, sumlevel):
#         '''
#         Add figure to the description
#         '''
#         return SUMLEVELS[sumlevel]['census_description']
# 
#     def columns(self):
#         input_ = self.input()
#         sections = input_['sections']
#         subsections = input_['subsections']
#         source = input_['source']['tiger-source']
#         license = input_['license']['no-restrictions']
# 
#         columns = {}
#         for level in list(SUMLEVELS.values()):
#             columns[level['slug'] + '_{}'.format(self.year)] = OBSColumn(
#                 type='Geometry',
#                 name=level['name'] + '_{}'.format(self.year),
#                 description=level['census_description'],
#                 weight=level['weight'],
#                 tags=[sections['united_states'], subsections['boundary'], source, license]
#             )
# 
#         return columns
# 
# Path: tests/util.py
# def runtask(task, superclasses=None):
#     '''
#     Run deps of tasks then the task, faking session management
# 
#     superclasses is a list of classes that we will be willing to run as
#     pre-reqs, other pre-reqs will be ignored.  Can be useful when testing to
#     only run metadata classes, for example.
#     '''
#     from lib.logger import get_logger
#     LOGGER = get_logger(__name__)
#     if task.complete():
#         return
#     for dep in task.deps():
#         if superclasses:
#             for klass in superclasses:
#                 if isinstance(dep, klass):
#                     runtask(dep, superclasses=superclasses)
#                     assert dep.complete() is True, 'dependency {} not complete for class {}'.format(dep, klass)
#         else:
#             runtask(dep)
#             assert dep.complete() is True, 'dependency {} not complete'.format(dep)
#     try:
#         before = time()
#         for klass, cb_dict in task._event_callbacks.items():
#             if isinstance(task, klass):
#                 start_callbacks = cb_dict.get('event.core.start', [])
#                 for scb in start_callbacks:
#                     scb(task)
#         task.run()
#         task.on_success()
#         after = time()
#         LOGGER.warn('runtask timing %s: %s', task, round(after - before, 2))
#     except Exception as exc:
#         task.on_failure(exc)
#         raise
# 
# def setup():
#     from tasks.meta import current_session, Base
#     if Base.metadata.bind.url.database != 'test':
#         raise Exception('Can only run tests on database "test"')
#     session = current_session()
#     session.rollback()
#     session.execute('DROP SCHEMA IF EXISTS observatory CASCADE')
#     session.execute('CREATE SCHEMA observatory')
#     session.commit()
#     Base.metadata.create_all()
#     session.close()
# 
# def teardown():
#     from tasks.meta import current_session, Base
#     if Base.metadata.bind.url.database != 'test':
#         raise Exception('Can only run tests on database "test"')
#     session = current_session()
#     session.rollback()
#     Base.metadata.drop_all()
#     session.execute('DROP SCHEMA IF EXISTS observatory CASCADE')
#     session.commit()
#     session.close()


from tasks.util import shell
from nose.tools import with_setup
from tasks.us.census.tiger import GeoidColumns, GeomColumns
from tests.util import runtask, setup, teardown
'''
Test Tiger columns
'''


# TODO clean this up in a more general init script

try:
    shell('createdb test')
except:
    pass





@with_setup(setup, teardown)
def test_geom_columns_run():
    runtask(GeomColumns(year='2015'))


@with_setup(setup, teardown)
def test_geoid_columns_run():

# Path: tasks/util.py
# def shell(cmd, encoding='utf-8'):
#     '''
#     Run a shell command, uses :py:func:`subprocess.check_output(cmd,
#     shell=True)` under the hood.
# 
#     Returns the ``STDOUT`` output, and raises an error if there is a
#     none-zero exit code.
#     '''
#     try:
#         return subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT).decode(encoding)
#     except subprocess.CalledProcessError as err:
#         LOGGER.error(err.output)
#         raise
# 
# Path: tasks/us/census/tiger.py
# class GeoidColumns(ColumnsTask):
#     '''
#     Used for external dependencies on Tiger.
# 
#     This creates two different geoid columns
#     (GEOID_SUMLEVEL_COLUMN for the SumLevels geometries and
#     GEOID_SHORELINECLIPPED_COLUMN for the ShorelineClipped geometries).
# 
#     This allows external tables to depend on both shoreline clipped and non-shoreline clipped geometries.
#     '''
# 
#     year = IntParameter()
# 
#     def version(self):
#         return 8
# 
#     def requires(self):
#         return {
#             'raw': GeomColumns(year=self.year),
#             'clipped': ClippedGeomColumns(year=self.year)
#         }
# 
#     def columns(self):
#         cols = OrderedDict()
#         clipped = self.input()['clipped']
#         for colname, coltarget in self.input()['raw'].items():
#             col = coltarget._column
#             cols[colname + GEOID_SHORELINECLIPPED_COLUMN] = OBSColumn(
#                 type='Text',
#                 name=col.name + ' Geoids',
#                 weight=0,
#                 targets={
#                     clipped[colname + '_clipped']._column: GEOM_REF
#                 }
#             )
#             cols[colname + GEOID_SUMLEVEL_COLUMN] = OBSColumn(
#                 type='Text',
#                 name=col.name + ' Geoids',
#                 weight=0,
#                 targets={
#                     col: GEOM_REF,
#                 }
#             )
# 
#         return cols
# 
# class GeomColumns(ColumnsTask):
#     year = IntParameter()
# 
#     def version(self):
#         return 18
# 
#     def requires(self):
#         return {
#             'sections': SectionTags(),
#             'subsections': SubsectionTags(),
#             'source': TigerSourceTags(),
#             'license': LicenseTags(),
#             'boundary': BoundaryTags(),
#         }
# 
#     def _generate_desc(self, sumlevel):
#         '''
#         Add figure to the description
#         '''
#         return SUMLEVELS[sumlevel]['census_description']
# 
#     def columns(self):
#         input_ = self.input()
#         sections = input_['sections']
#         subsections = input_['subsections']
#         source = input_['source']['tiger-source']
#         license = input_['license']['no-restrictions']
# 
#         columns = {}
#         for level in list(SUMLEVELS.values()):
#             columns[level['slug'] + '_{}'.format(self.year)] = OBSColumn(
#                 type='Geometry',
#                 name=level['name'] + '_{}'.format(self.year),
#                 description=level['census_description'],
#                 weight=level['weight'],
#                 tags=[sections['united_states'], subsections['boundary'], source, license]
#             )
# 
#         return columns
# 
# Path: tests/util.py
# def runtask(task, superclasses=None):
#     '''
#     Run deps of tasks then the task, faking session management
# 
#     superclasses is a list of classes that we will be willing to run as
#     pre-reqs, other pre-reqs will be ignored.  Can be useful when testing to
#     only run metadata classes, for example.
#     '''
#     from lib.logger import get_logger
#     LOGGER = get_logger(__name__)
#     if task.complete():
#         return
#     for dep in task.deps():
#         if superclasses:
#             for klass in superclasses:
#                 if isinstance(dep, klass):
#                     runtask(dep, superclasses=superclasses)
#                     assert dep.complete() is True, 'dependency {} not complete for class {}'.format(dep, klass)
#         else:
#             runtask(dep)
#             assert dep.complete() is True, 'dependency {} not complete'.format(dep)
#     try:
#         before = time()
#         for klass, cb_dict in task._event_callbacks.items():
#             if isinstance(task, klass):
#                 start_callbacks = cb_dict.get('event.core.start', [])
#                 for scb in start_callbacks:
#                     scb(task)
#         task.run()
#         task.on_success()
#         after = time()
#         LOGGER.warn('runtask timing %s: %s', task, round(after - before, 2))
#     except Exception as exc:
#         task.on_failure(exc)
#         raise
# 
# def setup():
#     from tasks.meta import current_session, Base
#     if Base.metadata.bind.url.database != 'test':
#         raise Exception('Can only run tests on database "test"')
#     session = current_session()
#     session.rollback()
#     session.execute('DROP SCHEMA IF EXISTS observatory CASCADE')
#     session.execute('CREATE SCHEMA observatory')
#     session.commit()
#     Base.metadata.create_all()
#     session.close()
# 
# def teardown():
#     from tasks.meta import current_session, Base
#     if Base.metadata.bind.url.database != 'test':
#         raise Exception('Can only run tests on database "test"')
#     session = current_session()
#     session.rollback()
#     Base.metadata.drop_all()
#     session.execute('DROP SCHEMA IF EXISTS observatory CASCADE')
#     session.commit()
#     session.close()


# Path: tests/us/census/test_tiger.py
from tasks.util import shell
from nose.tools import with_setup
from tasks.us.census.tiger import GeoidColumns, GeomColumns
from tests.util import runtask, setup, teardown

'''
Test Tiger columns
'''


# TODO clean this up in a more general init script

try:
    shell('createdb test')
except:
    pass





@with_setup(setup, teardown)
def test_geom_columns_run():
    runtask(GeomColumns(year='2015'))


@with_setup(setup, teardown)
def test_geoid_columns_run():

    runtask(GeoidColumns(year='2015'))