为什么会话不是最新的?

时间:2014-09-23 01:33:22

标签: python unit-testing session orm sqlalchemy

我有一个像这样定义的单元测试。 setUp正常工作。 Config是一个包含mysql可执行文件位置和数据库名称的字典。

import unittest

#mercury
from DataInterface import SqlDataSources
from CandC import BlankSlate
from CandC import Configuration

#under test
from CandC import AddTask

#This is a temporary measure until a more elegant configuration is implemented
configpath = '/somewhere/in/my/filesystem'

class AddTaskTest(unittest.TestCase):
  '''
  Test adding a task
  '''

  def setUp(self):
    '''
    blank out the database
    '''
    config = Configuration.Config(configpath)
    BlankSlate.wipe(config)

  def test_addAndRetreive(self):
    '''
    add and retrieve a task
    '''

    config = Configuration.Config(configpath)

    source = SqlDataSources.Source(config.sqlCredentials())

    #of type sqlalchemy.orm.session.Session
    session = source.sqlSession()

    #insert some test tasks
    AddTask.insert('Tests/CandC/test_task', session)
    AddTask.insert('Tests/CandC/test_task', session)
    AddTask.insert('Tests/CandC/test_task', session)
    session.close()

    #retreive the test task
    #ask for more than should be in there
    session = source.sqlSession()
    tasks = source.openTasksReady(4, session)

    #three should return
    self.assertEqual(len(tasks), 3)

Source类看起来像这样:

from ActionResources import WorkHandlers

__author__ = 'packet-racket'

'''
Encapsulates all data access to mysql via sqlalchemy. Maintains stateful connectiont to db'''

#sqlalchemy connection
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

#mercury objects
from MercuryAlchemy import SchemaObjects

#needed built-ins
from datetime import datetime

class Source():

  '''
  connection imports
  '''
  def __init__(self, connectionParameters):
    '''
    make and keep up a connection to mysql

    connectionParameters -- a dict
    '''
    #connect

    # self.engine = create_engine('mysql+mysqldb://root:@localhost:3306/mercury', pool_recycle=3600)
    #KLUDGE -- pool_recycle
    self.engine = create_engine(connectionParameters, pool_recycle=3600)
    self.session = sessionmaker()
    self.session.configure(bind=self.engine)

  def add(self, schemaObject, sess):
    '''
    ACID addition of a SchemaObject type

    schemObject -- SchemaObjet.whatever
    '''
    sess.add(schemaObject)


  def sqlSession(self):
    '''

    :return: a session to work with
    '''
    return self.session()

  def openTasksReady(self, thisMany, aSession):
    '''
    return thisMany open tasks that are ready to start

    thisMany -- integer
    sess - session to work with
    '''
    return aSession.query(SchemaObjects.Task).filter(
      SchemaObjects.Task.status == 'open').filter(
      SchemaObjects.Task.start_time <= datetime.now()).all()

AddTask看起来像这样:

import ast

from datetime import datetime

#mercury imports
from ActionResources import WorkHandlers
from DataInterface import SessionHelpers

def insert(fileName, session):
  '''
  insert task from given file name

  session -- sql alchemy session
  '''

  lines = ''
  with open(fileName, 'rb') as atHand:
    lines = atHand.readlines()

    #commbine file into one line, getting rid of newlines
    lines = ''.join(lines)
    lines = lines.split('\n')
    #no blank elements
    lines = [item for item in lines if len(item) > 0]
    lines = ''.join(lines)

  inputDict = ast.literal_eval(lines)

  #TODO -- maybe a cleaner way but whatever
  #needs to be manually changed with every new workhandler -- big kludge
  '''
  How it should be done.

  Scane the WorkHandlers module for one matching the name of the one given in input.  Create and insert one of that found type.
  '''
  mappings = {
    'createonedeleteold': WorkHandlers.CreateOneDeleteOld,
    'donothing': WorkHandlers.DoNothing
  }

  #create worker
  specifiedHandler = inputDict['work_handler'].lower()
  if specifiedHandler in mappings:
    #map the class instantiator to a variable
    handlerClass = mappings[specifiedHandler]
  else:
    raise Exception('Invalid work handler named.')

  #remember this:
  #datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S.%f')

  if 'start_time' in inputDict:
    #format: '2014-09-19 15:19:50.414395'
    start_time = datetime.strptime(inputDict['start_time'], '%Y-%m-%d %H:%M:%S.%f')
  else:
    start_time = datetime.now()

  task = handlerClass(description=inputDict['description'],
                      status='open',
                      created=datetime.now(),
                      start_time=start_time)

  #insert into tasks
  session.add(task)
  session.commit()

SqlDataSources是我自己的类,它与我的SQL Alchemy设置进行交互。它的方法需要一个会话并使用它来检索或插入数据。问题是检索并不总是获取任何对象。它间歇性地失败了。如果我在调试模式下运行它并在行tasks = source.openTasksReady(4, session)之前暂停,它总是通过测试。可能是我的问题?

0 个答案:

没有答案