Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么会话可能不是当前会话?_Python_Unit Testing_Session_Orm_Sqlalchemy - Fatal编程技术网

Python 为什么会话可能不是当前会话?

Python 为什么会话可能不是当前会话?,python,unit-testing,session,orm,sqlalchemy,Python,Unit Testing,Session,Orm,Sqlalchemy,我有一个这样定义的单元测试。设置工作正常。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

我有一个这样定义的单元测试。设置工作正常。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)
源类如下所示:

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()
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.opentasksrady4,session行之前暂停,它总是通过测试。我可能有什么问题?

你能把剩下的代码贴出来吗?在测试框架中,会话管理有很多地方会遇到障碍。我还承认,我将粘贴在这里的代码限制为我认为在执行过程中被击中的代码。如果需要,我可以回去批量粘贴这些类,但是有一些函数没有被调用,还有其他一些东西是这个项目当前草稿的一部分。好吧,如果不能复制你的问题,我很难准确地告诉你,但我想尝试以下几件事:1理顺你的会话使用。有时从源类获取,有时将其传递给源类。您在函数内部提交它,在其他地方关闭它。所有这些行为都会导致有趣的结果。对Session.close、Session.commit、Session.rollback的调用都将结束当前事务。另一个要检查的角度:确保你在一条线上工作谢谢。我查一下。