body_hash
stringlengths 64
64
| body
stringlengths 23
109k
| docstring
stringlengths 1
57k
| path
stringlengths 4
198
| name
stringlengths 1
115
| repository_name
stringlengths 7
111
| repository_stars
float64 0
191k
| lang
stringclasses 1
value | body_without_docstring
stringlengths 14
108k
| unified
stringlengths 45
133k
|
---|---|---|---|---|---|---|---|---|---|
9ca0bc016b0489a0dc8193fddd0edf67a69289d3ddc33786dc960f12e9bd8f3a | def transferFiles(src, dst, arrangementInfo):
'transferFiles(): Carries out the actual transfer of files.\n \n Arguments: \n [1] Source - path to source directory; \n [2] Destination - path to destination directory.\n \n Returns:\n True:\n False: \n '
returnData = {}
src = os.path.abspath(src)
dst = os.path.abspath(dst)
srcDirectory = src
dstDirectory = dst
if (os.path.isdir(dstDirectory) != True):
try:
os.makedirs(dst)
except os.error as osError:
print_error(osError)
globalvars.errorList.append((row + [str(osError)]))
print_error(errorcodes.ERROR_CANNOT_CREATE_DESTINATION_DIRECTORY['message'].format(dst))
exit(errorcodes.ERROR_CANNOT_CREATE_DESTINATION_DIRECTORY['code'])
prevHighestSerialNo = 0
else:
prevHighestSerialNo = getHighestSerialNo(srcDirectory)
print_info('Previous highest file serial number: {}'.format(prevHighestSerialNo))
try:
fileList = sorted(glob.glob(os.path.join(src, ('*.' + globalvars.ext))))
totalNumFiles = len(fileList)
numFilesTransferred = 0
if (totalNumFiles == 0):
returnData['status'] = False
print_error("No files found with extension '{}'!".format(globalvars.ext))
returnData['comment'] = "No files found with extension '{}'!".format(globalvars.ext)
return returnData
currentSerialNo = (prevHighestSerialNo + 1)
for fileName in fileList[prevHighestSerialNo:]:
srcFileName = os.path.basename(fileName)
srcFileExt = srcFileName.split('.')[(- 1)]
recordParams = {}
recordParams['fileName'] = fileName
recordParams['fileSize'] = os.path.getsize(fileName)
recordParams['fmtName'] = getFileFormatName(srcFileName)
recordParams['fmtVer'] = getFileFormatVersion(srcFileName)
recordParams[globalvars.ARRANGEMENT_INFO_LABEL] = arrangementInfo
metadataRecord = initMetadataRecord(recordParams)
uniqueId = metadataRecord['_id']
idAssignmentEvent = createIDAssignmentEvent(uniqueId)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(idAssignmentEvent)
dstFilePrelimPath = os.path.join(dst, uniqueId, srcFileName)
dstFileUniquePath = os.path.join(dst, uniqueId, ((uniqueId + '.') + srcFileExt))
dstFileName = os.path.basename(dstFileUniquePath)
srcChecksum = getFileChecksum(fileName)
msgDigestCalcEvent = createMsgDigestCalcEvent(srcChecksum, globalvars.CHECKSUM_ALGO)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(msgDigestCalcEvent)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_chars.name][globalvars.labels.obj_fixity.name][globalvars.labels.obj_msgdgst_algo.name] = globalvars.CHECKSUM_ALGO
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_chars.name][globalvars.labels.obj_fixity.name][globalvars.labels.obj_msgdgst.name] = srcChecksum
(path, nameFile) = os.path.split(dstFilePrelimPath)
print_info("{} '{}' from '{}' to '{}'".format(('Moving' if (globalvars.move == True) else 'Copying'), os.path.basename(fileName), src, path))
if (os.path.isdir(path) != True):
try:
os.makedirs(path)
shutil.copy(fileName, dstFilePrelimPath)
except os.error as osError:
print_error(osError)
globalvars.errorList.append((row + [str(osError)]))
print_error(errorcodes.ERROR_CANNOT_CREATE_DESTINATION_DIRECTORY['message'].format(path))
exit(errorcodes.ERROR_CANNOT_CREATE_DESTINATION_DIRECTORY['code'])
if (globalvars.move == True):
eventType = 'migration'
else:
eventType = 'replication'
fileCopyEvent = createFileCopyEvent(eventType, fileName, dstFilePrelimPath)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(fileCopyEvent)
os.rename(dstFilePrelimPath, dstFileUniquePath)
filenameChangeEvent = createFilenameChangeEvent(dstFilePrelimPath, dstFileUniquePath)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(filenameChangeEvent)
dstChecksum = getFileChecksum(dstFileUniquePath)
if (dstChecksum != srcChecksum):
print_error("Checksum mismatch for '{}', and '{}'".format(fileName, dstFileUniquePath))
try:
os.remove(dstFileUniquePath)
except os.error as ExceptionFileRemoval:
print_error(ExceptionFileRemoval)
print_error(errorcodes.ERROR_CANNOT_REMOVE_FILE['message'])
exit(errorcodes.ERROR_CANNOT_REMOVE_FILE['code'])
deleteRecordFromDB(uniqueId)
returnData['status'] = False
returnData['comment'] = "Checksum mismatch for '{}', and '{}'. Aborted transfers for remaining files in directory.".format(fileName, dstFileUniquePath)
return returnData
else:
fixityCheckEvent = createFixityCheckEvent(True, dstChecksum)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(fixityCheckEvent)
metadataRecord = updateSerialNumber(metadataRecord, currentSerialNo)
accessionEvent = createAccessionEvent()
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(accessionEvent)
dbRetValue = insertRecordInDB(metadataRecord)
if (dbRetValue != uniqueId):
print_error('DB Insert operation not successful. Unique ID returned by DB does not match the one provided by the script. Exiting.')
returnData['status'] = False
returnData['comment'] = 'DB Insert operation not successful.'
return returnData
if (globalvars.move == True):
try:
os.remove(dstFileUniquePath)
except os.error as ExceptionFileRemoval:
print_error("Cannot remove file '{}' from source '{}' after the move. Only a copy was made to the destination.".format(srcFileName, srcDirectory))
print_error(ExceptionFileRemoval)
print_error(errorcodes.ERROR_CANNOT_REMOVE_FILE['message'])
exit(errorcodes.ERROR_CANNOT_REMOVE_FILE['code'])
currentSerialNo += 1
numFilesTransferred += 1
except Exception as shutilException:
print_error(shutilException)
print_error("Cannot complete transfer for '{}', and '{}'".format(src, dst))
print_error(shutilException)
returnData['status'] = False
commentString = ('Error: ' + shutilException)
returnData['comment'] = commentString
return returnData
returnData['status'] = True
commentString = 'Success. {} out of {} files transferred'.format(numFilesTransferred, totalNumFiles)
returnData['comment'] = commentString
return returnData | transferFiles(): Carries out the actual transfer of files.
Arguments:
[1] Source - path to source directory;
[2] Destination - path to destination directory.
Returns:
True:
False: | accession.py | transferFiles | CLACI/DarkArchiveWorkflow | 2 | python | def transferFiles(src, dst, arrangementInfo):
'transferFiles(): Carries out the actual transfer of files.\n \n Arguments: \n [1] Source - path to source directory; \n [2] Destination - path to destination directory.\n \n Returns:\n True:\n False: \n '
returnData = {}
src = os.path.abspath(src)
dst = os.path.abspath(dst)
srcDirectory = src
dstDirectory = dst
if (os.path.isdir(dstDirectory) != True):
try:
os.makedirs(dst)
except os.error as osError:
print_error(osError)
globalvars.errorList.append((row + [str(osError)]))
print_error(errorcodes.ERROR_CANNOT_CREATE_DESTINATION_DIRECTORY['message'].format(dst))
exit(errorcodes.ERROR_CANNOT_CREATE_DESTINATION_DIRECTORY['code'])
prevHighestSerialNo = 0
else:
prevHighestSerialNo = getHighestSerialNo(srcDirectory)
print_info('Previous highest file serial number: {}'.format(prevHighestSerialNo))
try:
fileList = sorted(glob.glob(os.path.join(src, ('*.' + globalvars.ext))))
totalNumFiles = len(fileList)
numFilesTransferred = 0
if (totalNumFiles == 0):
returnData['status'] = False
print_error("No files found with extension '{}'!".format(globalvars.ext))
returnData['comment'] = "No files found with extension '{}'!".format(globalvars.ext)
return returnData
currentSerialNo = (prevHighestSerialNo + 1)
for fileName in fileList[prevHighestSerialNo:]:
srcFileName = os.path.basename(fileName)
srcFileExt = srcFileName.split('.')[(- 1)]
recordParams = {}
recordParams['fileName'] = fileName
recordParams['fileSize'] = os.path.getsize(fileName)
recordParams['fmtName'] = getFileFormatName(srcFileName)
recordParams['fmtVer'] = getFileFormatVersion(srcFileName)
recordParams[globalvars.ARRANGEMENT_INFO_LABEL] = arrangementInfo
metadataRecord = initMetadataRecord(recordParams)
uniqueId = metadataRecord['_id']
idAssignmentEvent = createIDAssignmentEvent(uniqueId)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(idAssignmentEvent)
dstFilePrelimPath = os.path.join(dst, uniqueId, srcFileName)
dstFileUniquePath = os.path.join(dst, uniqueId, ((uniqueId + '.') + srcFileExt))
dstFileName = os.path.basename(dstFileUniquePath)
srcChecksum = getFileChecksum(fileName)
msgDigestCalcEvent = createMsgDigestCalcEvent(srcChecksum, globalvars.CHECKSUM_ALGO)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(msgDigestCalcEvent)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_chars.name][globalvars.labels.obj_fixity.name][globalvars.labels.obj_msgdgst_algo.name] = globalvars.CHECKSUM_ALGO
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_chars.name][globalvars.labels.obj_fixity.name][globalvars.labels.obj_msgdgst.name] = srcChecksum
(path, nameFile) = os.path.split(dstFilePrelimPath)
print_info("{} '{}' from '{}' to '{}'".format(('Moving' if (globalvars.move == True) else 'Copying'), os.path.basename(fileName), src, path))
if (os.path.isdir(path) != True):
try:
os.makedirs(path)
shutil.copy(fileName, dstFilePrelimPath)
except os.error as osError:
print_error(osError)
globalvars.errorList.append((row + [str(osError)]))
print_error(errorcodes.ERROR_CANNOT_CREATE_DESTINATION_DIRECTORY['message'].format(path))
exit(errorcodes.ERROR_CANNOT_CREATE_DESTINATION_DIRECTORY['code'])
if (globalvars.move == True):
eventType = 'migration'
else:
eventType = 'replication'
fileCopyEvent = createFileCopyEvent(eventType, fileName, dstFilePrelimPath)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(fileCopyEvent)
os.rename(dstFilePrelimPath, dstFileUniquePath)
filenameChangeEvent = createFilenameChangeEvent(dstFilePrelimPath, dstFileUniquePath)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(filenameChangeEvent)
dstChecksum = getFileChecksum(dstFileUniquePath)
if (dstChecksum != srcChecksum):
print_error("Checksum mismatch for '{}', and '{}'".format(fileName, dstFileUniquePath))
try:
os.remove(dstFileUniquePath)
except os.error as ExceptionFileRemoval:
print_error(ExceptionFileRemoval)
print_error(errorcodes.ERROR_CANNOT_REMOVE_FILE['message'])
exit(errorcodes.ERROR_CANNOT_REMOVE_FILE['code'])
deleteRecordFromDB(uniqueId)
returnData['status'] = False
returnData['comment'] = "Checksum mismatch for '{}', and '{}'. Aborted transfers for remaining files in directory.".format(fileName, dstFileUniquePath)
return returnData
else:
fixityCheckEvent = createFixityCheckEvent(True, dstChecksum)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(fixityCheckEvent)
metadataRecord = updateSerialNumber(metadataRecord, currentSerialNo)
accessionEvent = createAccessionEvent()
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(accessionEvent)
dbRetValue = insertRecordInDB(metadataRecord)
if (dbRetValue != uniqueId):
print_error('DB Insert operation not successful. Unique ID returned by DB does not match the one provided by the script. Exiting.')
returnData['status'] = False
returnData['comment'] = 'DB Insert operation not successful.'
return returnData
if (globalvars.move == True):
try:
os.remove(dstFileUniquePath)
except os.error as ExceptionFileRemoval:
print_error("Cannot remove file '{}' from source '{}' after the move. Only a copy was made to the destination.".format(srcFileName, srcDirectory))
print_error(ExceptionFileRemoval)
print_error(errorcodes.ERROR_CANNOT_REMOVE_FILE['message'])
exit(errorcodes.ERROR_CANNOT_REMOVE_FILE['code'])
currentSerialNo += 1
numFilesTransferred += 1
except Exception as shutilException:
print_error(shutilException)
print_error("Cannot complete transfer for '{}', and '{}'".format(src, dst))
print_error(shutilException)
returnData['status'] = False
commentString = ('Error: ' + shutilException)
returnData['comment'] = commentString
return returnData
returnData['status'] = True
commentString = 'Success. {} out of {} files transferred'.format(numFilesTransferred, totalNumFiles)
returnData['comment'] = commentString
return returnData | def transferFiles(src, dst, arrangementInfo):
'transferFiles(): Carries out the actual transfer of files.\n \n Arguments: \n [1] Source - path to source directory; \n [2] Destination - path to destination directory.\n \n Returns:\n True:\n False: \n '
returnData = {}
src = os.path.abspath(src)
dst = os.path.abspath(dst)
srcDirectory = src
dstDirectory = dst
if (os.path.isdir(dstDirectory) != True):
try:
os.makedirs(dst)
except os.error as osError:
print_error(osError)
globalvars.errorList.append((row + [str(osError)]))
print_error(errorcodes.ERROR_CANNOT_CREATE_DESTINATION_DIRECTORY['message'].format(dst))
exit(errorcodes.ERROR_CANNOT_CREATE_DESTINATION_DIRECTORY['code'])
prevHighestSerialNo = 0
else:
prevHighestSerialNo = getHighestSerialNo(srcDirectory)
print_info('Previous highest file serial number: {}'.format(prevHighestSerialNo))
try:
fileList = sorted(glob.glob(os.path.join(src, ('*.' + globalvars.ext))))
totalNumFiles = len(fileList)
numFilesTransferred = 0
if (totalNumFiles == 0):
returnData['status'] = False
print_error("No files found with extension '{}'!".format(globalvars.ext))
returnData['comment'] = "No files found with extension '{}'!".format(globalvars.ext)
return returnData
currentSerialNo = (prevHighestSerialNo + 1)
for fileName in fileList[prevHighestSerialNo:]:
srcFileName = os.path.basename(fileName)
srcFileExt = srcFileName.split('.')[(- 1)]
recordParams = {}
recordParams['fileName'] = fileName
recordParams['fileSize'] = os.path.getsize(fileName)
recordParams['fmtName'] = getFileFormatName(srcFileName)
recordParams['fmtVer'] = getFileFormatVersion(srcFileName)
recordParams[globalvars.ARRANGEMENT_INFO_LABEL] = arrangementInfo
metadataRecord = initMetadataRecord(recordParams)
uniqueId = metadataRecord['_id']
idAssignmentEvent = createIDAssignmentEvent(uniqueId)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(idAssignmentEvent)
dstFilePrelimPath = os.path.join(dst, uniqueId, srcFileName)
dstFileUniquePath = os.path.join(dst, uniqueId, ((uniqueId + '.') + srcFileExt))
dstFileName = os.path.basename(dstFileUniquePath)
srcChecksum = getFileChecksum(fileName)
msgDigestCalcEvent = createMsgDigestCalcEvent(srcChecksum, globalvars.CHECKSUM_ALGO)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(msgDigestCalcEvent)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_chars.name][globalvars.labels.obj_fixity.name][globalvars.labels.obj_msgdgst_algo.name] = globalvars.CHECKSUM_ALGO
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_chars.name][globalvars.labels.obj_fixity.name][globalvars.labels.obj_msgdgst.name] = srcChecksum
(path, nameFile) = os.path.split(dstFilePrelimPath)
print_info("{} '{}' from '{}' to '{}'".format(('Moving' if (globalvars.move == True) else 'Copying'), os.path.basename(fileName), src, path))
if (os.path.isdir(path) != True):
try:
os.makedirs(path)
shutil.copy(fileName, dstFilePrelimPath)
except os.error as osError:
print_error(osError)
globalvars.errorList.append((row + [str(osError)]))
print_error(errorcodes.ERROR_CANNOT_CREATE_DESTINATION_DIRECTORY['message'].format(path))
exit(errorcodes.ERROR_CANNOT_CREATE_DESTINATION_DIRECTORY['code'])
if (globalvars.move == True):
eventType = 'migration'
else:
eventType = 'replication'
fileCopyEvent = createFileCopyEvent(eventType, fileName, dstFilePrelimPath)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(fileCopyEvent)
os.rename(dstFilePrelimPath, dstFileUniquePath)
filenameChangeEvent = createFilenameChangeEvent(dstFilePrelimPath, dstFileUniquePath)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(filenameChangeEvent)
dstChecksum = getFileChecksum(dstFileUniquePath)
if (dstChecksum != srcChecksum):
print_error("Checksum mismatch for '{}', and '{}'".format(fileName, dstFileUniquePath))
try:
os.remove(dstFileUniquePath)
except os.error as ExceptionFileRemoval:
print_error(ExceptionFileRemoval)
print_error(errorcodes.ERROR_CANNOT_REMOVE_FILE['message'])
exit(errorcodes.ERROR_CANNOT_REMOVE_FILE['code'])
deleteRecordFromDB(uniqueId)
returnData['status'] = False
returnData['comment'] = "Checksum mismatch for '{}', and '{}'. Aborted transfers for remaining files in directory.".format(fileName, dstFileUniquePath)
return returnData
else:
fixityCheckEvent = createFixityCheckEvent(True, dstChecksum)
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(fixityCheckEvent)
metadataRecord = updateSerialNumber(metadataRecord, currentSerialNo)
accessionEvent = createAccessionEvent()
metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name].append(accessionEvent)
dbRetValue = insertRecordInDB(metadataRecord)
if (dbRetValue != uniqueId):
print_error('DB Insert operation not successful. Unique ID returned by DB does not match the one provided by the script. Exiting.')
returnData['status'] = False
returnData['comment'] = 'DB Insert operation not successful.'
return returnData
if (globalvars.move == True):
try:
os.remove(dstFileUniquePath)
except os.error as ExceptionFileRemoval:
print_error("Cannot remove file '{}' from source '{}' after the move. Only a copy was made to the destination.".format(srcFileName, srcDirectory))
print_error(ExceptionFileRemoval)
print_error(errorcodes.ERROR_CANNOT_REMOVE_FILE['message'])
exit(errorcodes.ERROR_CANNOT_REMOVE_FILE['code'])
currentSerialNo += 1
numFilesTransferred += 1
except Exception as shutilException:
print_error(shutilException)
print_error("Cannot complete transfer for '{}', and '{}'".format(src, dst))
print_error(shutilException)
returnData['status'] = False
commentString = ('Error: ' + shutilException)
returnData['comment'] = commentString
return returnData
returnData['status'] = True
commentString = 'Success. {} out of {} files transferred'.format(numFilesTransferred, totalNumFiles)
returnData['comment'] = commentString
return returnData<|docstring|>transferFiles(): Carries out the actual transfer of files.
Arguments:
[1] Source - path to source directory;
[2] Destination - path to destination directory.
Returns:
True:
False:<|endoftext|> |
822f52fefeacdbe3cdf235eac34909642a2619b91790cddf034e6f3951c52225 | async def subscribe(p2p_client: P2PClient, topic: str) -> anyio.abc.SocketStream:
'\n Subscribes to the specified topic.\n :param p2p_client: P2P daemon client.\n :param topic: Topic on which to subscribe.\n :return: A socket stream object. This stream can be used to read data posted by other peers on the topic.\n '
return (await p2p_client.pubsub_subscribe(topic)) | Subscribes to the specified topic.
:param p2p_client: P2P daemon client.
:param topic: Topic on which to subscribe.
:return: A socket stream object. This stream can be used to read data posted by other peers on the topic. | src/aleph/services/p2p/pubsub.py | subscribe | odesenfans/pyaleph | 0 | python | async def subscribe(p2p_client: P2PClient, topic: str) -> anyio.abc.SocketStream:
'\n Subscribes to the specified topic.\n :param p2p_client: P2P daemon client.\n :param topic: Topic on which to subscribe.\n :return: A socket stream object. This stream can be used to read data posted by other peers on the topic.\n '
return (await p2p_client.pubsub_subscribe(topic)) | async def subscribe(p2p_client: P2PClient, topic: str) -> anyio.abc.SocketStream:
'\n Subscribes to the specified topic.\n :param p2p_client: P2P daemon client.\n :param topic: Topic on which to subscribe.\n :return: A socket stream object. This stream can be used to read data posted by other peers on the topic.\n '
return (await p2p_client.pubsub_subscribe(topic))<|docstring|>Subscribes to the specified topic.
:param p2p_client: P2P daemon client.
:param topic: Topic on which to subscribe.
:return: A socket stream object. This stream can be used to read data posted by other peers on the topic.<|endoftext|> |
12b155a9827c2bad0763f01faa5e3a718fc91079ac98d7e61fe6bf464237a300 | async def receive_pubsub_messages(stream: anyio.abc.SocketStream) -> AsyncIterator[PSMessage]:
'\n Receives messages from a P2P pubsub topic in a loop and yields them one by one.\n :param stream: The stream (= return value of the `subscribe` function) to read data from.\n '
while True:
pubsub_msg = PSMessage()
(await read_pbmsg_safe(stream, pubsub_msg))
LOGGER.debug(('New message received %r' % pubsub_msg))
(yield pubsub_msg) | Receives messages from a P2P pubsub topic in a loop and yields them one by one.
:param stream: The stream (= return value of the `subscribe` function) to read data from. | src/aleph/services/p2p/pubsub.py | receive_pubsub_messages | odesenfans/pyaleph | 0 | python | async def receive_pubsub_messages(stream: anyio.abc.SocketStream) -> AsyncIterator[PSMessage]:
'\n Receives messages from a P2P pubsub topic in a loop and yields them one by one.\n :param stream: The stream (= return value of the `subscribe` function) to read data from.\n '
while True:
pubsub_msg = PSMessage()
(await read_pbmsg_safe(stream, pubsub_msg))
LOGGER.debug(('New message received %r' % pubsub_msg))
(yield pubsub_msg) | async def receive_pubsub_messages(stream: anyio.abc.SocketStream) -> AsyncIterator[PSMessage]:
'\n Receives messages from a P2P pubsub topic in a loop and yields them one by one.\n :param stream: The stream (= return value of the `subscribe` function) to read data from.\n '
while True:
pubsub_msg = PSMessage()
(await read_pbmsg_safe(stream, pubsub_msg))
LOGGER.debug(('New message received %r' % pubsub_msg))
(yield pubsub_msg)<|docstring|>Receives messages from a P2P pubsub topic in a loop and yields them one by one.
:param stream: The stream (= return value of the `subscribe` function) to read data from.<|endoftext|> |
dbf3d5f9b6e30276cf7b46a9d6c6c4bf9fabaf213934cb766fe94f9321da8478 | async def publish(p2p_client: P2PClient, topic: str, message: Union[(bytes, str)]) -> None:
'\n Publishes a message on the specified topic.\n :param p2p_client: P2P daemon client.\n :param topic: Topic on which to send the message.\n :param message: The message itself. Can be provided as bytes or as a string.\n '
data = (message if isinstance(message, bytes) else message.encode('UTF-8'))
(await p2p_client.pubsub_publish(topic, data)) | Publishes a message on the specified topic.
:param p2p_client: P2P daemon client.
:param topic: Topic on which to send the message.
:param message: The message itself. Can be provided as bytes or as a string. | src/aleph/services/p2p/pubsub.py | publish | odesenfans/pyaleph | 0 | python | async def publish(p2p_client: P2PClient, topic: str, message: Union[(bytes, str)]) -> None:
'\n Publishes a message on the specified topic.\n :param p2p_client: P2P daemon client.\n :param topic: Topic on which to send the message.\n :param message: The message itself. Can be provided as bytes or as a string.\n '
data = (message if isinstance(message, bytes) else message.encode('UTF-8'))
(await p2p_client.pubsub_publish(topic, data)) | async def publish(p2p_client: P2PClient, topic: str, message: Union[(bytes, str)]) -> None:
'\n Publishes a message on the specified topic.\n :param p2p_client: P2P daemon client.\n :param topic: Topic on which to send the message.\n :param message: The message itself. Can be provided as bytes or as a string.\n '
data = (message if isinstance(message, bytes) else message.encode('UTF-8'))
(await p2p_client.pubsub_publish(topic, data))<|docstring|>Publishes a message on the specified topic.
:param p2p_client: P2P daemon client.
:param topic: Topic on which to send the message.
:param message: The message itself. Can be provided as bytes or as a string.<|endoftext|> |
ae64dc7da0de33286c1d84eaa27ad81e9ae1d1dbf2e36e63f87ef9b14065bf84 | def __init__(self, name: str, parent=None, **kargs):
'\n Subclasses must pass the `name` parameter as a value into the\n\n :param name:\n :param parent:\n :param kargs:\n '
object.__init__(self)
self.__name = name
if (parent is not None):
assert isinstance(parent, RunContext), 'Parent must be a run context instance'
assert (parent.name == name), 'parent must be of type {0} (found {1}'.format(name, parent.name)
self._parent = parent | Subclasses must pass the `name` parameter as a value into the
:param name:
:param parent:
:param kargs: | python/runcontext/runcontext.py | __init__ | groboclown/x-context | 0 | python | def __init__(self, name: str, parent=None, **kargs):
'\n Subclasses must pass the `name` parameter as a value into the\n\n :param name:\n :param parent:\n :param kargs:\n '
object.__init__(self)
self.__name = name
if (parent is not None):
assert isinstance(parent, RunContext), 'Parent must be a run context instance'
assert (parent.name == name), 'parent must be of type {0} (found {1}'.format(name, parent.name)
self._parent = parent | def __init__(self, name: str, parent=None, **kargs):
'\n Subclasses must pass the `name` parameter as a value into the\n\n :param name:\n :param parent:\n :param kargs:\n '
object.__init__(self)
self.__name = name
if (parent is not None):
assert isinstance(parent, RunContext), 'Parent must be a run context instance'
assert (parent.name == name), 'parent must be of type {0} (found {1}'.format(name, parent.name)
self._parent = parent<|docstring|>Subclasses must pass the `name` parameter as a value into the
:param name:
:param parent:
:param kargs:<|endoftext|> |
836073e6d09e897a7eb9949e45a4608a5d92b76f6394272eeb5e1745dc292e94 | def enter_context(self, **kargs):
'\n Called when a child context is entered. Must return another RunContext instance of this type,\n or raise an error.\n\n :param kargs: variable arguments, as required by the context.\n :return: RunContext\n :raise: NestedContextError\n '
raise NotImplemented() | Called when a child context is entered. Must return another RunContext instance of this type,
or raise an error.
:param kargs: variable arguments, as required by the context.
:return: RunContext
:raise: NestedContextError | python/runcontext/runcontext.py | enter_context | groboclown/x-context | 0 | python | def enter_context(self, **kargs):
'\n Called when a child context is entered. Must return another RunContext instance of this type,\n or raise an error.\n\n :param kargs: variable arguments, as required by the context.\n :return: RunContext\n :raise: NestedContextError\n '
raise NotImplemented() | def enter_context(self, **kargs):
'\n Called when a child context is entered. Must return another RunContext instance of this type,\n or raise an error.\n\n :param kargs: variable arguments, as required by the context.\n :return: RunContext\n :raise: NestedContextError\n '
raise NotImplemented()<|docstring|>Called when a child context is entered. Must return another RunContext instance of this type,
or raise an error.
:param kargs: variable arguments, as required by the context.
:return: RunContext
:raise: NestedContextError<|endoftext|> |
ccd40b35dcddb1c671f32f97d3f59cfa6f096a781a8d37c69073447d88b4456c | def main(plan, resume, collaborators_file, data_config_fname, validate_without_patches_flag, data_in_memory_flag, data_queue_max_length, data_queue_num_workers, torch_threads, kmp_affinity_flag, logging_config_path, logging_default_level, logging_directory, model_device, **kwargs):
'Run the federation simulation from the federation (FL) plan.\n\n Runs a federated training from the federation (FL) plan but creates the\n aggregator and collaborators on the same compute node. This allows\n the developer to test the model and data loaders before running\n on the remote collaborator nodes.\n\n Args:\n plan : The Federation (FL) plan (YAML file)\n resume : Whether or not the aggregator is told to resume from previous best\n collaborators_file : The file listing the collaborators\n data_config_fname : The file describing where the dataset is located on the collaborators\n validate_withouut_patches_flag : controls a model init kwarg\n data_in_memory_flag : controls a data init kwarg \n data_queue_max_length : controls a data init kwarg \n data_queue_num_workers : controls a data init kwarg\n torch_threads : number of threads to set in torch \n kmp_affinity_flag : controls a model init kwarg\n logging_config_path : The log file\n logging_default_level : The log level\n **kwargs : Variable parameters to pass to the function\n\n '
script_dir = os.path.dirname(os.path.realpath(__file__))
base_dir = os.path.join(script_dir, 'federations')
plan_dir = os.path.join(base_dir, 'plans')
weights_dir = os.path.join(base_dir, 'weights')
metadata_dir = os.path.join(base_dir, 'metadata')
collaborators_dir = os.path.join(base_dir, 'collaborator_lists')
logging_config_path = os.path.join(script_dir, logging_config_path)
logging_directory = os.path.join(script_dir, logging_directory)
setup_logging(path=logging_config_path, default_level=logging_default_level, logging_directory=logging_directory)
flplan = parse_fl_plan(os.path.join(plan_dir, plan))
model_init_kwarg_keys = ['validate_without_patches', 'torch_threads', 'kmp_affinity']
model_init_kwarg_vals = [validate_without_patches_flag, torch_threads, kmp_affinity_flag]
for (key, value) in zip(model_init_kwarg_keys, model_init_kwarg_vals):
if ((value is not None) and (value != False)):
flplan['model_object_init']['init_kwargs'][key] = value
data_init_kwarg_keys = ['in_memory', 'q_max_length', 'q_num_workers']
data_init_kwarg_vals = [data_in_memory_flag, data_queue_max_length, data_queue_num_workers]
for (key, value) in zip(data_init_kwarg_keys, data_init_kwarg_vals):
if ((value is not None) and (value != False)):
flplan['data_object_init']['init_kwargs'][key] = value
local_config = load_yaml(os.path.join(base_dir, data_config_fname))
collaborator_common_names = load_yaml(os.path.join(collaborators_dir, collaborators_file))['collaborator_common_names']
federate(flplan=flplan, resume=resume, local_config=local_config, collaborator_common_names=collaborator_common_names, base_dir=base_dir, weights_dir=weights_dir, metadata_dir=metadata_dir, model_device=model_device) | Run the federation simulation from the federation (FL) plan.
Runs a federated training from the federation (FL) plan but creates the
aggregator and collaborators on the same compute node. This allows
the developer to test the model and data loaders before running
on the remote collaborator nodes.
Args:
plan : The Federation (FL) plan (YAML file)
resume : Whether or not the aggregator is told to resume from previous best
collaborators_file : The file listing the collaborators
data_config_fname : The file describing where the dataset is located on the collaborators
validate_withouut_patches_flag : controls a model init kwarg
data_in_memory_flag : controls a data init kwarg
data_queue_max_length : controls a data init kwarg
data_queue_num_workers : controls a data init kwarg
torch_threads : number of threads to set in torch
kmp_affinity_flag : controls a model init kwarg
logging_config_path : The log file
logging_default_level : The log level
**kwargs : Variable parameters to pass to the function | bin/run_simulation_from_flplan.py | main | sarthakpati/OpenFederatedLearning | 1 | python | def main(plan, resume, collaborators_file, data_config_fname, validate_without_patches_flag, data_in_memory_flag, data_queue_max_length, data_queue_num_workers, torch_threads, kmp_affinity_flag, logging_config_path, logging_default_level, logging_directory, model_device, **kwargs):
'Run the federation simulation from the federation (FL) plan.\n\n Runs a federated training from the federation (FL) plan but creates the\n aggregator and collaborators on the same compute node. This allows\n the developer to test the model and data loaders before running\n on the remote collaborator nodes.\n\n Args:\n plan : The Federation (FL) plan (YAML file)\n resume : Whether or not the aggregator is told to resume from previous best\n collaborators_file : The file listing the collaborators\n data_config_fname : The file describing where the dataset is located on the collaborators\n validate_withouut_patches_flag : controls a model init kwarg\n data_in_memory_flag : controls a data init kwarg \n data_queue_max_length : controls a data init kwarg \n data_queue_num_workers : controls a data init kwarg\n torch_threads : number of threads to set in torch \n kmp_affinity_flag : controls a model init kwarg\n logging_config_path : The log file\n logging_default_level : The log level\n **kwargs : Variable parameters to pass to the function\n\n '
script_dir = os.path.dirname(os.path.realpath(__file__))
base_dir = os.path.join(script_dir, 'federations')
plan_dir = os.path.join(base_dir, 'plans')
weights_dir = os.path.join(base_dir, 'weights')
metadata_dir = os.path.join(base_dir, 'metadata')
collaborators_dir = os.path.join(base_dir, 'collaborator_lists')
logging_config_path = os.path.join(script_dir, logging_config_path)
logging_directory = os.path.join(script_dir, logging_directory)
setup_logging(path=logging_config_path, default_level=logging_default_level, logging_directory=logging_directory)
flplan = parse_fl_plan(os.path.join(plan_dir, plan))
model_init_kwarg_keys = ['validate_without_patches', 'torch_threads', 'kmp_affinity']
model_init_kwarg_vals = [validate_without_patches_flag, torch_threads, kmp_affinity_flag]
for (key, value) in zip(model_init_kwarg_keys, model_init_kwarg_vals):
if ((value is not None) and (value != False)):
flplan['model_object_init']['init_kwargs'][key] = value
data_init_kwarg_keys = ['in_memory', 'q_max_length', 'q_num_workers']
data_init_kwarg_vals = [data_in_memory_flag, data_queue_max_length, data_queue_num_workers]
for (key, value) in zip(data_init_kwarg_keys, data_init_kwarg_vals):
if ((value is not None) and (value != False)):
flplan['data_object_init']['init_kwargs'][key] = value
local_config = load_yaml(os.path.join(base_dir, data_config_fname))
collaborator_common_names = load_yaml(os.path.join(collaborators_dir, collaborators_file))['collaborator_common_names']
federate(flplan=flplan, resume=resume, local_config=local_config, collaborator_common_names=collaborator_common_names, base_dir=base_dir, weights_dir=weights_dir, metadata_dir=metadata_dir, model_device=model_device) | def main(plan, resume, collaborators_file, data_config_fname, validate_without_patches_flag, data_in_memory_flag, data_queue_max_length, data_queue_num_workers, torch_threads, kmp_affinity_flag, logging_config_path, logging_default_level, logging_directory, model_device, **kwargs):
'Run the federation simulation from the federation (FL) plan.\n\n Runs a federated training from the federation (FL) plan but creates the\n aggregator and collaborators on the same compute node. This allows\n the developer to test the model and data loaders before running\n on the remote collaborator nodes.\n\n Args:\n plan : The Federation (FL) plan (YAML file)\n resume : Whether or not the aggregator is told to resume from previous best\n collaborators_file : The file listing the collaborators\n data_config_fname : The file describing where the dataset is located on the collaborators\n validate_withouut_patches_flag : controls a model init kwarg\n data_in_memory_flag : controls a data init kwarg \n data_queue_max_length : controls a data init kwarg \n data_queue_num_workers : controls a data init kwarg\n torch_threads : number of threads to set in torch \n kmp_affinity_flag : controls a model init kwarg\n logging_config_path : The log file\n logging_default_level : The log level\n **kwargs : Variable parameters to pass to the function\n\n '
script_dir = os.path.dirname(os.path.realpath(__file__))
base_dir = os.path.join(script_dir, 'federations')
plan_dir = os.path.join(base_dir, 'plans')
weights_dir = os.path.join(base_dir, 'weights')
metadata_dir = os.path.join(base_dir, 'metadata')
collaborators_dir = os.path.join(base_dir, 'collaborator_lists')
logging_config_path = os.path.join(script_dir, logging_config_path)
logging_directory = os.path.join(script_dir, logging_directory)
setup_logging(path=logging_config_path, default_level=logging_default_level, logging_directory=logging_directory)
flplan = parse_fl_plan(os.path.join(plan_dir, plan))
model_init_kwarg_keys = ['validate_without_patches', 'torch_threads', 'kmp_affinity']
model_init_kwarg_vals = [validate_without_patches_flag, torch_threads, kmp_affinity_flag]
for (key, value) in zip(model_init_kwarg_keys, model_init_kwarg_vals):
if ((value is not None) and (value != False)):
flplan['model_object_init']['init_kwargs'][key] = value
data_init_kwarg_keys = ['in_memory', 'q_max_length', 'q_num_workers']
data_init_kwarg_vals = [data_in_memory_flag, data_queue_max_length, data_queue_num_workers]
for (key, value) in zip(data_init_kwarg_keys, data_init_kwarg_vals):
if ((value is not None) and (value != False)):
flplan['data_object_init']['init_kwargs'][key] = value
local_config = load_yaml(os.path.join(base_dir, data_config_fname))
collaborator_common_names = load_yaml(os.path.join(collaborators_dir, collaborators_file))['collaborator_common_names']
federate(flplan=flplan, resume=resume, local_config=local_config, collaborator_common_names=collaborator_common_names, base_dir=base_dir, weights_dir=weights_dir, metadata_dir=metadata_dir, model_device=model_device)<|docstring|>Run the federation simulation from the federation (FL) plan.
Runs a federated training from the federation (FL) plan but creates the
aggregator and collaborators on the same compute node. This allows
the developer to test the model and data loaders before running
on the remote collaborator nodes.
Args:
plan : The Federation (FL) plan (YAML file)
resume : Whether or not the aggregator is told to resume from previous best
collaborators_file : The file listing the collaborators
data_config_fname : The file describing where the dataset is located on the collaborators
validate_withouut_patches_flag : controls a model init kwarg
data_in_memory_flag : controls a data init kwarg
data_queue_max_length : controls a data init kwarg
data_queue_num_workers : controls a data init kwarg
torch_threads : number of threads to set in torch
kmp_affinity_flag : controls a model init kwarg
logging_config_path : The log file
logging_default_level : The log level
**kwargs : Variable parameters to pass to the function<|endoftext|> |
44044d53c96ca0d340395bcd25ea024dca6b66670ea7a0abdc9b96bd14eec398 | def Inception(inputs, units=8, strides=1):
'\n naive google inception block\n '
x1 = Conv2D(units, 5, padding='same', activation='relu', strides=strides)(inputs)
x2 = Conv2D(units, 3, padding='same', activation='relu', strides=strides)(inputs)
x3 = Conv2D(units, 1, padding='same', activation='relu', strides=strides)(inputs)
outputs = Concatenate()([x1, x2, x3])
return outputs | naive google inception block | molmap/model/net2.py | Inception | riversdark/bidd-molmap | 75 | python | def Inception(inputs, units=8, strides=1):
'\n \n '
x1 = Conv2D(units, 5, padding='same', activation='relu', strides=strides)(inputs)
x2 = Conv2D(units, 3, padding='same', activation='relu', strides=strides)(inputs)
x3 = Conv2D(units, 1, padding='same', activation='relu', strides=strides)(inputs)
outputs = Concatenate()([x1, x2, x3])
return outputs | def Inception(inputs, units=8, strides=1):
'\n \n '
x1 = Conv2D(units, 5, padding='same', activation='relu', strides=strides)(inputs)
x2 = Conv2D(units, 3, padding='same', activation='relu', strides=strides)(inputs)
x3 = Conv2D(units, 1, padding='same', activation='relu', strides=strides)(inputs)
outputs = Concatenate()([x1, x2, x3])
return outputs<|docstring|>naive google inception block<|endoftext|> |
3fd64ae692016c18e21b2aaf870807a97549f5ff850a43a3f12c6076e3fb66a4 | def MolMapNet(input_shape, n_outputs=1, conv1_kernel_size=13, dense_layers=[128, 32], dense_avf='relu', last_avf=None):
'\n parameters\n ----------------------\n molmap_shape: w, h, c\n n_outputs: output units\n dense_layers: list, how many dense layers and units\n dense_avf: activation function for dense layers\n last_avf: activation function for last layer\n '
tf.keras.backend.clear_session()
assert (len(input_shape) == 3)
inputs = Input(input_shape)
conv1 = Conv2D(48, conv1_kernel_size, padding='same', activation='relu', strides=1)(inputs)
conv1 = MaxPool2D(pool_size=3, strides=2, padding='same')(conv1)
incept1 = Inception(conv1, strides=1, units=32)
incept1 = MaxPool2D(pool_size=3, strides=2, padding='same')(incept1)
incept2 = Inception(incept1, strides=1, units=64)
x = GlobalMaxPool2D()(incept2)
for units in dense_layers:
x = Dense(units, activation=dense_avf)(x)
outputs = Dense(n_outputs, activation=last_avf)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
return model | parameters
----------------------
molmap_shape: w, h, c
n_outputs: output units
dense_layers: list, how many dense layers and units
dense_avf: activation function for dense layers
last_avf: activation function for last layer | molmap/model/net2.py | MolMapNet | riversdark/bidd-molmap | 75 | python | def MolMapNet(input_shape, n_outputs=1, conv1_kernel_size=13, dense_layers=[128, 32], dense_avf='relu', last_avf=None):
'\n parameters\n ----------------------\n molmap_shape: w, h, c\n n_outputs: output units\n dense_layers: list, how many dense layers and units\n dense_avf: activation function for dense layers\n last_avf: activation function for last layer\n '
tf.keras.backend.clear_session()
assert (len(input_shape) == 3)
inputs = Input(input_shape)
conv1 = Conv2D(48, conv1_kernel_size, padding='same', activation='relu', strides=1)(inputs)
conv1 = MaxPool2D(pool_size=3, strides=2, padding='same')(conv1)
incept1 = Inception(conv1, strides=1, units=32)
incept1 = MaxPool2D(pool_size=3, strides=2, padding='same')(incept1)
incept2 = Inception(incept1, strides=1, units=64)
x = GlobalMaxPool2D()(incept2)
for units in dense_layers:
x = Dense(units, activation=dense_avf)(x)
outputs = Dense(n_outputs, activation=last_avf)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
return model | def MolMapNet(input_shape, n_outputs=1, conv1_kernel_size=13, dense_layers=[128, 32], dense_avf='relu', last_avf=None):
'\n parameters\n ----------------------\n molmap_shape: w, h, c\n n_outputs: output units\n dense_layers: list, how many dense layers and units\n dense_avf: activation function for dense layers\n last_avf: activation function for last layer\n '
tf.keras.backend.clear_session()
assert (len(input_shape) == 3)
inputs = Input(input_shape)
conv1 = Conv2D(48, conv1_kernel_size, padding='same', activation='relu', strides=1)(inputs)
conv1 = MaxPool2D(pool_size=3, strides=2, padding='same')(conv1)
incept1 = Inception(conv1, strides=1, units=32)
incept1 = MaxPool2D(pool_size=3, strides=2, padding='same')(incept1)
incept2 = Inception(incept1, strides=1, units=64)
x = GlobalMaxPool2D()(incept2)
for units in dense_layers:
x = Dense(units, activation=dense_avf)(x)
outputs = Dense(n_outputs, activation=last_avf)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
return model<|docstring|>parameters
----------------------
molmap_shape: w, h, c
n_outputs: output units
dense_layers: list, how many dense layers and units
dense_avf: activation function for dense layers
last_avf: activation function for last layer<|endoftext|> |
e416b67eeede3e715a06d9163b96368d9ad945c81a28ad0770d30e33b459f14e | def MolMapDualPathNet(molmap1_size, molmap2_size, n_outputs=1, conv1_kernel_size=13, dense_layers=[256, 128, 32], dense_avf='relu', last_avf=None):
'\n parameters\n ----------------------\n molmap1_size: w, h, c, shape of first molmap\n molmap2_size: w, h, c, shape of second molmap\n n_outputs: output units\n dense_layers: list, how many dense layers and units\n dense_avf: activation function for dense layers\n last_avf: activation function for last layer\n '
tf.keras.backend.clear_session()
d_inputs1 = Input(molmap1_size)
d_conv1 = Conv2D(48, conv1_kernel_size, padding='same', activation='relu', strides=1)(d_inputs1)
d_pool1 = MaxPool2D(pool_size=3, strides=2, padding='same')(d_conv1)
d_incept1 = Inception(d_pool1, strides=1, units=32)
d_pool2 = MaxPool2D(pool_size=3, strides=2, padding='same')(d_incept1)
d_incept2 = Inception(d_pool2, strides=1, units=64)
d_flat1 = GlobalMaxPool2D()(d_incept2)
f_inputs1 = Input(molmap2_size)
f_conv1 = Conv2D(48, conv1_kernel_size, padding='same', activation='relu', strides=1)(f_inputs1)
f_pool1 = MaxPool2D(pool_size=3, strides=2, padding='same')(f_conv1)
f_incept1 = Inception(f_pool1, strides=1, units=32)
f_pool2 = MaxPool2D(pool_size=3, strides=2, padding='same')(f_incept1)
f_incept2 = Inception(f_pool2, strides=1, units=64)
f_flat1 = GlobalMaxPool2D()(f_incept2)
x = Concatenate()([d_flat1, f_flat1])
for units in dense_layers:
x = Dense(units, activation=dense_avf)(x)
outputs = Dense(n_outputs, activation=last_avf)(x)
model = tf.keras.Model(inputs=[d_inputs1, f_inputs1], outputs=outputs)
return model | parameters
----------------------
molmap1_size: w, h, c, shape of first molmap
molmap2_size: w, h, c, shape of second molmap
n_outputs: output units
dense_layers: list, how many dense layers and units
dense_avf: activation function for dense layers
last_avf: activation function for last layer | molmap/model/net2.py | MolMapDualPathNet | riversdark/bidd-molmap | 75 | python | def MolMapDualPathNet(molmap1_size, molmap2_size, n_outputs=1, conv1_kernel_size=13, dense_layers=[256, 128, 32], dense_avf='relu', last_avf=None):
'\n parameters\n ----------------------\n molmap1_size: w, h, c, shape of first molmap\n molmap2_size: w, h, c, shape of second molmap\n n_outputs: output units\n dense_layers: list, how many dense layers and units\n dense_avf: activation function for dense layers\n last_avf: activation function for last layer\n '
tf.keras.backend.clear_session()
d_inputs1 = Input(molmap1_size)
d_conv1 = Conv2D(48, conv1_kernel_size, padding='same', activation='relu', strides=1)(d_inputs1)
d_pool1 = MaxPool2D(pool_size=3, strides=2, padding='same')(d_conv1)
d_incept1 = Inception(d_pool1, strides=1, units=32)
d_pool2 = MaxPool2D(pool_size=3, strides=2, padding='same')(d_incept1)
d_incept2 = Inception(d_pool2, strides=1, units=64)
d_flat1 = GlobalMaxPool2D()(d_incept2)
f_inputs1 = Input(molmap2_size)
f_conv1 = Conv2D(48, conv1_kernel_size, padding='same', activation='relu', strides=1)(f_inputs1)
f_pool1 = MaxPool2D(pool_size=3, strides=2, padding='same')(f_conv1)
f_incept1 = Inception(f_pool1, strides=1, units=32)
f_pool2 = MaxPool2D(pool_size=3, strides=2, padding='same')(f_incept1)
f_incept2 = Inception(f_pool2, strides=1, units=64)
f_flat1 = GlobalMaxPool2D()(f_incept2)
x = Concatenate()([d_flat1, f_flat1])
for units in dense_layers:
x = Dense(units, activation=dense_avf)(x)
outputs = Dense(n_outputs, activation=last_avf)(x)
model = tf.keras.Model(inputs=[d_inputs1, f_inputs1], outputs=outputs)
return model | def MolMapDualPathNet(molmap1_size, molmap2_size, n_outputs=1, conv1_kernel_size=13, dense_layers=[256, 128, 32], dense_avf='relu', last_avf=None):
'\n parameters\n ----------------------\n molmap1_size: w, h, c, shape of first molmap\n molmap2_size: w, h, c, shape of second molmap\n n_outputs: output units\n dense_layers: list, how many dense layers and units\n dense_avf: activation function for dense layers\n last_avf: activation function for last layer\n '
tf.keras.backend.clear_session()
d_inputs1 = Input(molmap1_size)
d_conv1 = Conv2D(48, conv1_kernel_size, padding='same', activation='relu', strides=1)(d_inputs1)
d_pool1 = MaxPool2D(pool_size=3, strides=2, padding='same')(d_conv1)
d_incept1 = Inception(d_pool1, strides=1, units=32)
d_pool2 = MaxPool2D(pool_size=3, strides=2, padding='same')(d_incept1)
d_incept2 = Inception(d_pool2, strides=1, units=64)
d_flat1 = GlobalMaxPool2D()(d_incept2)
f_inputs1 = Input(molmap2_size)
f_conv1 = Conv2D(48, conv1_kernel_size, padding='same', activation='relu', strides=1)(f_inputs1)
f_pool1 = MaxPool2D(pool_size=3, strides=2, padding='same')(f_conv1)
f_incept1 = Inception(f_pool1, strides=1, units=32)
f_pool2 = MaxPool2D(pool_size=3, strides=2, padding='same')(f_incept1)
f_incept2 = Inception(f_pool2, strides=1, units=64)
f_flat1 = GlobalMaxPool2D()(f_incept2)
x = Concatenate()([d_flat1, f_flat1])
for units in dense_layers:
x = Dense(units, activation=dense_avf)(x)
outputs = Dense(n_outputs, activation=last_avf)(x)
model = tf.keras.Model(inputs=[d_inputs1, f_inputs1], outputs=outputs)
return model<|docstring|>parameters
----------------------
molmap1_size: w, h, c, shape of first molmap
molmap2_size: w, h, c, shape of second molmap
n_outputs: output units
dense_layers: list, how many dense layers and units
dense_avf: activation function for dense layers
last_avf: activation function for last layer<|endoftext|> |
61f14305612141537287f5a3734c929fcf6ba331b850d1b61e9e2178ed13f8aa | def MolMapAddPathNet(molmap_shape, additional_shape, n_outputs=1, dense_layers=[128, 32], dense_avf='relu', last_avf=None):
'\n parameters\n ----------------------\n molmap_shape: w, h, c\n n_outputs: output units\n dense_layers: list, how many dense layers and units\n dense_avf: activation function for dense layers\n last_avf: activation function for last layer\n '
tf.keras.backend.clear_session()
assert (len(molmap_shape) == 3)
inputs = Input(molmap_shape)
inputs_actvie_amount = Input(additional_shape)
conv1 = Conv2D(48, 13, padding='same', activation='relu', strides=1)(inputs)
conv1 = MaxPool2D(pool_size=3, strides=2, padding='same')(conv1)
incept1 = Inception(conv1, strides=1, units=32)
incept1 = MaxPool2D(pool_size=3, strides=2, padding='same')(incept1)
incept2 = Inception(incept1, strides=1, units=64)
x = GlobalMaxPool2D()(incept2)
x = tf.keras.layers.concatenate([x, inputs_actvie_amount], axis=(- 1))
for units in dense_layers:
x = Dense(units, activation=dense_avf)(x)
outputs = Dense(n_outputs, activation=last_avf)(x)
model = tf.keras.Model(inputs=[inputs, inputs_actvie_amount], outputs=outputs)
return model | parameters
----------------------
molmap_shape: w, h, c
n_outputs: output units
dense_layers: list, how many dense layers and units
dense_avf: activation function for dense layers
last_avf: activation function for last layer | molmap/model/net2.py | MolMapAddPathNet | riversdark/bidd-molmap | 75 | python | def MolMapAddPathNet(molmap_shape, additional_shape, n_outputs=1, dense_layers=[128, 32], dense_avf='relu', last_avf=None):
'\n parameters\n ----------------------\n molmap_shape: w, h, c\n n_outputs: output units\n dense_layers: list, how many dense layers and units\n dense_avf: activation function for dense layers\n last_avf: activation function for last layer\n '
tf.keras.backend.clear_session()
assert (len(molmap_shape) == 3)
inputs = Input(molmap_shape)
inputs_actvie_amount = Input(additional_shape)
conv1 = Conv2D(48, 13, padding='same', activation='relu', strides=1)(inputs)
conv1 = MaxPool2D(pool_size=3, strides=2, padding='same')(conv1)
incept1 = Inception(conv1, strides=1, units=32)
incept1 = MaxPool2D(pool_size=3, strides=2, padding='same')(incept1)
incept2 = Inception(incept1, strides=1, units=64)
x = GlobalMaxPool2D()(incept2)
x = tf.keras.layers.concatenate([x, inputs_actvie_amount], axis=(- 1))
for units in dense_layers:
x = Dense(units, activation=dense_avf)(x)
outputs = Dense(n_outputs, activation=last_avf)(x)
model = tf.keras.Model(inputs=[inputs, inputs_actvie_amount], outputs=outputs)
return model | def MolMapAddPathNet(molmap_shape, additional_shape, n_outputs=1, dense_layers=[128, 32], dense_avf='relu', last_avf=None):
'\n parameters\n ----------------------\n molmap_shape: w, h, c\n n_outputs: output units\n dense_layers: list, how many dense layers and units\n dense_avf: activation function for dense layers\n last_avf: activation function for last layer\n '
tf.keras.backend.clear_session()
assert (len(molmap_shape) == 3)
inputs = Input(molmap_shape)
inputs_actvie_amount = Input(additional_shape)
conv1 = Conv2D(48, 13, padding='same', activation='relu', strides=1)(inputs)
conv1 = MaxPool2D(pool_size=3, strides=2, padding='same')(conv1)
incept1 = Inception(conv1, strides=1, units=32)
incept1 = MaxPool2D(pool_size=3, strides=2, padding='same')(incept1)
incept2 = Inception(incept1, strides=1, units=64)
x = GlobalMaxPool2D()(incept2)
x = tf.keras.layers.concatenate([x, inputs_actvie_amount], axis=(- 1))
for units in dense_layers:
x = Dense(units, activation=dense_avf)(x)
outputs = Dense(n_outputs, activation=last_avf)(x)
model = tf.keras.Model(inputs=[inputs, inputs_actvie_amount], outputs=outputs)
return model<|docstring|>parameters
----------------------
molmap_shape: w, h, c
n_outputs: output units
dense_layers: list, how many dense layers and units
dense_avf: activation function for dense layers
last_avf: activation function for last layer<|endoftext|> |
f88f7db4772b63f1fa88b4163eafddc0f08a94c90a80ecb5b57869093ee5c74d | def MolMapResNet(input_shape, num_resnet_blocks=8, n_outputs=1, dense_layers=[128, 32], dense_avf='relu', last_avf=None):
'\n parameters\n ----------------------\n molmap_shape: w, h, c\n num_resnet_blocks: int\n n_outputs: output units\n dense_layers: list, how many dense layers and units\n dense_avf: activation function for dense layers\n last_avf: activation function for last layer\n '
tf.keras.backend.clear_session()
inputs = tf.keras.Input(input_shape)
x = Conv2D(64, 13, padding='same', activation='relu', strides=1)(inputs)
x = MaxPool2D(pool_size=3, strides=2, padding='same')(x)
for i in range(num_resnet_blocks):
x = resnet_block(x, 64, 3)
x = layers.Conv2D(256, 3, activation='relu')(x)
x = layers.GlobalMaxPool2D()(x)
for units in dense_layers:
x = layers.Dense(units, activation=dense_avf)(x)
outputs = Dense(n_outputs, activation=last_avf)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
return model | parameters
----------------------
molmap_shape: w, h, c
num_resnet_blocks: int
n_outputs: output units
dense_layers: list, how many dense layers and units
dense_avf: activation function for dense layers
last_avf: activation function for last layer | molmap/model/net2.py | MolMapResNet | riversdark/bidd-molmap | 75 | python | def MolMapResNet(input_shape, num_resnet_blocks=8, n_outputs=1, dense_layers=[128, 32], dense_avf='relu', last_avf=None):
'\n parameters\n ----------------------\n molmap_shape: w, h, c\n num_resnet_blocks: int\n n_outputs: output units\n dense_layers: list, how many dense layers and units\n dense_avf: activation function for dense layers\n last_avf: activation function for last layer\n '
tf.keras.backend.clear_session()
inputs = tf.keras.Input(input_shape)
x = Conv2D(64, 13, padding='same', activation='relu', strides=1)(inputs)
x = MaxPool2D(pool_size=3, strides=2, padding='same')(x)
for i in range(num_resnet_blocks):
x = resnet_block(x, 64, 3)
x = layers.Conv2D(256, 3, activation='relu')(x)
x = layers.GlobalMaxPool2D()(x)
for units in dense_layers:
x = layers.Dense(units, activation=dense_avf)(x)
outputs = Dense(n_outputs, activation=last_avf)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
return model | def MolMapResNet(input_shape, num_resnet_blocks=8, n_outputs=1, dense_layers=[128, 32], dense_avf='relu', last_avf=None):
'\n parameters\n ----------------------\n molmap_shape: w, h, c\n num_resnet_blocks: int\n n_outputs: output units\n dense_layers: list, how many dense layers and units\n dense_avf: activation function for dense layers\n last_avf: activation function for last layer\n '
tf.keras.backend.clear_session()
inputs = tf.keras.Input(input_shape)
x = Conv2D(64, 13, padding='same', activation='relu', strides=1)(inputs)
x = MaxPool2D(pool_size=3, strides=2, padding='same')(x)
for i in range(num_resnet_blocks):
x = resnet_block(x, 64, 3)
x = layers.Conv2D(256, 3, activation='relu')(x)
x = layers.GlobalMaxPool2D()(x)
for units in dense_layers:
x = layers.Dense(units, activation=dense_avf)(x)
outputs = Dense(n_outputs, activation=last_avf)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
return model<|docstring|>parameters
----------------------
molmap_shape: w, h, c
num_resnet_blocks: int
n_outputs: output units
dense_layers: list, how many dense layers and units
dense_avf: activation function for dense layers
last_avf: activation function for last layer<|endoftext|> |
fa951dbef7adc0e2f034c0c6c5c561543c3c5231999fe725f548c44d67b6b4ac | def any_old(resource_type, extra_fields=None):
'\n Create any old resource... a generic and unique object of a given type\n @param resource_type the resource type\n @param extra_fields dict of any extra fields to set\n '
if (not extra_fields):
extra_fields = {}
if (resource_type not in _sa_test_helpers_ionobj_count):
_sa_test_helpers_ionobj_count[resource_type] = 0
_sa_test_helpers_ionobj_count[resource_type] = (_sa_test_helpers_ionobj_count[resource_type] + 1)
name = ('%s_%d' % (resource_type, _sa_test_helpers_ionobj_count[resource_type]))
desc = ('My %s #%d' % (resource_type, _sa_test_helpers_ionobj_count[resource_type]))
log.debug('Creating any old %s IonObject (#%d)', resource_type, _sa_test_helpers_ionobj_count[resource_type])
ret = IonObject(resource_type, name=name, description=desc)
for (k, v) in extra_fields.iteritems():
setattr(ret, k, v)
return ret | Create any old resource... a generic and unique object of a given type
@param resource_type the resource type
@param extra_fields dict of any extra fields to set | ion/services/sa/test/helpers.py | any_old | ooici/coi-services | 3 | python | def any_old(resource_type, extra_fields=None):
'\n Create any old resource... a generic and unique object of a given type\n @param resource_type the resource type\n @param extra_fields dict of any extra fields to set\n '
if (not extra_fields):
extra_fields = {}
if (resource_type not in _sa_test_helpers_ionobj_count):
_sa_test_helpers_ionobj_count[resource_type] = 0
_sa_test_helpers_ionobj_count[resource_type] = (_sa_test_helpers_ionobj_count[resource_type] + 1)
name = ('%s_%d' % (resource_type, _sa_test_helpers_ionobj_count[resource_type]))
desc = ('My %s #%d' % (resource_type, _sa_test_helpers_ionobj_count[resource_type]))
log.debug('Creating any old %s IonObject (#%d)', resource_type, _sa_test_helpers_ionobj_count[resource_type])
ret = IonObject(resource_type, name=name, description=desc)
for (k, v) in extra_fields.iteritems():
setattr(ret, k, v)
return ret | def any_old(resource_type, extra_fields=None):
'\n Create any old resource... a generic and unique object of a given type\n @param resource_type the resource type\n @param extra_fields dict of any extra fields to set\n '
if (not extra_fields):
extra_fields = {}
if (resource_type not in _sa_test_helpers_ionobj_count):
_sa_test_helpers_ionobj_count[resource_type] = 0
_sa_test_helpers_ionobj_count[resource_type] = (_sa_test_helpers_ionobj_count[resource_type] + 1)
name = ('%s_%d' % (resource_type, _sa_test_helpers_ionobj_count[resource_type]))
desc = ('My %s #%d' % (resource_type, _sa_test_helpers_ionobj_count[resource_type]))
log.debug('Creating any old %s IonObject (#%d)', resource_type, _sa_test_helpers_ionobj_count[resource_type])
ret = IonObject(resource_type, name=name, description=desc)
for (k, v) in extra_fields.iteritems():
setattr(ret, k, v)
return ret<|docstring|>Create any old resource... a generic and unique object of a given type
@param resource_type the resource type
@param extra_fields dict of any extra fields to set<|endoftext|> |
f5dc0bc7c1a6ea0b5568f3211602ac56729847ebd468581602c653409a64734c | def add_keyworded_attachment(resource_registry_client, resource_id, keywords, extra_fields=None):
'\n create a generic attachment to a given resource -- a generic and unique attachment\n\n @param resource_registry_client a service client\n @param resource_id string the resource to get the attachment\n @param keywords list of string keywords\n @param extra_fields dict of extra fields to set. "keywords" can be set here with no ill effects\n '
if (not extra_fields):
extra_fields = {}
if (not ('attachment_type' in extra_fields)):
extra_fields['attachment_type'] = AttachmentType.ASCII
if (not ('content' in extra_fields)):
extra_fields['content'] = 'these are contents'
if (not ('keywords' in extra_fields)):
extra_fields['keywords'] = []
for k in keywords:
extra_fields['keywords'].append(k)
ret = any_old(RT.Attachment, extra_fields)
resource_registry_client.create_attachment(resource_id, ret)
return ret | create a generic attachment to a given resource -- a generic and unique attachment
@param resource_registry_client a service client
@param resource_id string the resource to get the attachment
@param keywords list of string keywords
@param extra_fields dict of extra fields to set. "keywords" can be set here with no ill effects | ion/services/sa/test/helpers.py | add_keyworded_attachment | ooici/coi-services | 3 | python | def add_keyworded_attachment(resource_registry_client, resource_id, keywords, extra_fields=None):
'\n create a generic attachment to a given resource -- a generic and unique attachment\n\n @param resource_registry_client a service client\n @param resource_id string the resource to get the attachment\n @param keywords list of string keywords\n @param extra_fields dict of extra fields to set. "keywords" can be set here with no ill effects\n '
if (not extra_fields):
extra_fields = {}
if (not ('attachment_type' in extra_fields)):
extra_fields['attachment_type'] = AttachmentType.ASCII
if (not ('content' in extra_fields)):
extra_fields['content'] = 'these are contents'
if (not ('keywords' in extra_fields)):
extra_fields['keywords'] = []
for k in keywords:
extra_fields['keywords'].append(k)
ret = any_old(RT.Attachment, extra_fields)
resource_registry_client.create_attachment(resource_id, ret)
return ret | def add_keyworded_attachment(resource_registry_client, resource_id, keywords, extra_fields=None):
'\n create a generic attachment to a given resource -- a generic and unique attachment\n\n @param resource_registry_client a service client\n @param resource_id string the resource to get the attachment\n @param keywords list of string keywords\n @param extra_fields dict of extra fields to set. "keywords" can be set here with no ill effects\n '
if (not extra_fields):
extra_fields = {}
if (not ('attachment_type' in extra_fields)):
extra_fields['attachment_type'] = AttachmentType.ASCII
if (not ('content' in extra_fields)):
extra_fields['content'] = 'these are contents'
if (not ('keywords' in extra_fields)):
extra_fields['keywords'] = []
for k in keywords:
extra_fields['keywords'].append(k)
ret = any_old(RT.Attachment, extra_fields)
resource_registry_client.create_attachment(resource_id, ret)
return ret<|docstring|>create a generic attachment to a given resource -- a generic and unique attachment
@param resource_registry_client a service client
@param resource_id string the resource to get the attachment
@param keywords list of string keywords
@param extra_fields dict of extra fields to set. "keywords" can be set here with no ill effects<|endoftext|> |
28d1b8749b82c37e97d1c3887da6d57ba19e73ce9d8806a6260405e076a5d2f7 | def __init__(self, unit_test_class, service_under_test_class):
"\n @param unit_test_class the class that will perform the setup/ testing, to which methods will be added\n @param service_under_test_class the class of the service that's being tested\n "
self.tester_class = unit_test_class
self.service_instance = service_under_test_class()
self.service_instance.on_init()
self.all_in_one = False | @param unit_test_class the class that will perform the setup/ testing, to which methods will be added
@param service_under_test_class the class of the service that's being tested | ion/services/sa/test/helpers.py | __init__ | ooici/coi-services | 3 | python | def __init__(self, unit_test_class, service_under_test_class):
"\n @param unit_test_class the class that will perform the setup/ testing, to which methods will be added\n @param service_under_test_class the class of the service that's being tested\n "
self.tester_class = unit_test_class
self.service_instance = service_under_test_class()
self.service_instance.on_init()
self.all_in_one = False | def __init__(self, unit_test_class, service_under_test_class):
"\n @param unit_test_class the class that will perform the setup/ testing, to which methods will be added\n @param service_under_test_class the class of the service that's being tested\n "
self.tester_class = unit_test_class
self.service_instance = service_under_test_class()
self.service_instance.on_init()
self.all_in_one = False<|docstring|>@param unit_test_class the class that will perform the setup/ testing, to which methods will be added
@param service_under_test_class the class of the service that's being tested<|endoftext|> |
a35be37ae8653963686ac7780d6eda0b7137365c5360f30570ffbf43e0008eee | def test_all_in_one(self, yes):
'\n @param yes whether to run int tests all in one\n '
self.all_in_one = yes | @param yes whether to run int tests all in one | ion/services/sa/test/helpers.py | test_all_in_one | ooici/coi-services | 3 | python | def test_all_in_one(self, yes):
'\n \n '
self.all_in_one = yes | def test_all_in_one(self, yes):
'\n \n '
self.all_in_one = yes<|docstring|>@param yes whether to run int tests all in one<|endoftext|> |
f78c67aba5489e9b0ee104486dc7661b6eae0e1c4565811008981d2e58bd3e87 | def build_test_descriptors(self, resource_params):
'\n build a sample resource from the supplied impl class\n and populate it with the supplied parameters\n\n @param resource_params a dict of params for the sample resource\n '
sample_resource_extras = ''
sample_resource_md5 = ''
if resource_params:
extras = []
for (k, v) in resource_params.iteritems():
extras.append(("%s='%s'" % (k, v)))
sample_resource_extras = ('(with %s)' % ', '.join(extras))
sample_resource_md5 = ('_%s' % str(hashlib.sha224(sample_resource_extras).hexdigest()[:7]))
self.sample_resource_extras = sample_resource_extras
self.sample_resource_md5 = sample_resource_md5 | build a sample resource from the supplied impl class
and populate it with the supplied parameters
@param resource_params a dict of params for the sample resource | ion/services/sa/test/helpers.py | build_test_descriptors | ooici/coi-services | 3 | python | def build_test_descriptors(self, resource_params):
'\n build a sample resource from the supplied impl class\n and populate it with the supplied parameters\n\n @param resource_params a dict of params for the sample resource\n '
sample_resource_extras =
sample_resource_md5 =
if resource_params:
extras = []
for (k, v) in resource_params.iteritems():
extras.append(("%s='%s'" % (k, v)))
sample_resource_extras = ('(with %s)' % ', '.join(extras))
sample_resource_md5 = ('_%s' % str(hashlib.sha224(sample_resource_extras).hexdigest()[:7]))
self.sample_resource_extras = sample_resource_extras
self.sample_resource_md5 = sample_resource_md5 | def build_test_descriptors(self, resource_params):
'\n build a sample resource from the supplied impl class\n and populate it with the supplied parameters\n\n @param resource_params a dict of params for the sample resource\n '
sample_resource_extras =
sample_resource_md5 =
if resource_params:
extras = []
for (k, v) in resource_params.iteritems():
extras.append(("%s='%s'" % (k, v)))
sample_resource_extras = ('(with %s)' % ', '.join(extras))
sample_resource_md5 = ('_%s' % str(hashlib.sha224(sample_resource_extras).hexdigest()[:7]))
self.sample_resource_extras = sample_resource_extras
self.sample_resource_md5 = sample_resource_md5<|docstring|>build a sample resource from the supplied impl class
and populate it with the supplied parameters
@param resource_params a dict of params for the sample resource<|endoftext|> |
e565b6f75b63338f3961382bf211531fc1b821dd0c9ef55aa2e128ca7ed76047 | def sample_resource_factory(self, iontype, resource_params):
"\n build a sample resource factory from the supplied impl class\n that produces resources populated with the supplied parameters\n\n this will give us the ability to use the service that we're testing\n to generate the resource for us.\n\n @param iontype the ion type to create\n @resource_params a dict of params to add\n "
def fun():
log.debug('Creating sample %s', iontype)
ret = IonObject(iontype)
ret.name = ('sample %s' % iontype)
ret.description = ('description of sample %s' % iontype)
for (k, v) in resource_params.iteritems():
setattr(ret, k, v)
return ret
return fun | build a sample resource factory from the supplied impl class
that produces resources populated with the supplied parameters
this will give us the ability to use the service that we're testing
to generate the resource for us.
@param iontype the ion type to create
@resource_params a dict of params to add | ion/services/sa/test/helpers.py | sample_resource_factory | ooici/coi-services | 3 | python | def sample_resource_factory(self, iontype, resource_params):
"\n build a sample resource factory from the supplied impl class\n that produces resources populated with the supplied parameters\n\n this will give us the ability to use the service that we're testing\n to generate the resource for us.\n\n @param iontype the ion type to create\n @resource_params a dict of params to add\n "
def fun():
log.debug('Creating sample %s', iontype)
ret = IonObject(iontype)
ret.name = ('sample %s' % iontype)
ret.description = ('description of sample %s' % iontype)
for (k, v) in resource_params.iteritems():
setattr(ret, k, v)
return ret
return fun | def sample_resource_factory(self, iontype, resource_params):
"\n build a sample resource factory from the supplied impl class\n that produces resources populated with the supplied parameters\n\n this will give us the ability to use the service that we're testing\n to generate the resource for us.\n\n @param iontype the ion type to create\n @resource_params a dict of params to add\n "
def fun():
log.debug('Creating sample %s', iontype)
ret = IonObject(iontype)
ret.name = ('sample %s' % iontype)
ret.description = ('description of sample %s' % iontype)
for (k, v) in resource_params.iteritems():
setattr(ret, k, v)
return ret
return fun<|docstring|>build a sample resource factory from the supplied impl class
that produces resources populated with the supplied parameters
this will give us the ability to use the service that we're testing
to generate the resource for us.
@param iontype the ion type to create
@resource_params a dict of params to add<|endoftext|> |
bcb0b7c485691a86bd2c62344b2774463779e63b7bc4955c0349909f6d168449 | def find_class_variable_name(self, instance, target_type):
"\n determine which class variable in the instance is of the target type\n @param instance the class to be searched\n @param target_type the type of the variable we want to find\n @retval string the name of the class variable\n\n we use this to get the reference to a variable in another class but\n WITHOUT knowing what it's called.\n "
ret = None
for (k, v) in instance.__dict__.iteritems():
if (type(v) == target_type):
ret = k
return ret | determine which class variable in the instance is of the target type
@param instance the class to be searched
@param target_type the type of the variable we want to find
@retval string the name of the class variable
we use this to get the reference to a variable in another class but
WITHOUT knowing what it's called. | ion/services/sa/test/helpers.py | find_class_variable_name | ooici/coi-services | 3 | python | def find_class_variable_name(self, instance, target_type):
"\n determine which class variable in the instance is of the target type\n @param instance the class to be searched\n @param target_type the type of the variable we want to find\n @retval string the name of the class variable\n\n we use this to get the reference to a variable in another class but\n WITHOUT knowing what it's called.\n "
ret = None
for (k, v) in instance.__dict__.iteritems():
if (type(v) == target_type):
ret = k
return ret | def find_class_variable_name(self, instance, target_type):
"\n determine which class variable in the instance is of the target type\n @param instance the class to be searched\n @param target_type the type of the variable we want to find\n @retval string the name of the class variable\n\n we use this to get the reference to a variable in another class but\n WITHOUT knowing what it's called.\n "
ret = None
for (k, v) in instance.__dict__.iteritems():
if (type(v) == target_type):
ret = k
return ret<|docstring|>determine which class variable in the instance is of the target type
@param instance the class to be searched
@param target_type the type of the variable we want to find
@retval string the name of the class variable
we use this to get the reference to a variable in another class but
WITHOUT knowing what it's called.<|endoftext|> |
dd64efc19183b865aa95bcc10d1dacdc72587a90255a7a83de6f75c2c85f5061 | def add_resource_unittests(self, resource_iontype, resource_label, resource_params=None):
'\n Add tests for the resorce_impl_class to the (self.)resource_tester_class\n\n @param resource_iontype the IonObject type to test with (e.g. RT.PlatformModel)\n @param resource_label the base of the function names for this resource (e.g. platform_model)\n @param resource_params dictionary of extra params to add to the sample resource\n\n this function will be huge. it is a list of smaller functions that are templates\n for tests of various resource_impl class functionality. the functions are given\n proper references to member variables in the service and test class, then injected\n into the test class itself.\n\n '
if (None == resource_params):
resource_params = {}
self.build_test_descriptors(resource_params)
sample_resource = self.sample_resource_factory(resource_iontype, resource_params)
all_in_one = self.all_in_one
find_cv_func = self.find_class_variable_name
service_type = type(self.service_instance)
added_methods = {}
def add_new_method(name, docstring, newmethod):
'\n dynamically add a new method to the tester class\n @param name the name of the new method\n @param docstring a description of the test\n @newmethod the function itself\n '
newmethod.__name__ = name
newmethod.__doc__ = docstring
setattr(self.tester_class, newmethod.__name__, newmethod)
added_methods[name] = True
def add_test_method(name, docstring, newmethod):
'\n dynamically add a test method to the tester class\n @param name the name of the test function (minus the "test_" part)\n @param docstring a description of the test\n @newmethod the function itself\n '
add_new_method(('test_%s' % name), docstring, newmethod)
def make_name(name):
'\n make a good name for a test from the resource name and an md5 of extra params\n @param name the base string for the name\n '
assert self.sample_resource_md5
return ('%s%s' % (name, self.sample_resource_md5))
def make_doc(doc):
'\n make a good doc string for a test from by including the extra params\n @param doc the base string for the descripton\n '
return ('%s %s' % (doc, self.sample_resource_extras))
def gen_svc_cleanup():
def fun(instance):
for (k, _) in added_methods.iteritems():
if hasattr(instance, k):
instance.addCleanup(delattr, instance, k)
add_new_method(('_utg_cleanup_%s%s' % (resource_iontype, self.sample_resource_md5)), 'Cleanup', fun)
def whole_cleanup(instance):
for k in dir(instance):
if ((- 1) < k.find('_utg_cleanup_')):
cleanup_fn = getattr(instance, k)
cleanup_fn()
add_new_method('_utg_whole_cleanup', 'Global cleanup', whole_cleanup)
def gen_svc_lookup():
'\n put a new method in the tester class to find the instance of the service being tested\n\n the prefix is "_utg_": unit_test_generator\n '
def getsvc_fun(self):
'\n self is an instance of the tester class\n '
if (not hasattr(self, '_utg_service_obj')):
service_itself = getattr(self, find_cv_func(self, service_type))
self._utg_service_obj = service_itself
assert self._utg_service_obj
return self._utg_service_obj
def getcrudmethod_fun(self, rsrc_lbl, method_str):
'\n self is an instance of the tester class\n method_str is a crud method name like "create" that will become "create_resource_label"\n '
svc = self._utg_getservice()
methodname = ('%s_%s' % (method_str, rsrc_lbl))
if (not hasattr(svc, methodname)):
raise SkipTest('CRUD method does not exist, skipping')
return getattr(svc, methodname)
if (not hasattr(self.tester_class, '_utg_getservice')):
add_new_method('_utg_getservice', 'Finds instance of service under test', getsvc_fun)
if (not hasattr(self.tester_class, '_utg_getcrudmethod')):
add_new_method('_utg_getcrudmethod', 'Finds instance of crud method in service', getcrudmethod_fun)
def test_create_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_create_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
good_sample_resource = sample_resource()
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
sample_resource_id = testfun(good_sample_resource)
svc.clients.resource_registry.create.assert_called_once_with(good_sample_resource)
self.assertEqual(sample_resource_id, '111')
def test_create_bad_wrongtype_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_create_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = IonObject(RT.Resource, name='Generic Resource')
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
self.assertRaisesRegexp(BadRequest, 'type', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count)
def test_create_bad_noname_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_create_bad_noname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = sample_resource()
delattr(bad_sample_resource, 'name')
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
self.assertRaisesRegexp(BadRequest, 'name', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count)
def test_create_bad_dupname_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_create_bad_dupname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = sample_resource()
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([0], [0])
self.assertRaisesRegexp(BadRequest, 'uplicate', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count)
def test_read_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_read_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'read')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
response = testfun('111')
svc.clients.resource_registry.read.assert_called_once_with('111', '')
self.assertEqual(response, myret)
if all_in_one:
svc.clients.resource_registry.reset_mock()
def test_read_bad_wrongtype_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_read_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'read')
myret = IonObject(RT.Resource, name='Generic Resource')
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
self.assertEqual(0, svc.clients.resource_registry.read.call_count)
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
svc.clients.resource_registry.read.assert_called_once_with('111', '')
def test_update_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_update_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
good_sample_resource = sample_resource()
setattr(good_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
svc.clients.resource_registry.update.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
testfun(good_sample_resource)
svc.clients.resource_registry.update.assert_called_once_with(good_sample_resource)
def test_update_bad_dupname_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_update_bad_dupname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
bad_sample_resource = sample_resource()
setattr(bad_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
svc.clients.resource_registry.find_resources.return_value = ([0], [0])
self.assertRaisesRegexp(BadRequest, 'uplicate', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.update.call_count)
def test_update_bad_wrongtype_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_update_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
bad_sample_resource = IonObject(RT.Resource, name='Generic Name')
setattr(bad_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
self.assertRaisesRegexp(BadRequest, 'type', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.update.call_count)
def test_delete_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_delete_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'delete')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
svc.clients.resource_registry.read.return_value = myret
svc.clients.resource_registry.delete.return_value = None
svc.clients.resource_registry.lcs_delete.return_value = None
try:
testfun('111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
svc.clients.resource_registry.reset_mock()
return
else:
raise SkipTest('Must test this with INT test')
svc.clients.resource_registry.lcs_delete.assert_called_once_with('111')
self.assertEqual(0, svc.clients.resource_registry.delete.call_count)
def test_delete_bad_wrongtype_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_delete_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'delete')
myret = IonObject(RT.Resource, name='Generic Name')
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
try:
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
self.assertEqual(0, svc.clients.resource_registry.lcs_delete.call_count)
self.assertEqual(0, svc.clients.resource_registry.delete.call_count)
def test_force_delete_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_force_delete_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'force_delete')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
svc.clients.resource_registry.read.return_value = myret
svc.clients.resource_registry.delete.return_value = None
svc.clients.resource_registry.find_resources.return_value = None
svc.clients.resource_registry.find_objects.return_value = ([], [])
svc.clients.resource_registry.find_subjects.return_value = ([], [])
try:
testfun('111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
svc.clients.resource_registry.delete.assert_called_once_with('111')
def test_force_delete_bad_wrongtype_fun(self):
'\n self is an inst ance of the tester class\n '
log.debug('test_force_delete_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'force_delete')
myret = IonObject(RT.Resource, name='Generic Name')
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.find_objects.return_value = ([], [])
svc.clients.resource_registry.find_subjects.return_value = ([], [])
svc.clients.resource_registry.read.return_value = myret
try:
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
self.assertEqual(0, svc.clients.resource_registry.lcs_delete.call_count)
self.assertEqual(0, svc.clients.resource_registry.delete.call_count)
def gen_test_create():
'\n generate the function to test the create\n '
name = make_name(('%s_create' % resource_label))
doc = make_doc(('Creation of a new %s resource' % resource_iontype))
add_test_method(name, doc, test_create_fun)
def gen_test_create_bad_wrongtype():
'\n generate the function to test the create for the wrong resource type\n '
name = make_name(('%s_create_bad_wrongtype' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (wrong type)' % resource_iontype))
add_test_method(name, doc, test_create_bad_wrongtype_fun)
def gen_test_create_bad_noname():
'\n generate the function to test the create in a bad case\n '
name = make_name(('%s_create_bad_noname' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (no name)' % resource_iontype))
add_test_method(name, doc, test_create_bad_noname_fun)
def gen_test_create_bad_dupname():
'\n generate the function to test the create in a bad case where the name already exists\n '
name = make_name(('%s_create_bad_dupname' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (duplicate name)' % resource_iontype))
add_test_method(name, doc, test_create_bad_dupname_fun)
def gen_test_read():
'\n generate the function to test the read\n '
name = make_name(('%s_read' % resource_label))
doc = make_doc(('Reading a %s resource' % resource_iontype))
add_test_method(name, doc, test_read_fun)
def gen_test_read_bad_wrongtype():
'\n generate the function to test the read with bad type\n '
name = make_name(('%s_read_bad_wrongtype' % resource_label))
doc = make_doc(('Reading a %s resource but having it come back as wrong type' % resource_iontype))
add_test_method(name, doc, test_read_bad_wrongtype_fun)
def gen_test_update():
'\n generate the function to test the update\n '
name = make_name(('%s_update' % resource_label))
doc = make_doc(('Updating a %s resource' % resource_iontype))
add_test_method(name, doc, test_update_fun)
def gen_test_update_bad_wrongtype():
'\n generate the function to test the update with wrong type\n '
name = make_name(('%s_update_bad_wrongtype' % resource_label))
doc = make_doc(('Updating a %s resource with the wrong type' % resource_iontype))
add_test_method(name, doc, test_update_bad_wrongtype_fun)
def gen_test_update_bad_dupname():
'\n generate the function to test the update with wrong type\n '
name = make_name(('%s_update_bad_duplicate' % resource_label))
doc = make_doc(('Updating a %s resource to a duplicate name' % resource_iontype))
add_test_method(name, doc, test_update_bad_dupname_fun)
def gen_test_delete():
'\n generate the function to test the delete\n '
name = make_name(('%s_delete' % resource_label))
doc = make_doc(('Deleting (retiring) a %s resource' % resource_iontype))
add_test_method(name, doc, test_delete_fun)
def gen_test_delete_bad_wrongtype():
'\n generate the function to test the delete with wrong type\n '
name = make_name(('%s_delete_bad_wrongtype' % resource_label))
doc = make_doc(('Deleting (retiring) a %s resource of the wrong type' % resource_iontype))
add_test_method(name, doc, test_delete_bad_wrongtype_fun)
def gen_test_force_delete():
'\n generate the function to test the delete\n '
name = make_name(('%s_force_delete' % resource_label))
doc = make_doc(('Deleting -- destructively -- a %s resource' % resource_iontype))
add_test_method(name, doc, test_force_delete_fun)
def gen_test_force_delete_bad_wrongtype():
'\n generate the function to test the delete with the wrong type\n '
name = make_name(('%s_force_delete_bad_wrongtype' % resource_label))
doc = make_doc(('Deleting -- destructively -- a %s resource of the wrong type' % resource_iontype))
add_test_method(name, doc, test_force_delete_bad_wrongtype_fun)
def gen_test_allinone():
'\n generate the function to test EVERYTHING at once\n '
def fun(self):
'\n self is an instance of the tester class\n '
test_create_fun(self)
test_create_bad_wrongtype_fun(self)
test_create_bad_noname_fun(self)
test_read_fun(self)
test_read_bad_wrongtype_fun(self)
test_update_fun(self)
test_update_bad_wrongtype_fun(self)
test_delete_fun(self)
test_delete_bad_wrongtype_fun(self)
test_force_delete_fun(self)
test_force_delete_bad_wrongtype_fun(self)
name = make_name(('%s_allinone' % resource_label))
doc = make_doc(('Performing all CRUD tests on %s resources' % resource_iontype))
add_test_method(name, doc, fun)
gen_svc_lookup()
if all_in_one:
gen_test_allinone()
else:
gen_test_create()
gen_test_create_bad_wrongtype()
gen_test_create_bad_noname()
gen_test_read()
gen_test_read_bad_wrongtype()
gen_test_update()
gen_test_update_bad_wrongtype()
gen_test_delete()
gen_test_delete_bad_wrongtype()
gen_test_force_delete()
gen_test_force_delete_bad_wrongtype() | Add tests for the resorce_impl_class to the (self.)resource_tester_class
@param resource_iontype the IonObject type to test with (e.g. RT.PlatformModel)
@param resource_label the base of the function names for this resource (e.g. platform_model)
@param resource_params dictionary of extra params to add to the sample resource
this function will be huge. it is a list of smaller functions that are templates
for tests of various resource_impl class functionality. the functions are given
proper references to member variables in the service and test class, then injected
into the test class itself. | ion/services/sa/test/helpers.py | add_resource_unittests | ooici/coi-services | 3 | python | def add_resource_unittests(self, resource_iontype, resource_label, resource_params=None):
'\n Add tests for the resorce_impl_class to the (self.)resource_tester_class\n\n @param resource_iontype the IonObject type to test with (e.g. RT.PlatformModel)\n @param resource_label the base of the function names for this resource (e.g. platform_model)\n @param resource_params dictionary of extra params to add to the sample resource\n\n this function will be huge. it is a list of smaller functions that are templates\n for tests of various resource_impl class functionality. the functions are given\n proper references to member variables in the service and test class, then injected\n into the test class itself.\n\n '
if (None == resource_params):
resource_params = {}
self.build_test_descriptors(resource_params)
sample_resource = self.sample_resource_factory(resource_iontype, resource_params)
all_in_one = self.all_in_one
find_cv_func = self.find_class_variable_name
service_type = type(self.service_instance)
added_methods = {}
def add_new_method(name, docstring, newmethod):
'\n dynamically add a new method to the tester class\n @param name the name of the new method\n @param docstring a description of the test\n @newmethod the function itself\n '
newmethod.__name__ = name
newmethod.__doc__ = docstring
setattr(self.tester_class, newmethod.__name__, newmethod)
added_methods[name] = True
def add_test_method(name, docstring, newmethod):
'\n dynamically add a test method to the tester class\n @param name the name of the test function (minus the "test_" part)\n @param docstring a description of the test\n @newmethod the function itself\n '
add_new_method(('test_%s' % name), docstring, newmethod)
def make_name(name):
'\n make a good name for a test from the resource name and an md5 of extra params\n @param name the base string for the name\n '
assert self.sample_resource_md5
return ('%s%s' % (name, self.sample_resource_md5))
def make_doc(doc):
'\n make a good doc string for a test from by including the extra params\n @param doc the base string for the descripton\n '
return ('%s %s' % (doc, self.sample_resource_extras))
def gen_svc_cleanup():
def fun(instance):
for (k, _) in added_methods.iteritems():
if hasattr(instance, k):
instance.addCleanup(delattr, instance, k)
add_new_method(('_utg_cleanup_%s%s' % (resource_iontype, self.sample_resource_md5)), 'Cleanup', fun)
def whole_cleanup(instance):
for k in dir(instance):
if ((- 1) < k.find('_utg_cleanup_')):
cleanup_fn = getattr(instance, k)
cleanup_fn()
add_new_method('_utg_whole_cleanup', 'Global cleanup', whole_cleanup)
def gen_svc_lookup():
'\n put a new method in the tester class to find the instance of the service being tested\n\n the prefix is "_utg_": unit_test_generator\n '
def getsvc_fun(self):
'\n self is an instance of the tester class\n '
if (not hasattr(self, '_utg_service_obj')):
service_itself = getattr(self, find_cv_func(self, service_type))
self._utg_service_obj = service_itself
assert self._utg_service_obj
return self._utg_service_obj
def getcrudmethod_fun(self, rsrc_lbl, method_str):
'\n self is an instance of the tester class\n method_str is a crud method name like "create" that will become "create_resource_label"\n '
svc = self._utg_getservice()
methodname = ('%s_%s' % (method_str, rsrc_lbl))
if (not hasattr(svc, methodname)):
raise SkipTest('CRUD method does not exist, skipping')
return getattr(svc, methodname)
if (not hasattr(self.tester_class, '_utg_getservice')):
add_new_method('_utg_getservice', 'Finds instance of service under test', getsvc_fun)
if (not hasattr(self.tester_class, '_utg_getcrudmethod')):
add_new_method('_utg_getcrudmethod', 'Finds instance of crud method in service', getcrudmethod_fun)
def test_create_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_create_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
good_sample_resource = sample_resource()
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
sample_resource_id = testfun(good_sample_resource)
svc.clients.resource_registry.create.assert_called_once_with(good_sample_resource)
self.assertEqual(sample_resource_id, '111')
def test_create_bad_wrongtype_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_create_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = IonObject(RT.Resource, name='Generic Resource')
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
self.assertRaisesRegexp(BadRequest, 'type', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count)
def test_create_bad_noname_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_create_bad_noname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = sample_resource()
delattr(bad_sample_resource, 'name')
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
self.assertRaisesRegexp(BadRequest, 'name', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count)
def test_create_bad_dupname_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_create_bad_dupname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = sample_resource()
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([0], [0])
self.assertRaisesRegexp(BadRequest, 'uplicate', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count)
def test_read_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_read_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'read')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
response = testfun('111')
svc.clients.resource_registry.read.assert_called_once_with('111', )
self.assertEqual(response, myret)
if all_in_one:
svc.clients.resource_registry.reset_mock()
def test_read_bad_wrongtype_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_read_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'read')
myret = IonObject(RT.Resource, name='Generic Resource')
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
self.assertEqual(0, svc.clients.resource_registry.read.call_count)
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
svc.clients.resource_registry.read.assert_called_once_with('111', )
def test_update_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_update_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
good_sample_resource = sample_resource()
setattr(good_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
svc.clients.resource_registry.update.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
testfun(good_sample_resource)
svc.clients.resource_registry.update.assert_called_once_with(good_sample_resource)
def test_update_bad_dupname_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_update_bad_dupname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
bad_sample_resource = sample_resource()
setattr(bad_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
svc.clients.resource_registry.find_resources.return_value = ([0], [0])
self.assertRaisesRegexp(BadRequest, 'uplicate', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.update.call_count)
def test_update_bad_wrongtype_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_update_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
bad_sample_resource = IonObject(RT.Resource, name='Generic Name')
setattr(bad_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
self.assertRaisesRegexp(BadRequest, 'type', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.update.call_count)
def test_delete_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_delete_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'delete')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
svc.clients.resource_registry.read.return_value = myret
svc.clients.resource_registry.delete.return_value = None
svc.clients.resource_registry.lcs_delete.return_value = None
try:
testfun('111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
svc.clients.resource_registry.reset_mock()
return
else:
raise SkipTest('Must test this with INT test')
svc.clients.resource_registry.lcs_delete.assert_called_once_with('111')
self.assertEqual(0, svc.clients.resource_registry.delete.call_count)
def test_delete_bad_wrongtype_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_delete_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'delete')
myret = IonObject(RT.Resource, name='Generic Name')
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
try:
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
self.assertEqual(0, svc.clients.resource_registry.lcs_delete.call_count)
self.assertEqual(0, svc.clients.resource_registry.delete.call_count)
def test_force_delete_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_force_delete_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'force_delete')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
svc.clients.resource_registry.read.return_value = myret
svc.clients.resource_registry.delete.return_value = None
svc.clients.resource_registry.find_resources.return_value = None
svc.clients.resource_registry.find_objects.return_value = ([], [])
svc.clients.resource_registry.find_subjects.return_value = ([], [])
try:
testfun('111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
svc.clients.resource_registry.delete.assert_called_once_with('111')
def test_force_delete_bad_wrongtype_fun(self):
'\n self is an inst ance of the tester class\n '
log.debug('test_force_delete_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'force_delete')
myret = IonObject(RT.Resource, name='Generic Name')
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.find_objects.return_value = ([], [])
svc.clients.resource_registry.find_subjects.return_value = ([], [])
svc.clients.resource_registry.read.return_value = myret
try:
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
self.assertEqual(0, svc.clients.resource_registry.lcs_delete.call_count)
self.assertEqual(0, svc.clients.resource_registry.delete.call_count)
def gen_test_create():
'\n generate the function to test the create\n '
name = make_name(('%s_create' % resource_label))
doc = make_doc(('Creation of a new %s resource' % resource_iontype))
add_test_method(name, doc, test_create_fun)
def gen_test_create_bad_wrongtype():
'\n generate the function to test the create for the wrong resource type\n '
name = make_name(('%s_create_bad_wrongtype' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (wrong type)' % resource_iontype))
add_test_method(name, doc, test_create_bad_wrongtype_fun)
def gen_test_create_bad_noname():
'\n generate the function to test the create in a bad case\n '
name = make_name(('%s_create_bad_noname' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (no name)' % resource_iontype))
add_test_method(name, doc, test_create_bad_noname_fun)
def gen_test_create_bad_dupname():
'\n generate the function to test the create in a bad case where the name already exists\n '
name = make_name(('%s_create_bad_dupname' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (duplicate name)' % resource_iontype))
add_test_method(name, doc, test_create_bad_dupname_fun)
def gen_test_read():
'\n generate the function to test the read\n '
name = make_name(('%s_read' % resource_label))
doc = make_doc(('Reading a %s resource' % resource_iontype))
add_test_method(name, doc, test_read_fun)
def gen_test_read_bad_wrongtype():
'\n generate the function to test the read with bad type\n '
name = make_name(('%s_read_bad_wrongtype' % resource_label))
doc = make_doc(('Reading a %s resource but having it come back as wrong type' % resource_iontype))
add_test_method(name, doc, test_read_bad_wrongtype_fun)
def gen_test_update():
'\n generate the function to test the update\n '
name = make_name(('%s_update' % resource_label))
doc = make_doc(('Updating a %s resource' % resource_iontype))
add_test_method(name, doc, test_update_fun)
def gen_test_update_bad_wrongtype():
'\n generate the function to test the update with wrong type\n '
name = make_name(('%s_update_bad_wrongtype' % resource_label))
doc = make_doc(('Updating a %s resource with the wrong type' % resource_iontype))
add_test_method(name, doc, test_update_bad_wrongtype_fun)
def gen_test_update_bad_dupname():
'\n generate the function to test the update with wrong type\n '
name = make_name(('%s_update_bad_duplicate' % resource_label))
doc = make_doc(('Updating a %s resource to a duplicate name' % resource_iontype))
add_test_method(name, doc, test_update_bad_dupname_fun)
def gen_test_delete():
'\n generate the function to test the delete\n '
name = make_name(('%s_delete' % resource_label))
doc = make_doc(('Deleting (retiring) a %s resource' % resource_iontype))
add_test_method(name, doc, test_delete_fun)
def gen_test_delete_bad_wrongtype():
'\n generate the function to test the delete with wrong type\n '
name = make_name(('%s_delete_bad_wrongtype' % resource_label))
doc = make_doc(('Deleting (retiring) a %s resource of the wrong type' % resource_iontype))
add_test_method(name, doc, test_delete_bad_wrongtype_fun)
def gen_test_force_delete():
'\n generate the function to test the delete\n '
name = make_name(('%s_force_delete' % resource_label))
doc = make_doc(('Deleting -- destructively -- a %s resource' % resource_iontype))
add_test_method(name, doc, test_force_delete_fun)
def gen_test_force_delete_bad_wrongtype():
'\n generate the function to test the delete with the wrong type\n '
name = make_name(('%s_force_delete_bad_wrongtype' % resource_label))
doc = make_doc(('Deleting -- destructively -- a %s resource of the wrong type' % resource_iontype))
add_test_method(name, doc, test_force_delete_bad_wrongtype_fun)
def gen_test_allinone():
'\n generate the function to test EVERYTHING at once\n '
def fun(self):
'\n self is an instance of the tester class\n '
test_create_fun(self)
test_create_bad_wrongtype_fun(self)
test_create_bad_noname_fun(self)
test_read_fun(self)
test_read_bad_wrongtype_fun(self)
test_update_fun(self)
test_update_bad_wrongtype_fun(self)
test_delete_fun(self)
test_delete_bad_wrongtype_fun(self)
test_force_delete_fun(self)
test_force_delete_bad_wrongtype_fun(self)
name = make_name(('%s_allinone' % resource_label))
doc = make_doc(('Performing all CRUD tests on %s resources' % resource_iontype))
add_test_method(name, doc, fun)
gen_svc_lookup()
if all_in_one:
gen_test_allinone()
else:
gen_test_create()
gen_test_create_bad_wrongtype()
gen_test_create_bad_noname()
gen_test_read()
gen_test_read_bad_wrongtype()
gen_test_update()
gen_test_update_bad_wrongtype()
gen_test_delete()
gen_test_delete_bad_wrongtype()
gen_test_force_delete()
gen_test_force_delete_bad_wrongtype() | def add_resource_unittests(self, resource_iontype, resource_label, resource_params=None):
'\n Add tests for the resorce_impl_class to the (self.)resource_tester_class\n\n @param resource_iontype the IonObject type to test with (e.g. RT.PlatformModel)\n @param resource_label the base of the function names for this resource (e.g. platform_model)\n @param resource_params dictionary of extra params to add to the sample resource\n\n this function will be huge. it is a list of smaller functions that are templates\n for tests of various resource_impl class functionality. the functions are given\n proper references to member variables in the service and test class, then injected\n into the test class itself.\n\n '
if (None == resource_params):
resource_params = {}
self.build_test_descriptors(resource_params)
sample_resource = self.sample_resource_factory(resource_iontype, resource_params)
all_in_one = self.all_in_one
find_cv_func = self.find_class_variable_name
service_type = type(self.service_instance)
added_methods = {}
def add_new_method(name, docstring, newmethod):
'\n dynamically add a new method to the tester class\n @param name the name of the new method\n @param docstring a description of the test\n @newmethod the function itself\n '
newmethod.__name__ = name
newmethod.__doc__ = docstring
setattr(self.tester_class, newmethod.__name__, newmethod)
added_methods[name] = True
def add_test_method(name, docstring, newmethod):
'\n dynamically add a test method to the tester class\n @param name the name of the test function (minus the "test_" part)\n @param docstring a description of the test\n @newmethod the function itself\n '
add_new_method(('test_%s' % name), docstring, newmethod)
def make_name(name):
'\n make a good name for a test from the resource name and an md5 of extra params\n @param name the base string for the name\n '
assert self.sample_resource_md5
return ('%s%s' % (name, self.sample_resource_md5))
def make_doc(doc):
'\n make a good doc string for a test from by including the extra params\n @param doc the base string for the descripton\n '
return ('%s %s' % (doc, self.sample_resource_extras))
def gen_svc_cleanup():
def fun(instance):
for (k, _) in added_methods.iteritems():
if hasattr(instance, k):
instance.addCleanup(delattr, instance, k)
add_new_method(('_utg_cleanup_%s%s' % (resource_iontype, self.sample_resource_md5)), 'Cleanup', fun)
def whole_cleanup(instance):
for k in dir(instance):
if ((- 1) < k.find('_utg_cleanup_')):
cleanup_fn = getattr(instance, k)
cleanup_fn()
add_new_method('_utg_whole_cleanup', 'Global cleanup', whole_cleanup)
def gen_svc_lookup():
'\n put a new method in the tester class to find the instance of the service being tested\n\n the prefix is "_utg_": unit_test_generator\n '
def getsvc_fun(self):
'\n self is an instance of the tester class\n '
if (not hasattr(self, '_utg_service_obj')):
service_itself = getattr(self, find_cv_func(self, service_type))
self._utg_service_obj = service_itself
assert self._utg_service_obj
return self._utg_service_obj
def getcrudmethod_fun(self, rsrc_lbl, method_str):
'\n self is an instance of the tester class\n method_str is a crud method name like "create" that will become "create_resource_label"\n '
svc = self._utg_getservice()
methodname = ('%s_%s' % (method_str, rsrc_lbl))
if (not hasattr(svc, methodname)):
raise SkipTest('CRUD method does not exist, skipping')
return getattr(svc, methodname)
if (not hasattr(self.tester_class, '_utg_getservice')):
add_new_method('_utg_getservice', 'Finds instance of service under test', getsvc_fun)
if (not hasattr(self.tester_class, '_utg_getcrudmethod')):
add_new_method('_utg_getcrudmethod', 'Finds instance of crud method in service', getcrudmethod_fun)
def test_create_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_create_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
good_sample_resource = sample_resource()
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
sample_resource_id = testfun(good_sample_resource)
svc.clients.resource_registry.create.assert_called_once_with(good_sample_resource)
self.assertEqual(sample_resource_id, '111')
def test_create_bad_wrongtype_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_create_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = IonObject(RT.Resource, name='Generic Resource')
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
self.assertRaisesRegexp(BadRequest, 'type', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count)
def test_create_bad_noname_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_create_bad_noname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = sample_resource()
delattr(bad_sample_resource, 'name')
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
self.assertRaisesRegexp(BadRequest, 'name', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count)
def test_create_bad_dupname_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_create_bad_dupname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = sample_resource()
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([0], [0])
self.assertRaisesRegexp(BadRequest, 'uplicate', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count)
def test_read_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_read_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'read')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
response = testfun('111')
svc.clients.resource_registry.read.assert_called_once_with('111', )
self.assertEqual(response, myret)
if all_in_one:
svc.clients.resource_registry.reset_mock()
def test_read_bad_wrongtype_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_read_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'read')
myret = IonObject(RT.Resource, name='Generic Resource')
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
self.assertEqual(0, svc.clients.resource_registry.read.call_count)
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
svc.clients.resource_registry.read.assert_called_once_with('111', )
def test_update_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_update_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
good_sample_resource = sample_resource()
setattr(good_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
svc.clients.resource_registry.update.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
testfun(good_sample_resource)
svc.clients.resource_registry.update.assert_called_once_with(good_sample_resource)
def test_update_bad_dupname_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_update_bad_dupname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
bad_sample_resource = sample_resource()
setattr(bad_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
svc.clients.resource_registry.find_resources.return_value = ([0], [0])
self.assertRaisesRegexp(BadRequest, 'uplicate', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.update.call_count)
def test_update_bad_wrongtype_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_update_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
bad_sample_resource = IonObject(RT.Resource, name='Generic Name')
setattr(bad_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
self.assertRaisesRegexp(BadRequest, 'type', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.update.call_count)
def test_delete_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_delete_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'delete')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
svc.clients.resource_registry.read.return_value = myret
svc.clients.resource_registry.delete.return_value = None
svc.clients.resource_registry.lcs_delete.return_value = None
try:
testfun('111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
svc.clients.resource_registry.reset_mock()
return
else:
raise SkipTest('Must test this with INT test')
svc.clients.resource_registry.lcs_delete.assert_called_once_with('111')
self.assertEqual(0, svc.clients.resource_registry.delete.call_count)
def test_delete_bad_wrongtype_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_delete_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'delete')
myret = IonObject(RT.Resource, name='Generic Name')
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
try:
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
self.assertEqual(0, svc.clients.resource_registry.lcs_delete.call_count)
self.assertEqual(0, svc.clients.resource_registry.delete.call_count)
def test_force_delete_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_force_delete_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'force_delete')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
svc.clients.resource_registry.read.return_value = myret
svc.clients.resource_registry.delete.return_value = None
svc.clients.resource_registry.find_resources.return_value = None
svc.clients.resource_registry.find_objects.return_value = ([], [])
svc.clients.resource_registry.find_subjects.return_value = ([], [])
try:
testfun('111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
svc.clients.resource_registry.delete.assert_called_once_with('111')
def test_force_delete_bad_wrongtype_fun(self):
'\n self is an inst ance of the tester class\n '
log.debug('test_force_delete_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'force_delete')
myret = IonObject(RT.Resource, name='Generic Name')
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.find_objects.return_value = ([], [])
svc.clients.resource_registry.find_subjects.return_value = ([], [])
svc.clients.resource_registry.read.return_value = myret
try:
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
self.assertEqual(0, svc.clients.resource_registry.lcs_delete.call_count)
self.assertEqual(0, svc.clients.resource_registry.delete.call_count)
def gen_test_create():
'\n generate the function to test the create\n '
name = make_name(('%s_create' % resource_label))
doc = make_doc(('Creation of a new %s resource' % resource_iontype))
add_test_method(name, doc, test_create_fun)
def gen_test_create_bad_wrongtype():
'\n generate the function to test the create for the wrong resource type\n '
name = make_name(('%s_create_bad_wrongtype' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (wrong type)' % resource_iontype))
add_test_method(name, doc, test_create_bad_wrongtype_fun)
def gen_test_create_bad_noname():
'\n generate the function to test the create in a bad case\n '
name = make_name(('%s_create_bad_noname' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (no name)' % resource_iontype))
add_test_method(name, doc, test_create_bad_noname_fun)
def gen_test_create_bad_dupname():
'\n generate the function to test the create in a bad case where the name already exists\n '
name = make_name(('%s_create_bad_dupname' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (duplicate name)' % resource_iontype))
add_test_method(name, doc, test_create_bad_dupname_fun)
def gen_test_read():
'\n generate the function to test the read\n '
name = make_name(('%s_read' % resource_label))
doc = make_doc(('Reading a %s resource' % resource_iontype))
add_test_method(name, doc, test_read_fun)
def gen_test_read_bad_wrongtype():
'\n generate the function to test the read with bad type\n '
name = make_name(('%s_read_bad_wrongtype' % resource_label))
doc = make_doc(('Reading a %s resource but having it come back as wrong type' % resource_iontype))
add_test_method(name, doc, test_read_bad_wrongtype_fun)
def gen_test_update():
'\n generate the function to test the update\n '
name = make_name(('%s_update' % resource_label))
doc = make_doc(('Updating a %s resource' % resource_iontype))
add_test_method(name, doc, test_update_fun)
def gen_test_update_bad_wrongtype():
'\n generate the function to test the update with wrong type\n '
name = make_name(('%s_update_bad_wrongtype' % resource_label))
doc = make_doc(('Updating a %s resource with the wrong type' % resource_iontype))
add_test_method(name, doc, test_update_bad_wrongtype_fun)
def gen_test_update_bad_dupname():
'\n generate the function to test the update with wrong type\n '
name = make_name(('%s_update_bad_duplicate' % resource_label))
doc = make_doc(('Updating a %s resource to a duplicate name' % resource_iontype))
add_test_method(name, doc, test_update_bad_dupname_fun)
def gen_test_delete():
'\n generate the function to test the delete\n '
name = make_name(('%s_delete' % resource_label))
doc = make_doc(('Deleting (retiring) a %s resource' % resource_iontype))
add_test_method(name, doc, test_delete_fun)
def gen_test_delete_bad_wrongtype():
'\n generate the function to test the delete with wrong type\n '
name = make_name(('%s_delete_bad_wrongtype' % resource_label))
doc = make_doc(('Deleting (retiring) a %s resource of the wrong type' % resource_iontype))
add_test_method(name, doc, test_delete_bad_wrongtype_fun)
def gen_test_force_delete():
'\n generate the function to test the delete\n '
name = make_name(('%s_force_delete' % resource_label))
doc = make_doc(('Deleting -- destructively -- a %s resource' % resource_iontype))
add_test_method(name, doc, test_force_delete_fun)
def gen_test_force_delete_bad_wrongtype():
'\n generate the function to test the delete with the wrong type\n '
name = make_name(('%s_force_delete_bad_wrongtype' % resource_label))
doc = make_doc(('Deleting -- destructively -- a %s resource of the wrong type' % resource_iontype))
add_test_method(name, doc, test_force_delete_bad_wrongtype_fun)
def gen_test_allinone():
'\n generate the function to test EVERYTHING at once\n '
def fun(self):
'\n self is an instance of the tester class\n '
test_create_fun(self)
test_create_bad_wrongtype_fun(self)
test_create_bad_noname_fun(self)
test_read_fun(self)
test_read_bad_wrongtype_fun(self)
test_update_fun(self)
test_update_bad_wrongtype_fun(self)
test_delete_fun(self)
test_delete_bad_wrongtype_fun(self)
test_force_delete_fun(self)
test_force_delete_bad_wrongtype_fun(self)
name = make_name(('%s_allinone' % resource_label))
doc = make_doc(('Performing all CRUD tests on %s resources' % resource_iontype))
add_test_method(name, doc, fun)
gen_svc_lookup()
if all_in_one:
gen_test_allinone()
else:
gen_test_create()
gen_test_create_bad_wrongtype()
gen_test_create_bad_noname()
gen_test_read()
gen_test_read_bad_wrongtype()
gen_test_update()
gen_test_update_bad_wrongtype()
gen_test_delete()
gen_test_delete_bad_wrongtype()
gen_test_force_delete()
gen_test_force_delete_bad_wrongtype()<|docstring|>Add tests for the resorce_impl_class to the (self.)resource_tester_class
@param resource_iontype the IonObject type to test with (e.g. RT.PlatformModel)
@param resource_label the base of the function names for this resource (e.g. platform_model)
@param resource_params dictionary of extra params to add to the sample resource
this function will be huge. it is a list of smaller functions that are templates
for tests of various resource_impl class functionality. the functions are given
proper references to member variables in the service and test class, then injected
into the test class itself.<|endoftext|> |
731d7fae1818237dacb0c0afb463d98f9b95e6487cb1abb4a5d0214e55eb9f8e | def assert_lcs_fail(self, owner_service, resource_label, resource_id, lc_event):
'\n execute an lcs event and verify that it fails\n\n @param owner_service instance of service client that will handle the request\n @param resource_label string like "instrument_device"\n @param resource_id string\n @param lc_event string like LCE.INTEGRATE\n '
lcsmethod = getattr(owner_service, ('execute_%s_lifecycle' % resource_label))
if True:
log.warn('Skipping generic_lcs_fail for beta testing purposes')
return
self.assertRaises(Unauthorized, lcsmethod, resource_id, lc_event) | execute an lcs event and verify that it fails
@param owner_service instance of service client that will handle the request
@param resource_label string like "instrument_device"
@param resource_id string
@param lc_event string like LCE.INTEGRATE | ion/services/sa/test/helpers.py | assert_lcs_fail | ooici/coi-services | 3 | python | def assert_lcs_fail(self, owner_service, resource_label, resource_id, lc_event):
'\n execute an lcs event and verify that it fails\n\n @param owner_service instance of service client that will handle the request\n @param resource_label string like "instrument_device"\n @param resource_id string\n @param lc_event string like LCE.INTEGRATE\n '
lcsmethod = getattr(owner_service, ('execute_%s_lifecycle' % resource_label))
if True:
log.warn('Skipping generic_lcs_fail for beta testing purposes')
return
self.assertRaises(Unauthorized, lcsmethod, resource_id, lc_event) | def assert_lcs_fail(self, owner_service, resource_label, resource_id, lc_event):
'\n execute an lcs event and verify that it fails\n\n @param owner_service instance of service client that will handle the request\n @param resource_label string like "instrument_device"\n @param resource_id string\n @param lc_event string like LCE.INTEGRATE\n '
lcsmethod = getattr(owner_service, ('execute_%s_lifecycle' % resource_label))
if True:
log.warn('Skipping generic_lcs_fail for beta testing purposes')
return
self.assertRaises(Unauthorized, lcsmethod, resource_id, lc_event)<|docstring|>execute an lcs event and verify that it fails
@param owner_service instance of service client that will handle the request
@param resource_label string like "instrument_device"
@param resource_id string
@param lc_event string like LCE.INTEGRATE<|endoftext|> |
1b60af4906a2f8946fa60ec4a173cc87739b5709e297ea608d08b5ead5f59db6 | def assert_lcs_pass(self, owner_service, resource_label, resource_id, lc_event, lc_state):
'\n execute an lcs event and verify that it passes and affects state\n\n @param owner_service instance of service client that will handle the request\n @param resource_label string like "instrument_device"\n @param resource_id string\n @param lc_event string like LCE.INTEGRATE\n @param lc_state string like LCS.INTEGRATED (where the state should end up\n '
lcsmethod = getattr(owner_service, ('execute_%s_lifecycle' % resource_label))
readmethod = getattr(owner_service, ('read_%s' % resource_label))
lcsmethod(resource_id, lc_event)
resource_obj = readmethod(resource_id)
self.assertEqual(lc_state, resource_obj.lcstate) | execute an lcs event and verify that it passes and affects state
@param owner_service instance of service client that will handle the request
@param resource_label string like "instrument_device"
@param resource_id string
@param lc_event string like LCE.INTEGRATE
@param lc_state string like LCS.INTEGRATED (where the state should end up | ion/services/sa/test/helpers.py | assert_lcs_pass | ooici/coi-services | 3 | python | def assert_lcs_pass(self, owner_service, resource_label, resource_id, lc_event, lc_state):
'\n execute an lcs event and verify that it passes and affects state\n\n @param owner_service instance of service client that will handle the request\n @param resource_label string like "instrument_device"\n @param resource_id string\n @param lc_event string like LCE.INTEGRATE\n @param lc_state string like LCS.INTEGRATED (where the state should end up\n '
lcsmethod = getattr(owner_service, ('execute_%s_lifecycle' % resource_label))
readmethod = getattr(owner_service, ('read_%s' % resource_label))
lcsmethod(resource_id, lc_event)
resource_obj = readmethod(resource_id)
self.assertEqual(lc_state, resource_obj.lcstate) | def assert_lcs_pass(self, owner_service, resource_label, resource_id, lc_event, lc_state):
'\n execute an lcs event and verify that it passes and affects state\n\n @param owner_service instance of service client that will handle the request\n @param resource_label string like "instrument_device"\n @param resource_id string\n @param lc_event string like LCE.INTEGRATE\n @param lc_state string like LCS.INTEGRATED (where the state should end up\n '
lcsmethod = getattr(owner_service, ('execute_%s_lifecycle' % resource_label))
readmethod = getattr(owner_service, ('read_%s' % resource_label))
lcsmethod(resource_id, lc_event)
resource_obj = readmethod(resource_id)
self.assertEqual(lc_state, resource_obj.lcstate)<|docstring|>execute an lcs event and verify that it passes and affects state
@param owner_service instance of service client that will handle the request
@param resource_label string like "instrument_device"
@param resource_id string
@param lc_event string like LCE.INTEGRATE
@param lc_state string like LCS.INTEGRATED (where the state should end up<|endoftext|> |
5bb0da129c6d97c999ee6dbc2ee8f51677a2e27b83d5b2228757ba3ce7ed1e60 | def perform_association_script(self, assign_obj_to_subj_fn, find_subj_fn, find_obj_fn, subj_id, obj_id):
'\n create an association and test that it went properly\n\n @param assign_obj_to_subj_fn the service method that takes (obj, subj) and associates them\n @param find_subj_fn the service method that returns a list of subjects given an object\n @param find_obj_fn the service method that returns a list of objects given a subject\n @param subj_id the subject id to associate\n @param obj_id the object id to associate\n '
initial_subj_count = len(find_subj_fn(obj_id))
initial_obj_count = len(find_obj_fn(subj_id))
log.debug('Creating association')
if (not ('str' == type(subj_id).__name__ == type(obj_id).__name__)):
raise NotImplementedError(("%s='%s' to %s='%s'" % (type(subj_id), str(subj_id), type(obj_id), str(obj_id))))
if (not (subj_id and obj_id)):
raise NotImplementedError(("%s='%s' to %s='%s'" % (type(subj_id), str(subj_id), type(obj_id), str(obj_id))))
assign_obj_to_subj_fn(obj_id, subj_id)
log.debug('Verifying find-subj-by-obj')
subjects = find_subj_fn(obj_id)
self.assertEqual((initial_subj_count + 1), len(subjects))
subject_ids = []
for x in subjects:
if (not ('_id' in x)):
raise Inconsistent(("'_id' field not found in resource! got: %s" % str(x)))
subject_ids.append(x._id)
self.assertIn(subj_id, subject_ids)
log.debug('Verifying find-obj-by-subj')
objects = find_obj_fn(subj_id)
self.assertEqual((initial_obj_count + 1), len(objects))
object_ids = []
for x in objects:
if (not ('_id' in x)):
raise Inconsistent(("'_id' field not found in resource! got: %s" % str(x)))
object_ids.append(x._id)
self.assertIn(obj_id, object_ids) | create an association and test that it went properly
@param assign_obj_to_subj_fn the service method that takes (obj, subj) and associates them
@param find_subj_fn the service method that returns a list of subjects given an object
@param find_obj_fn the service method that returns a list of objects given a subject
@param subj_id the subject id to associate
@param obj_id the object id to associate | ion/services/sa/test/helpers.py | perform_association_script | ooici/coi-services | 3 | python | def perform_association_script(self, assign_obj_to_subj_fn, find_subj_fn, find_obj_fn, subj_id, obj_id):
'\n create an association and test that it went properly\n\n @param assign_obj_to_subj_fn the service method that takes (obj, subj) and associates them\n @param find_subj_fn the service method that returns a list of subjects given an object\n @param find_obj_fn the service method that returns a list of objects given a subject\n @param subj_id the subject id to associate\n @param obj_id the object id to associate\n '
initial_subj_count = len(find_subj_fn(obj_id))
initial_obj_count = len(find_obj_fn(subj_id))
log.debug('Creating association')
if (not ('str' == type(subj_id).__name__ == type(obj_id).__name__)):
raise NotImplementedError(("%s='%s' to %s='%s'" % (type(subj_id), str(subj_id), type(obj_id), str(obj_id))))
if (not (subj_id and obj_id)):
raise NotImplementedError(("%s='%s' to %s='%s'" % (type(subj_id), str(subj_id), type(obj_id), str(obj_id))))
assign_obj_to_subj_fn(obj_id, subj_id)
log.debug('Verifying find-subj-by-obj')
subjects = find_subj_fn(obj_id)
self.assertEqual((initial_subj_count + 1), len(subjects))
subject_ids = []
for x in subjects:
if (not ('_id' in x)):
raise Inconsistent(("'_id' field not found in resource! got: %s" % str(x)))
subject_ids.append(x._id)
self.assertIn(subj_id, subject_ids)
log.debug('Verifying find-obj-by-subj')
objects = find_obj_fn(subj_id)
self.assertEqual((initial_obj_count + 1), len(objects))
object_ids = []
for x in objects:
if (not ('_id' in x)):
raise Inconsistent(("'_id' field not found in resource! got: %s" % str(x)))
object_ids.append(x._id)
self.assertIn(obj_id, object_ids) | def perform_association_script(self, assign_obj_to_subj_fn, find_subj_fn, find_obj_fn, subj_id, obj_id):
'\n create an association and test that it went properly\n\n @param assign_obj_to_subj_fn the service method that takes (obj, subj) and associates them\n @param find_subj_fn the service method that returns a list of subjects given an object\n @param find_obj_fn the service method that returns a list of objects given a subject\n @param subj_id the subject id to associate\n @param obj_id the object id to associate\n '
initial_subj_count = len(find_subj_fn(obj_id))
initial_obj_count = len(find_obj_fn(subj_id))
log.debug('Creating association')
if (not ('str' == type(subj_id).__name__ == type(obj_id).__name__)):
raise NotImplementedError(("%s='%s' to %s='%s'" % (type(subj_id), str(subj_id), type(obj_id), str(obj_id))))
if (not (subj_id and obj_id)):
raise NotImplementedError(("%s='%s' to %s='%s'" % (type(subj_id), str(subj_id), type(obj_id), str(obj_id))))
assign_obj_to_subj_fn(obj_id, subj_id)
log.debug('Verifying find-subj-by-obj')
subjects = find_subj_fn(obj_id)
self.assertEqual((initial_subj_count + 1), len(subjects))
subject_ids = []
for x in subjects:
if (not ('_id' in x)):
raise Inconsistent(("'_id' field not found in resource! got: %s" % str(x)))
subject_ids.append(x._id)
self.assertIn(subj_id, subject_ids)
log.debug('Verifying find-obj-by-subj')
objects = find_obj_fn(subj_id)
self.assertEqual((initial_obj_count + 1), len(objects))
object_ids = []
for x in objects:
if (not ('_id' in x)):
raise Inconsistent(("'_id' field not found in resource! got: %s" % str(x)))
object_ids.append(x._id)
self.assertIn(obj_id, object_ids)<|docstring|>create an association and test that it went properly
@param assign_obj_to_subj_fn the service method that takes (obj, subj) and associates them
@param find_subj_fn the service method that returns a list of subjects given an object
@param find_obj_fn the service method that returns a list of objects given a subject
@param subj_id the subject id to associate
@param obj_id the object id to associate<|endoftext|> |
acaf3f4eb110efa9f0727d62957f4467f5edc4cdd3861619a613de7bc9f72ff2 | def perform_fd_script(self, resource_id, resource_label, owner_service):
'\n delete a resource and check that it was properly deleted\n\n @param resource_id id to be deleted\n @param resource_label something like platform_model\n @param owner_service service client instance\n '
del_op = getattr(owner_service, ('force_delete_%s' % resource_label))
del_op(resource_id)
self.assertRaises(NotFound, del_op, resource_id) | delete a resource and check that it was properly deleted
@param resource_id id to be deleted
@param resource_label something like platform_model
@param owner_service service client instance | ion/services/sa/test/helpers.py | perform_fd_script | ooici/coi-services | 3 | python | def perform_fd_script(self, resource_id, resource_label, owner_service):
'\n delete a resource and check that it was properly deleted\n\n @param resource_id id to be deleted\n @param resource_label something like platform_model\n @param owner_service service client instance\n '
del_op = getattr(owner_service, ('force_delete_%s' % resource_label))
del_op(resource_id)
self.assertRaises(NotFound, del_op, resource_id) | def perform_fd_script(self, resource_id, resource_label, owner_service):
'\n delete a resource and check that it was properly deleted\n\n @param resource_id id to be deleted\n @param resource_label something like platform_model\n @param owner_service service client instance\n '
del_op = getattr(owner_service, ('force_delete_%s' % resource_label))
del_op(resource_id)
self.assertRaises(NotFound, del_op, resource_id)<|docstring|>delete a resource and check that it was properly deleted
@param resource_id id to be deleted
@param resource_label something like platform_model
@param owner_service service client instance<|endoftext|> |
3bd3990f8dceb66c39e4dd9aef43d1fc61e263e5f423f38210f729dae27121a7 | def perform_fcruf_script(self, resource_iontype, resource_label, owner_service, actual_obj=None, extra_fn=None):
'\n run through find, create, read, update, and find ops on a basic resource\n\n NO DELETE in here.\n\n @param resource_iontype something like RT.PlatformModel\n @param resource_label something like platform_model\n @param owner_service a service client instance like InstrumentManagementServiceClient\n @param actual_obj use this IonObject instead of a generic object for testing\n @param extra_fn a function to run after the script, taking the new resource id as input\n @return generic_id, the resource_id of the generic resource that was created\n '
some_service = DotDict()
def fill(svc, method):
'\n make a "shortcut service" for testing crud ops.\n @param svc a dotdict\n @param method the method name to add\n '
realmethod = ('%s_widget' % method)
setattr(svc, realmethod, getattr(owner_service, ('%s_%s' % (method, resource_label))))
fill(some_service, 'create')
fill(some_service, 'read')
fill(some_service, 'update')
fill(some_service, 'delete')
def find_widgets():
(ret, _) = self.generic_int_helper_rr.find_resources(resource_iontype, None, None, False)
return ret
log.info('Finding %s objects', resource_label)
num_objs = len(find_widgets())
log.info('I found %d %s objects', num_objs, resource_label)
generic_obj = (actual_obj or any_old(resource_iontype))
log.info("Creating a %s with name='%s'", resource_label, generic_obj.name)
generic_id = some_service.create_widget(generic_obj)
self.assertIsNotNone(generic_id, ('%s failed its creation' % resource_iontype))
log.info("Reading %s '%s'", resource_label, generic_id)
generic_ret = some_service.read_widget(generic_id)
log.info('Verifying equality of stored and retrieved object')
self.assertEqual(generic_obj.name, generic_ret.name)
self.assertEqual(generic_obj.description, generic_ret.description)
log.info("Updating %s '%s'", resource_label, generic_id)
generic_newname = ('%s updated' % generic_ret.name)
generic_ret.name = generic_newname
some_service.update_widget(generic_ret)
log.info("Reading %s '%s' to verify update", resource_iontype, generic_id)
generic_ret = some_service.read_widget(generic_id)
self.assertEqual(generic_newname, generic_ret.name)
self.assertEqual(generic_obj.description, generic_ret.description)
log.info("Finding %s objects... checking that there's a new one", resource_iontype)
num_objs2 = len(find_widgets())
log.info('There were %s and now there are %s', num_objs, num_objs2)
self.assertTrue((num_objs2 > num_objs))
if (not (extra_fn is None)):
log.info(("Running extra_fn on generic resource '%s'" % generic_id))
extra_fn(generic_id)
log.info("Returning %s with id '%s'", resource_iontype, generic_id)
return generic_id | run through find, create, read, update, and find ops on a basic resource
NO DELETE in here.
@param resource_iontype something like RT.PlatformModel
@param resource_label something like platform_model
@param owner_service a service client instance like InstrumentManagementServiceClient
@param actual_obj use this IonObject instead of a generic object for testing
@param extra_fn a function to run after the script, taking the new resource id as input
@return generic_id, the resource_id of the generic resource that was created | ion/services/sa/test/helpers.py | perform_fcruf_script | ooici/coi-services | 3 | python | def perform_fcruf_script(self, resource_iontype, resource_label, owner_service, actual_obj=None, extra_fn=None):
'\n run through find, create, read, update, and find ops on a basic resource\n\n NO DELETE in here.\n\n @param resource_iontype something like RT.PlatformModel\n @param resource_label something like platform_model\n @param owner_service a service client instance like InstrumentManagementServiceClient\n @param actual_obj use this IonObject instead of a generic object for testing\n @param extra_fn a function to run after the script, taking the new resource id as input\n @return generic_id, the resource_id of the generic resource that was created\n '
some_service = DotDict()
def fill(svc, method):
'\n make a "shortcut service" for testing crud ops.\n @param svc a dotdict\n @param method the method name to add\n '
realmethod = ('%s_widget' % method)
setattr(svc, realmethod, getattr(owner_service, ('%s_%s' % (method, resource_label))))
fill(some_service, 'create')
fill(some_service, 'read')
fill(some_service, 'update')
fill(some_service, 'delete')
def find_widgets():
(ret, _) = self.generic_int_helper_rr.find_resources(resource_iontype, None, None, False)
return ret
log.info('Finding %s objects', resource_label)
num_objs = len(find_widgets())
log.info('I found %d %s objects', num_objs, resource_label)
generic_obj = (actual_obj or any_old(resource_iontype))
log.info("Creating a %s with name='%s'", resource_label, generic_obj.name)
generic_id = some_service.create_widget(generic_obj)
self.assertIsNotNone(generic_id, ('%s failed its creation' % resource_iontype))
log.info("Reading %s '%s'", resource_label, generic_id)
generic_ret = some_service.read_widget(generic_id)
log.info('Verifying equality of stored and retrieved object')
self.assertEqual(generic_obj.name, generic_ret.name)
self.assertEqual(generic_obj.description, generic_ret.description)
log.info("Updating %s '%s'", resource_label, generic_id)
generic_newname = ('%s updated' % generic_ret.name)
generic_ret.name = generic_newname
some_service.update_widget(generic_ret)
log.info("Reading %s '%s' to verify update", resource_iontype, generic_id)
generic_ret = some_service.read_widget(generic_id)
self.assertEqual(generic_newname, generic_ret.name)
self.assertEqual(generic_obj.description, generic_ret.description)
log.info("Finding %s objects... checking that there's a new one", resource_iontype)
num_objs2 = len(find_widgets())
log.info('There were %s and now there are %s', num_objs, num_objs2)
self.assertTrue((num_objs2 > num_objs))
if (not (extra_fn is None)):
log.info(("Running extra_fn on generic resource '%s'" % generic_id))
extra_fn(generic_id)
log.info("Returning %s with id '%s'", resource_iontype, generic_id)
return generic_id | def perform_fcruf_script(self, resource_iontype, resource_label, owner_service, actual_obj=None, extra_fn=None):
'\n run through find, create, read, update, and find ops on a basic resource\n\n NO DELETE in here.\n\n @param resource_iontype something like RT.PlatformModel\n @param resource_label something like platform_model\n @param owner_service a service client instance like InstrumentManagementServiceClient\n @param actual_obj use this IonObject instead of a generic object for testing\n @param extra_fn a function to run after the script, taking the new resource id as input\n @return generic_id, the resource_id of the generic resource that was created\n '
some_service = DotDict()
def fill(svc, method):
'\n make a "shortcut service" for testing crud ops.\n @param svc a dotdict\n @param method the method name to add\n '
realmethod = ('%s_widget' % method)
setattr(svc, realmethod, getattr(owner_service, ('%s_%s' % (method, resource_label))))
fill(some_service, 'create')
fill(some_service, 'read')
fill(some_service, 'update')
fill(some_service, 'delete')
def find_widgets():
(ret, _) = self.generic_int_helper_rr.find_resources(resource_iontype, None, None, False)
return ret
log.info('Finding %s objects', resource_label)
num_objs = len(find_widgets())
log.info('I found %d %s objects', num_objs, resource_label)
generic_obj = (actual_obj or any_old(resource_iontype))
log.info("Creating a %s with name='%s'", resource_label, generic_obj.name)
generic_id = some_service.create_widget(generic_obj)
self.assertIsNotNone(generic_id, ('%s failed its creation' % resource_iontype))
log.info("Reading %s '%s'", resource_label, generic_id)
generic_ret = some_service.read_widget(generic_id)
log.info('Verifying equality of stored and retrieved object')
self.assertEqual(generic_obj.name, generic_ret.name)
self.assertEqual(generic_obj.description, generic_ret.description)
log.info("Updating %s '%s'", resource_label, generic_id)
generic_newname = ('%s updated' % generic_ret.name)
generic_ret.name = generic_newname
some_service.update_widget(generic_ret)
log.info("Reading %s '%s' to verify update", resource_iontype, generic_id)
generic_ret = some_service.read_widget(generic_id)
self.assertEqual(generic_newname, generic_ret.name)
self.assertEqual(generic_obj.description, generic_ret.description)
log.info("Finding %s objects... checking that there's a new one", resource_iontype)
num_objs2 = len(find_widgets())
log.info('There were %s and now there are %s', num_objs, num_objs2)
self.assertTrue((num_objs2 > num_objs))
if (not (extra_fn is None)):
log.info(("Running extra_fn on generic resource '%s'" % generic_id))
extra_fn(generic_id)
log.info("Returning %s with id '%s'", resource_iontype, generic_id)
return generic_id<|docstring|>run through find, create, read, update, and find ops on a basic resource
NO DELETE in here.
@param resource_iontype something like RT.PlatformModel
@param resource_label something like platform_model
@param owner_service a service client instance like InstrumentManagementServiceClient
@param actual_obj use this IonObject instead of a generic object for testing
@param extra_fn a function to run after the script, taking the new resource id as input
@return generic_id, the resource_id of the generic resource that was created<|endoftext|> |
de688daf9990d19a854fc8f4eb7db1d5f016abcb68a24fa7b886db84f16bbabd | def add_new_method(name, docstring, newmethod):
'\n dynamically add a new method to the tester class\n @param name the name of the new method\n @param docstring a description of the test\n @newmethod the function itself\n '
newmethod.__name__ = name
newmethod.__doc__ = docstring
setattr(self.tester_class, newmethod.__name__, newmethod)
added_methods[name] = True | dynamically add a new method to the tester class
@param name the name of the new method
@param docstring a description of the test
@newmethod the function itself | ion/services/sa/test/helpers.py | add_new_method | ooici/coi-services | 3 | python | def add_new_method(name, docstring, newmethod):
'\n dynamically add a new method to the tester class\n @param name the name of the new method\n @param docstring a description of the test\n @newmethod the function itself\n '
newmethod.__name__ = name
newmethod.__doc__ = docstring
setattr(self.tester_class, newmethod.__name__, newmethod)
added_methods[name] = True | def add_new_method(name, docstring, newmethod):
'\n dynamically add a new method to the tester class\n @param name the name of the new method\n @param docstring a description of the test\n @newmethod the function itself\n '
newmethod.__name__ = name
newmethod.__doc__ = docstring
setattr(self.tester_class, newmethod.__name__, newmethod)
added_methods[name] = True<|docstring|>dynamically add a new method to the tester class
@param name the name of the new method
@param docstring a description of the test
@newmethod the function itself<|endoftext|> |
5741912c334761ac22fd21cb4b858a1faca068a9ae2b6173b18d07a09907c7c5 | def add_test_method(name, docstring, newmethod):
'\n dynamically add a test method to the tester class\n @param name the name of the test function (minus the "test_" part)\n @param docstring a description of the test\n @newmethod the function itself\n '
add_new_method(('test_%s' % name), docstring, newmethod) | dynamically add a test method to the tester class
@param name the name of the test function (minus the "test_" part)
@param docstring a description of the test
@newmethod the function itself | ion/services/sa/test/helpers.py | add_test_method | ooici/coi-services | 3 | python | def add_test_method(name, docstring, newmethod):
'\n dynamically add a test method to the tester class\n @param name the name of the test function (minus the "test_" part)\n @param docstring a description of the test\n @newmethod the function itself\n '
add_new_method(('test_%s' % name), docstring, newmethod) | def add_test_method(name, docstring, newmethod):
'\n dynamically add a test method to the tester class\n @param name the name of the test function (minus the "test_" part)\n @param docstring a description of the test\n @newmethod the function itself\n '
add_new_method(('test_%s' % name), docstring, newmethod)<|docstring|>dynamically add a test method to the tester class
@param name the name of the test function (minus the "test_" part)
@param docstring a description of the test
@newmethod the function itself<|endoftext|> |
49303325b2bb3771684b2d7882fb21cfc7b199aa9c409f7c3f4f48f4afba163e | def make_name(name):
'\n make a good name for a test from the resource name and an md5 of extra params\n @param name the base string for the name\n '
assert self.sample_resource_md5
return ('%s%s' % (name, self.sample_resource_md5)) | make a good name for a test from the resource name and an md5 of extra params
@param name the base string for the name | ion/services/sa/test/helpers.py | make_name | ooici/coi-services | 3 | python | def make_name(name):
'\n make a good name for a test from the resource name and an md5 of extra params\n @param name the base string for the name\n '
assert self.sample_resource_md5
return ('%s%s' % (name, self.sample_resource_md5)) | def make_name(name):
'\n make a good name for a test from the resource name and an md5 of extra params\n @param name the base string for the name\n '
assert self.sample_resource_md5
return ('%s%s' % (name, self.sample_resource_md5))<|docstring|>make a good name for a test from the resource name and an md5 of extra params
@param name the base string for the name<|endoftext|> |
e9d36121b7a70b7c999c4bb14e0525f1aab59b4a3b5b991b8b5a0f130716fc65 | def make_doc(doc):
'\n make a good doc string for a test from by including the extra params\n @param doc the base string for the descripton\n '
return ('%s %s' % (doc, self.sample_resource_extras)) | make a good doc string for a test from by including the extra params
@param doc the base string for the descripton | ion/services/sa/test/helpers.py | make_doc | ooici/coi-services | 3 | python | def make_doc(doc):
'\n make a good doc string for a test from by including the extra params\n @param doc the base string for the descripton\n '
return ('%s %s' % (doc, self.sample_resource_extras)) | def make_doc(doc):
'\n make a good doc string for a test from by including the extra params\n @param doc the base string for the descripton\n '
return ('%s %s' % (doc, self.sample_resource_extras))<|docstring|>make a good doc string for a test from by including the extra params
@param doc the base string for the descripton<|endoftext|> |
62be43fb9c84f9e2a062f8b2be2a4cbb225b0737b2d53de030c5e11e000573e0 | def gen_svc_lookup():
'\n put a new method in the tester class to find the instance of the service being tested\n\n the prefix is "_utg_": unit_test_generator\n '
def getsvc_fun(self):
'\n self is an instance of the tester class\n '
if (not hasattr(self, '_utg_service_obj')):
service_itself = getattr(self, find_cv_func(self, service_type))
self._utg_service_obj = service_itself
assert self._utg_service_obj
return self._utg_service_obj
def getcrudmethod_fun(self, rsrc_lbl, method_str):
'\n self is an instance of the tester class\n method_str is a crud method name like "create" that will become "create_resource_label"\n '
svc = self._utg_getservice()
methodname = ('%s_%s' % (method_str, rsrc_lbl))
if (not hasattr(svc, methodname)):
raise SkipTest('CRUD method does not exist, skipping')
return getattr(svc, methodname)
if (not hasattr(self.tester_class, '_utg_getservice')):
add_new_method('_utg_getservice', 'Finds instance of service under test', getsvc_fun)
if (not hasattr(self.tester_class, '_utg_getcrudmethod')):
add_new_method('_utg_getcrudmethod', 'Finds instance of crud method in service', getcrudmethod_fun) | put a new method in the tester class to find the instance of the service being tested
the prefix is "_utg_": unit_test_generator | ion/services/sa/test/helpers.py | gen_svc_lookup | ooici/coi-services | 3 | python | def gen_svc_lookup():
'\n put a new method in the tester class to find the instance of the service being tested\n\n the prefix is "_utg_": unit_test_generator\n '
def getsvc_fun(self):
'\n self is an instance of the tester class\n '
if (not hasattr(self, '_utg_service_obj')):
service_itself = getattr(self, find_cv_func(self, service_type))
self._utg_service_obj = service_itself
assert self._utg_service_obj
return self._utg_service_obj
def getcrudmethod_fun(self, rsrc_lbl, method_str):
'\n self is an instance of the tester class\n method_str is a crud method name like "create" that will become "create_resource_label"\n '
svc = self._utg_getservice()
methodname = ('%s_%s' % (method_str, rsrc_lbl))
if (not hasattr(svc, methodname)):
raise SkipTest('CRUD method does not exist, skipping')
return getattr(svc, methodname)
if (not hasattr(self.tester_class, '_utg_getservice')):
add_new_method('_utg_getservice', 'Finds instance of service under test', getsvc_fun)
if (not hasattr(self.tester_class, '_utg_getcrudmethod')):
add_new_method('_utg_getcrudmethod', 'Finds instance of crud method in service', getcrudmethod_fun) | def gen_svc_lookup():
'\n put a new method in the tester class to find the instance of the service being tested\n\n the prefix is "_utg_": unit_test_generator\n '
def getsvc_fun(self):
'\n self is an instance of the tester class\n '
if (not hasattr(self, '_utg_service_obj')):
service_itself = getattr(self, find_cv_func(self, service_type))
self._utg_service_obj = service_itself
assert self._utg_service_obj
return self._utg_service_obj
def getcrudmethod_fun(self, rsrc_lbl, method_str):
'\n self is an instance of the tester class\n method_str is a crud method name like "create" that will become "create_resource_label"\n '
svc = self._utg_getservice()
methodname = ('%s_%s' % (method_str, rsrc_lbl))
if (not hasattr(svc, methodname)):
raise SkipTest('CRUD method does not exist, skipping')
return getattr(svc, methodname)
if (not hasattr(self.tester_class, '_utg_getservice')):
add_new_method('_utg_getservice', 'Finds instance of service under test', getsvc_fun)
if (not hasattr(self.tester_class, '_utg_getcrudmethod')):
add_new_method('_utg_getcrudmethod', 'Finds instance of crud method in service', getcrudmethod_fun)<|docstring|>put a new method in the tester class to find the instance of the service being tested
the prefix is "_utg_": unit_test_generator<|endoftext|> |
ff1f4e68926cb1d72da646c1e0a8219823e54db7fe17b79c214a4607fd263b4f | def test_create_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_create_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
good_sample_resource = sample_resource()
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
sample_resource_id = testfun(good_sample_resource)
svc.clients.resource_registry.create.assert_called_once_with(good_sample_resource)
self.assertEqual(sample_resource_id, '111') | self is an instance of the tester class | ion/services/sa/test/helpers.py | test_create_fun | ooici/coi-services | 3 | python | def test_create_fun(self):
'\n \n '
log.debug('test_create_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
good_sample_resource = sample_resource()
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
sample_resource_id = testfun(good_sample_resource)
svc.clients.resource_registry.create.assert_called_once_with(good_sample_resource)
self.assertEqual(sample_resource_id, '111') | def test_create_fun(self):
'\n \n '
log.debug('test_create_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
good_sample_resource = sample_resource()
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
sample_resource_id = testfun(good_sample_resource)
svc.clients.resource_registry.create.assert_called_once_with(good_sample_resource)
self.assertEqual(sample_resource_id, '111')<|docstring|>self is an instance of the tester class<|endoftext|> |
5262ca6c548858ed917083acfd71c7fffe7813f1b933991a0ad16dbabdca748b | def test_create_bad_wrongtype_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_create_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = IonObject(RT.Resource, name='Generic Resource')
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
self.assertRaisesRegexp(BadRequest, 'type', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count) | self is an instance of the tester class | ion/services/sa/test/helpers.py | test_create_bad_wrongtype_fun | ooici/coi-services | 3 | python | def test_create_bad_wrongtype_fun(self):
'\n \n '
log.debug('test_create_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = IonObject(RT.Resource, name='Generic Resource')
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
self.assertRaisesRegexp(BadRequest, 'type', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count) | def test_create_bad_wrongtype_fun(self):
'\n \n '
log.debug('test_create_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = IonObject(RT.Resource, name='Generic Resource')
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
self.assertRaisesRegexp(BadRequest, 'type', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count)<|docstring|>self is an instance of the tester class<|endoftext|> |
e6d0bbace454a11cf61173fd103379c0f73c1bec1a4486a4c0f76ba1eabf28f4 | def test_create_bad_noname_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_create_bad_noname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = sample_resource()
delattr(bad_sample_resource, 'name')
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
self.assertRaisesRegexp(BadRequest, 'name', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count) | self is an instance of the tester class | ion/services/sa/test/helpers.py | test_create_bad_noname_fun | ooici/coi-services | 3 | python | def test_create_bad_noname_fun(self):
'\n \n '
log.debug('test_create_bad_noname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = sample_resource()
delattr(bad_sample_resource, 'name')
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
self.assertRaisesRegexp(BadRequest, 'name', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count) | def test_create_bad_noname_fun(self):
'\n \n '
log.debug('test_create_bad_noname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = sample_resource()
delattr(bad_sample_resource, 'name')
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
self.assertRaisesRegexp(BadRequest, 'name', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count)<|docstring|>self is an instance of the tester class<|endoftext|> |
9873ddeda0f6524bd13ee2be96fa081d603dce10752cbac0281e229f724b0a8a | def test_create_bad_dupname_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_create_bad_dupname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = sample_resource()
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([0], [0])
self.assertRaisesRegexp(BadRequest, 'uplicate', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count) | self is an instance of the tester class | ion/services/sa/test/helpers.py | test_create_bad_dupname_fun | ooici/coi-services | 3 | python | def test_create_bad_dupname_fun(self):
'\n \n '
log.debug('test_create_bad_dupname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = sample_resource()
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([0], [0])
self.assertRaisesRegexp(BadRequest, 'uplicate', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count) | def test_create_bad_dupname_fun(self):
'\n \n '
log.debug('test_create_bad_dupname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'create')
bad_sample_resource = sample_resource()
if all_in_one:
svc.clients.resource_registry.create.reset_mock()
svc.clients.resource_registry.create.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([0], [0])
self.assertRaisesRegexp(BadRequest, 'uplicate', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.create.call_count)<|docstring|>self is an instance of the tester class<|endoftext|> |
88466be17e9dce65090b87fb3f39d52d85f0e1fe089747b1a5c26916e87856c3 | def test_read_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_read_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'read')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
response = testfun('111')
svc.clients.resource_registry.read.assert_called_once_with('111', '')
self.assertEqual(response, myret)
if all_in_one:
svc.clients.resource_registry.reset_mock() | self is an instance of the tester class | ion/services/sa/test/helpers.py | test_read_fun | ooici/coi-services | 3 | python | def test_read_fun(self):
'\n \n '
log.debug('test_read_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'read')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
response = testfun('111')
svc.clients.resource_registry.read.assert_called_once_with('111', )
self.assertEqual(response, myret)
if all_in_one:
svc.clients.resource_registry.reset_mock() | def test_read_fun(self):
'\n \n '
log.debug('test_read_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'read')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
response = testfun('111')
svc.clients.resource_registry.read.assert_called_once_with('111', )
self.assertEqual(response, myret)
if all_in_one:
svc.clients.resource_registry.reset_mock()<|docstring|>self is an instance of the tester class<|endoftext|> |
18406635d76d079ab760b89ffe3bf9f7f97eeb87540b869fb9ab9cd0186f1ae2 | def test_read_bad_wrongtype_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_read_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'read')
myret = IonObject(RT.Resource, name='Generic Resource')
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
self.assertEqual(0, svc.clients.resource_registry.read.call_count)
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
svc.clients.resource_registry.read.assert_called_once_with('111', '') | self is an instance of the tester class | ion/services/sa/test/helpers.py | test_read_bad_wrongtype_fun | ooici/coi-services | 3 | python | def test_read_bad_wrongtype_fun(self):
'\n \n '
log.debug('test_read_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'read')
myret = IonObject(RT.Resource, name='Generic Resource')
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
self.assertEqual(0, svc.clients.resource_registry.read.call_count)
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
svc.clients.resource_registry.read.assert_called_once_with('111', ) | def test_read_bad_wrongtype_fun(self):
'\n \n '
log.debug('test_read_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'read')
myret = IonObject(RT.Resource, name='Generic Resource')
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
self.assertEqual(0, svc.clients.resource_registry.read.call_count)
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
svc.clients.resource_registry.read.assert_called_once_with('111', )<|docstring|>self is an instance of the tester class<|endoftext|> |
4c323ac5ccefbccff58f8fca2d064e8dc7f654342daeeb8f7738a4b22d962b18 | def test_update_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_update_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
good_sample_resource = sample_resource()
setattr(good_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
svc.clients.resource_registry.update.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
testfun(good_sample_resource)
svc.clients.resource_registry.update.assert_called_once_with(good_sample_resource) | self is an instance of the tester class | ion/services/sa/test/helpers.py | test_update_fun | ooici/coi-services | 3 | python | def test_update_fun(self):
'\n \n '
log.debug('test_update_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
good_sample_resource = sample_resource()
setattr(good_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
svc.clients.resource_registry.update.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
testfun(good_sample_resource)
svc.clients.resource_registry.update.assert_called_once_with(good_sample_resource) | def test_update_fun(self):
'\n \n '
log.debug('test_update_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
good_sample_resource = sample_resource()
setattr(good_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
svc.clients.resource_registry.update.return_value = ('111', 'bla')
svc.clients.resource_registry.find_resources.return_value = ([], [])
testfun(good_sample_resource)
svc.clients.resource_registry.update.assert_called_once_with(good_sample_resource)<|docstring|>self is an instance of the tester class<|endoftext|> |
d744098e599b2720a03fbda453392592b25f22f5a8ade134e563b51233bb74f2 | def test_update_bad_dupname_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_update_bad_dupname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
bad_sample_resource = sample_resource()
setattr(bad_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
svc.clients.resource_registry.find_resources.return_value = ([0], [0])
self.assertRaisesRegexp(BadRequest, 'uplicate', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.update.call_count) | self is an instance of the tester class | ion/services/sa/test/helpers.py | test_update_bad_dupname_fun | ooici/coi-services | 3 | python | def test_update_bad_dupname_fun(self):
'\n \n '
log.debug('test_update_bad_dupname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
bad_sample_resource = sample_resource()
setattr(bad_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
svc.clients.resource_registry.find_resources.return_value = ([0], [0])
self.assertRaisesRegexp(BadRequest, 'uplicate', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.update.call_count) | def test_update_bad_dupname_fun(self):
'\n \n '
log.debug('test_update_bad_dupname_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
bad_sample_resource = sample_resource()
setattr(bad_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
svc.clients.resource_registry.find_resources.return_value = ([0], [0])
self.assertRaisesRegexp(BadRequest, 'uplicate', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.update.call_count)<|docstring|>self is an instance of the tester class<|endoftext|> |
641a0eeb031669e3c5ad6629eb7c026a7cbc2865cdabaf2405d572c8652dfa94 | def test_update_bad_wrongtype_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_update_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
bad_sample_resource = IonObject(RT.Resource, name='Generic Name')
setattr(bad_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
self.assertRaisesRegexp(BadRequest, 'type', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.update.call_count) | self is an instance of the tester class | ion/services/sa/test/helpers.py | test_update_bad_wrongtype_fun | ooici/coi-services | 3 | python | def test_update_bad_wrongtype_fun(self):
'\n \n '
log.debug('test_update_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
bad_sample_resource = IonObject(RT.Resource, name='Generic Name')
setattr(bad_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
self.assertRaisesRegexp(BadRequest, 'type', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.update.call_count) | def test_update_bad_wrongtype_fun(self):
'\n \n '
log.debug('test_update_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'update')
bad_sample_resource = IonObject(RT.Resource, name='Generic Name')
setattr(bad_sample_resource, '_id', '111')
if all_in_one:
svc.clients.resource_registry.update.reset_mock()
self.assertRaisesRegexp(BadRequest, 'type', testfun, bad_sample_resource)
self.assertEqual(0, svc.clients.resource_registry.update.call_count)<|docstring|>self is an instance of the tester class<|endoftext|> |
bcea432a8b485c7e4784de7b010143ee9aadec9860b8c3c277a3add889875b0c | def test_delete_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_delete_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'delete')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
svc.clients.resource_registry.read.return_value = myret
svc.clients.resource_registry.delete.return_value = None
svc.clients.resource_registry.lcs_delete.return_value = None
try:
testfun('111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
svc.clients.resource_registry.reset_mock()
return
else:
raise SkipTest('Must test this with INT test')
svc.clients.resource_registry.lcs_delete.assert_called_once_with('111')
self.assertEqual(0, svc.clients.resource_registry.delete.call_count) | self is an instance of the tester class | ion/services/sa/test/helpers.py | test_delete_fun | ooici/coi-services | 3 | python | def test_delete_fun(self):
'\n \n '
log.debug('test_delete_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'delete')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
svc.clients.resource_registry.read.return_value = myret
svc.clients.resource_registry.delete.return_value = None
svc.clients.resource_registry.lcs_delete.return_value = None
try:
testfun('111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
svc.clients.resource_registry.reset_mock()
return
else:
raise SkipTest('Must test this with INT test')
svc.clients.resource_registry.lcs_delete.assert_called_once_with('111')
self.assertEqual(0, svc.clients.resource_registry.delete.call_count) | def test_delete_fun(self):
'\n \n '
log.debug('test_delete_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'delete')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
svc.clients.resource_registry.read.return_value = myret
svc.clients.resource_registry.delete.return_value = None
svc.clients.resource_registry.lcs_delete.return_value = None
try:
testfun('111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
svc.clients.resource_registry.reset_mock()
return
else:
raise SkipTest('Must test this with INT test')
svc.clients.resource_registry.lcs_delete.assert_called_once_with('111')
self.assertEqual(0, svc.clients.resource_registry.delete.call_count)<|docstring|>self is an instance of the tester class<|endoftext|> |
2599c6055f8aaaeb8940a6e1888b59487863fb626933372e73c453677285eb0f | def test_delete_bad_wrongtype_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_delete_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'delete')
myret = IonObject(RT.Resource, name='Generic Name')
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
try:
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
self.assertEqual(0, svc.clients.resource_registry.lcs_delete.call_count)
self.assertEqual(0, svc.clients.resource_registry.delete.call_count) | self is an instance of the tester class | ion/services/sa/test/helpers.py | test_delete_bad_wrongtype_fun | ooici/coi-services | 3 | python | def test_delete_bad_wrongtype_fun(self):
'\n \n '
log.debug('test_delete_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'delete')
myret = IonObject(RT.Resource, name='Generic Name')
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
try:
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
self.assertEqual(0, svc.clients.resource_registry.lcs_delete.call_count)
self.assertEqual(0, svc.clients.resource_registry.delete.call_count) | def test_delete_bad_wrongtype_fun(self):
'\n \n '
log.debug('test_delete_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'delete')
myret = IonObject(RT.Resource, name='Generic Name')
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.read.return_value = myret
try:
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
self.assertEqual(0, svc.clients.resource_registry.lcs_delete.call_count)
self.assertEqual(0, svc.clients.resource_registry.delete.call_count)<|docstring|>self is an instance of the tester class<|endoftext|> |
df2a173e217bb936a2f877782f247f8de6d6210bc4a6ce277ed2ef4f6724a77e | def test_force_delete_fun(self):
'\n self is an instance of the tester class\n '
log.debug('test_force_delete_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'force_delete')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
svc.clients.resource_registry.read.return_value = myret
svc.clients.resource_registry.delete.return_value = None
svc.clients.resource_registry.find_resources.return_value = None
svc.clients.resource_registry.find_objects.return_value = ([], [])
svc.clients.resource_registry.find_subjects.return_value = ([], [])
try:
testfun('111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
svc.clients.resource_registry.delete.assert_called_once_with('111') | self is an instance of the tester class | ion/services/sa/test/helpers.py | test_force_delete_fun | ooici/coi-services | 3 | python | def test_force_delete_fun(self):
'\n \n '
log.debug('test_force_delete_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'force_delete')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
svc.clients.resource_registry.read.return_value = myret
svc.clients.resource_registry.delete.return_value = None
svc.clients.resource_registry.find_resources.return_value = None
svc.clients.resource_registry.find_objects.return_value = ([], [])
svc.clients.resource_registry.find_subjects.return_value = ([], [])
try:
testfun('111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
svc.clients.resource_registry.delete.assert_called_once_with('111') | def test_force_delete_fun(self):
'\n \n '
log.debug('test_force_delete_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'force_delete')
myret = sample_resource()
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
svc.clients.resource_registry.read.return_value = myret
svc.clients.resource_registry.delete.return_value = None
svc.clients.resource_registry.find_resources.return_value = None
svc.clients.resource_registry.find_objects.return_value = ([], [])
svc.clients.resource_registry.find_subjects.return_value = ([], [])
try:
testfun('111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
svc.clients.resource_registry.delete.assert_called_once_with('111')<|docstring|>self is an instance of the tester class<|endoftext|> |
37a4e77357086ffc8d864dfba9adbc7bbee92cf8cb6fe0751945624ee0216232 | def test_force_delete_bad_wrongtype_fun(self):
'\n self is an inst ance of the tester class\n '
log.debug('test_force_delete_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'force_delete')
myret = IonObject(RT.Resource, name='Generic Name')
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.find_objects.return_value = ([], [])
svc.clients.resource_registry.find_subjects.return_value = ([], [])
svc.clients.resource_registry.read.return_value = myret
try:
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
self.assertEqual(0, svc.clients.resource_registry.lcs_delete.call_count)
self.assertEqual(0, svc.clients.resource_registry.delete.call_count) | self is an inst ance of the tester class | ion/services/sa/test/helpers.py | test_force_delete_bad_wrongtype_fun | ooici/coi-services | 3 | python | def test_force_delete_bad_wrongtype_fun(self):
'\n \n '
log.debug('test_force_delete_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'force_delete')
myret = IonObject(RT.Resource, name='Generic Name')
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.find_objects.return_value = ([], [])
svc.clients.resource_registry.find_subjects.return_value = ([], [])
svc.clients.resource_registry.read.return_value = myret
try:
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
self.assertEqual(0, svc.clients.resource_registry.lcs_delete.call_count)
self.assertEqual(0, svc.clients.resource_registry.delete.call_count) | def test_force_delete_bad_wrongtype_fun(self):
'\n \n '
log.debug('test_force_delete_bad_wrongtype_fun')
svc = self._utg_getservice()
testfun = self._utg_getcrudmethod(resource_label, 'force_delete')
myret = IonObject(RT.Resource, name='Generic Name')
if all_in_one:
svc.clients.resource_registry.delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.lcs_delete.reset_mock()
if all_in_one:
svc.clients.resource_registry.read.reset_mock()
svc.clients.resource_registry.find_objects.return_value = ([], [])
svc.clients.resource_registry.find_subjects.return_value = ([], [])
svc.clients.resource_registry.read.return_value = myret
try:
self.assertRaisesRegexp(BadRequest, 'type', testfun, '111')
except TypeError as te:
if ("'Mock' object is not iterable" != te.message):
raise te
elif all_in_one:
return
else:
raise SkipTest('Must test this with INT test')
self.assertEqual(0, svc.clients.resource_registry.lcs_delete.call_count)
self.assertEqual(0, svc.clients.resource_registry.delete.call_count)<|docstring|>self is an inst ance of the tester class<|endoftext|> |
83f6a38da227e6785541243f1cb81e2068de5b6f2f4adfbce815ba9646791d70 | def gen_test_create():
'\n generate the function to test the create\n '
name = make_name(('%s_create' % resource_label))
doc = make_doc(('Creation of a new %s resource' % resource_iontype))
add_test_method(name, doc, test_create_fun) | generate the function to test the create | ion/services/sa/test/helpers.py | gen_test_create | ooici/coi-services | 3 | python | def gen_test_create():
'\n \n '
name = make_name(('%s_create' % resource_label))
doc = make_doc(('Creation of a new %s resource' % resource_iontype))
add_test_method(name, doc, test_create_fun) | def gen_test_create():
'\n \n '
name = make_name(('%s_create' % resource_label))
doc = make_doc(('Creation of a new %s resource' % resource_iontype))
add_test_method(name, doc, test_create_fun)<|docstring|>generate the function to test the create<|endoftext|> |
9c063df3ff05b9a4a4ce0929bb1d69a9bafac207a8314abdd2aa6d0e75b970cd | def gen_test_create_bad_wrongtype():
'\n generate the function to test the create for the wrong resource type\n '
name = make_name(('%s_create_bad_wrongtype' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (wrong type)' % resource_iontype))
add_test_method(name, doc, test_create_bad_wrongtype_fun) | generate the function to test the create for the wrong resource type | ion/services/sa/test/helpers.py | gen_test_create_bad_wrongtype | ooici/coi-services | 3 | python | def gen_test_create_bad_wrongtype():
'\n \n '
name = make_name(('%s_create_bad_wrongtype' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (wrong type)' % resource_iontype))
add_test_method(name, doc, test_create_bad_wrongtype_fun) | def gen_test_create_bad_wrongtype():
'\n \n '
name = make_name(('%s_create_bad_wrongtype' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (wrong type)' % resource_iontype))
add_test_method(name, doc, test_create_bad_wrongtype_fun)<|docstring|>generate the function to test the create for the wrong resource type<|endoftext|> |
a4362f3ac8825861574e5936c66465519a5d2a656b227cce0099885093cdf819 | def gen_test_create_bad_noname():
'\n generate the function to test the create in a bad case\n '
name = make_name(('%s_create_bad_noname' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (no name)' % resource_iontype))
add_test_method(name, doc, test_create_bad_noname_fun) | generate the function to test the create in a bad case | ion/services/sa/test/helpers.py | gen_test_create_bad_noname | ooici/coi-services | 3 | python | def gen_test_create_bad_noname():
'\n \n '
name = make_name(('%s_create_bad_noname' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (no name)' % resource_iontype))
add_test_method(name, doc, test_create_bad_noname_fun) | def gen_test_create_bad_noname():
'\n \n '
name = make_name(('%s_create_bad_noname' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (no name)' % resource_iontype))
add_test_method(name, doc, test_create_bad_noname_fun)<|docstring|>generate the function to test the create in a bad case<|endoftext|> |
b01fafa4949d8dc2073d4fd8428684c435a63ca75b13fc39c5b0560ff5a86988 | def gen_test_create_bad_dupname():
'\n generate the function to test the create in a bad case where the name already exists\n '
name = make_name(('%s_create_bad_dupname' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (duplicate name)' % resource_iontype))
add_test_method(name, doc, test_create_bad_dupname_fun) | generate the function to test the create in a bad case where the name already exists | ion/services/sa/test/helpers.py | gen_test_create_bad_dupname | ooici/coi-services | 3 | python | def gen_test_create_bad_dupname():
'\n \n '
name = make_name(('%s_create_bad_dupname' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (duplicate name)' % resource_iontype))
add_test_method(name, doc, test_create_bad_dupname_fun) | def gen_test_create_bad_dupname():
'\n \n '
name = make_name(('%s_create_bad_dupname' % resource_label))
doc = make_doc(('Creation of a (bad) new %s resource (duplicate name)' % resource_iontype))
add_test_method(name, doc, test_create_bad_dupname_fun)<|docstring|>generate the function to test the create in a bad case where the name already exists<|endoftext|> |
8cb614fb164b67a318261da6e7405047526bbdd73ca482e7dcd2c420ffeefdab | def gen_test_read():
'\n generate the function to test the read\n '
name = make_name(('%s_read' % resource_label))
doc = make_doc(('Reading a %s resource' % resource_iontype))
add_test_method(name, doc, test_read_fun) | generate the function to test the read | ion/services/sa/test/helpers.py | gen_test_read | ooici/coi-services | 3 | python | def gen_test_read():
'\n \n '
name = make_name(('%s_read' % resource_label))
doc = make_doc(('Reading a %s resource' % resource_iontype))
add_test_method(name, doc, test_read_fun) | def gen_test_read():
'\n \n '
name = make_name(('%s_read' % resource_label))
doc = make_doc(('Reading a %s resource' % resource_iontype))
add_test_method(name, doc, test_read_fun)<|docstring|>generate the function to test the read<|endoftext|> |
c5ff18124aff7dc713fa5c8324ff4eb63a1a983f478c5e61b59fc06c4d83b168 | def gen_test_read_bad_wrongtype():
'\n generate the function to test the read with bad type\n '
name = make_name(('%s_read_bad_wrongtype' % resource_label))
doc = make_doc(('Reading a %s resource but having it come back as wrong type' % resource_iontype))
add_test_method(name, doc, test_read_bad_wrongtype_fun) | generate the function to test the read with bad type | ion/services/sa/test/helpers.py | gen_test_read_bad_wrongtype | ooici/coi-services | 3 | python | def gen_test_read_bad_wrongtype():
'\n \n '
name = make_name(('%s_read_bad_wrongtype' % resource_label))
doc = make_doc(('Reading a %s resource but having it come back as wrong type' % resource_iontype))
add_test_method(name, doc, test_read_bad_wrongtype_fun) | def gen_test_read_bad_wrongtype():
'\n \n '
name = make_name(('%s_read_bad_wrongtype' % resource_label))
doc = make_doc(('Reading a %s resource but having it come back as wrong type' % resource_iontype))
add_test_method(name, doc, test_read_bad_wrongtype_fun)<|docstring|>generate the function to test the read with bad type<|endoftext|> |
3bd772e52c9acf19feca55f0742667919178306888276bd98c3a7904e323705b | def gen_test_update():
'\n generate the function to test the update\n '
name = make_name(('%s_update' % resource_label))
doc = make_doc(('Updating a %s resource' % resource_iontype))
add_test_method(name, doc, test_update_fun) | generate the function to test the update | ion/services/sa/test/helpers.py | gen_test_update | ooici/coi-services | 3 | python | def gen_test_update():
'\n \n '
name = make_name(('%s_update' % resource_label))
doc = make_doc(('Updating a %s resource' % resource_iontype))
add_test_method(name, doc, test_update_fun) | def gen_test_update():
'\n \n '
name = make_name(('%s_update' % resource_label))
doc = make_doc(('Updating a %s resource' % resource_iontype))
add_test_method(name, doc, test_update_fun)<|docstring|>generate the function to test the update<|endoftext|> |
086fd7ba82023a0e0f9e72aa98f8361498acc99c82b239b674d17183c3e866b9 | def gen_test_update_bad_wrongtype():
'\n generate the function to test the update with wrong type\n '
name = make_name(('%s_update_bad_wrongtype' % resource_label))
doc = make_doc(('Updating a %s resource with the wrong type' % resource_iontype))
add_test_method(name, doc, test_update_bad_wrongtype_fun) | generate the function to test the update with wrong type | ion/services/sa/test/helpers.py | gen_test_update_bad_wrongtype | ooici/coi-services | 3 | python | def gen_test_update_bad_wrongtype():
'\n \n '
name = make_name(('%s_update_bad_wrongtype' % resource_label))
doc = make_doc(('Updating a %s resource with the wrong type' % resource_iontype))
add_test_method(name, doc, test_update_bad_wrongtype_fun) | def gen_test_update_bad_wrongtype():
'\n \n '
name = make_name(('%s_update_bad_wrongtype' % resource_label))
doc = make_doc(('Updating a %s resource with the wrong type' % resource_iontype))
add_test_method(name, doc, test_update_bad_wrongtype_fun)<|docstring|>generate the function to test the update with wrong type<|endoftext|> |
c2648b8c89e0bc69d49abb9ad99c9ab59a142bcde037731340881c93ee5b5713 | def gen_test_update_bad_dupname():
'\n generate the function to test the update with wrong type\n '
name = make_name(('%s_update_bad_duplicate' % resource_label))
doc = make_doc(('Updating a %s resource to a duplicate name' % resource_iontype))
add_test_method(name, doc, test_update_bad_dupname_fun) | generate the function to test the update with wrong type | ion/services/sa/test/helpers.py | gen_test_update_bad_dupname | ooici/coi-services | 3 | python | def gen_test_update_bad_dupname():
'\n \n '
name = make_name(('%s_update_bad_duplicate' % resource_label))
doc = make_doc(('Updating a %s resource to a duplicate name' % resource_iontype))
add_test_method(name, doc, test_update_bad_dupname_fun) | def gen_test_update_bad_dupname():
'\n \n '
name = make_name(('%s_update_bad_duplicate' % resource_label))
doc = make_doc(('Updating a %s resource to a duplicate name' % resource_iontype))
add_test_method(name, doc, test_update_bad_dupname_fun)<|docstring|>generate the function to test the update with wrong type<|endoftext|> |
6c8ef95cee4aa527cf44988df49598b2b9ad633e81c246e22dda0c0926d44449 | def gen_test_delete():
'\n generate the function to test the delete\n '
name = make_name(('%s_delete' % resource_label))
doc = make_doc(('Deleting (retiring) a %s resource' % resource_iontype))
add_test_method(name, doc, test_delete_fun) | generate the function to test the delete | ion/services/sa/test/helpers.py | gen_test_delete | ooici/coi-services | 3 | python | def gen_test_delete():
'\n \n '
name = make_name(('%s_delete' % resource_label))
doc = make_doc(('Deleting (retiring) a %s resource' % resource_iontype))
add_test_method(name, doc, test_delete_fun) | def gen_test_delete():
'\n \n '
name = make_name(('%s_delete' % resource_label))
doc = make_doc(('Deleting (retiring) a %s resource' % resource_iontype))
add_test_method(name, doc, test_delete_fun)<|docstring|>generate the function to test the delete<|endoftext|> |
8b16d76f398b703b16942a41428e2430178ec4b23ba3ccff8f1f4b0d8c556565 | def gen_test_delete_bad_wrongtype():
'\n generate the function to test the delete with wrong type\n '
name = make_name(('%s_delete_bad_wrongtype' % resource_label))
doc = make_doc(('Deleting (retiring) a %s resource of the wrong type' % resource_iontype))
add_test_method(name, doc, test_delete_bad_wrongtype_fun) | generate the function to test the delete with wrong type | ion/services/sa/test/helpers.py | gen_test_delete_bad_wrongtype | ooici/coi-services | 3 | python | def gen_test_delete_bad_wrongtype():
'\n \n '
name = make_name(('%s_delete_bad_wrongtype' % resource_label))
doc = make_doc(('Deleting (retiring) a %s resource of the wrong type' % resource_iontype))
add_test_method(name, doc, test_delete_bad_wrongtype_fun) | def gen_test_delete_bad_wrongtype():
'\n \n '
name = make_name(('%s_delete_bad_wrongtype' % resource_label))
doc = make_doc(('Deleting (retiring) a %s resource of the wrong type' % resource_iontype))
add_test_method(name, doc, test_delete_bad_wrongtype_fun)<|docstring|>generate the function to test the delete with wrong type<|endoftext|> |
555d78223e8a480c5f6efde90975547a84b562cb2d2497d62d8a05cf548a3f3f | def gen_test_force_delete():
'\n generate the function to test the delete\n '
name = make_name(('%s_force_delete' % resource_label))
doc = make_doc(('Deleting -- destructively -- a %s resource' % resource_iontype))
add_test_method(name, doc, test_force_delete_fun) | generate the function to test the delete | ion/services/sa/test/helpers.py | gen_test_force_delete | ooici/coi-services | 3 | python | def gen_test_force_delete():
'\n \n '
name = make_name(('%s_force_delete' % resource_label))
doc = make_doc(('Deleting -- destructively -- a %s resource' % resource_iontype))
add_test_method(name, doc, test_force_delete_fun) | def gen_test_force_delete():
'\n \n '
name = make_name(('%s_force_delete' % resource_label))
doc = make_doc(('Deleting -- destructively -- a %s resource' % resource_iontype))
add_test_method(name, doc, test_force_delete_fun)<|docstring|>generate the function to test the delete<|endoftext|> |
85fb8a818eacca847ab574a86f1c225eafb744fef8544d0af047793e8c590963 | def gen_test_force_delete_bad_wrongtype():
'\n generate the function to test the delete with the wrong type\n '
name = make_name(('%s_force_delete_bad_wrongtype' % resource_label))
doc = make_doc(('Deleting -- destructively -- a %s resource of the wrong type' % resource_iontype))
add_test_method(name, doc, test_force_delete_bad_wrongtype_fun) | generate the function to test the delete with the wrong type | ion/services/sa/test/helpers.py | gen_test_force_delete_bad_wrongtype | ooici/coi-services | 3 | python | def gen_test_force_delete_bad_wrongtype():
'\n \n '
name = make_name(('%s_force_delete_bad_wrongtype' % resource_label))
doc = make_doc(('Deleting -- destructively -- a %s resource of the wrong type' % resource_iontype))
add_test_method(name, doc, test_force_delete_bad_wrongtype_fun) | def gen_test_force_delete_bad_wrongtype():
'\n \n '
name = make_name(('%s_force_delete_bad_wrongtype' % resource_label))
doc = make_doc(('Deleting -- destructively -- a %s resource of the wrong type' % resource_iontype))
add_test_method(name, doc, test_force_delete_bad_wrongtype_fun)<|docstring|>generate the function to test the delete with the wrong type<|endoftext|> |
49b8d7469d7b5b0154c51daed7599dddb872148a43fb064d6f78490aa9929f34 | def gen_test_allinone():
'\n generate the function to test EVERYTHING at once\n '
def fun(self):
'\n self is an instance of the tester class\n '
test_create_fun(self)
test_create_bad_wrongtype_fun(self)
test_create_bad_noname_fun(self)
test_read_fun(self)
test_read_bad_wrongtype_fun(self)
test_update_fun(self)
test_update_bad_wrongtype_fun(self)
test_delete_fun(self)
test_delete_bad_wrongtype_fun(self)
test_force_delete_fun(self)
test_force_delete_bad_wrongtype_fun(self)
name = make_name(('%s_allinone' % resource_label))
doc = make_doc(('Performing all CRUD tests on %s resources' % resource_iontype))
add_test_method(name, doc, fun) | generate the function to test EVERYTHING at once | ion/services/sa/test/helpers.py | gen_test_allinone | ooici/coi-services | 3 | python | def gen_test_allinone():
'\n \n '
def fun(self):
'\n self is an instance of the tester class\n '
test_create_fun(self)
test_create_bad_wrongtype_fun(self)
test_create_bad_noname_fun(self)
test_read_fun(self)
test_read_bad_wrongtype_fun(self)
test_update_fun(self)
test_update_bad_wrongtype_fun(self)
test_delete_fun(self)
test_delete_bad_wrongtype_fun(self)
test_force_delete_fun(self)
test_force_delete_bad_wrongtype_fun(self)
name = make_name(('%s_allinone' % resource_label))
doc = make_doc(('Performing all CRUD tests on %s resources' % resource_iontype))
add_test_method(name, doc, fun) | def gen_test_allinone():
'\n \n '
def fun(self):
'\n self is an instance of the tester class\n '
test_create_fun(self)
test_create_bad_wrongtype_fun(self)
test_create_bad_noname_fun(self)
test_read_fun(self)
test_read_bad_wrongtype_fun(self)
test_update_fun(self)
test_update_bad_wrongtype_fun(self)
test_delete_fun(self)
test_delete_bad_wrongtype_fun(self)
test_force_delete_fun(self)
test_force_delete_bad_wrongtype_fun(self)
name = make_name(('%s_allinone' % resource_label))
doc = make_doc(('Performing all CRUD tests on %s resources' % resource_iontype))
add_test_method(name, doc, fun)<|docstring|>generate the function to test EVERYTHING at once<|endoftext|> |
2194597f30aab7e2298e80b8456fd3dfe0270b0139c6a019e575032209e65b13 | def fill(svc, method):
'\n make a "shortcut service" for testing crud ops.\n @param svc a dotdict\n @param method the method name to add\n '
realmethod = ('%s_widget' % method)
setattr(svc, realmethod, getattr(owner_service, ('%s_%s' % (method, resource_label)))) | make a "shortcut service" for testing crud ops.
@param svc a dotdict
@param method the method name to add | ion/services/sa/test/helpers.py | fill | ooici/coi-services | 3 | python | def fill(svc, method):
'\n make a "shortcut service" for testing crud ops.\n @param svc a dotdict\n @param method the method name to add\n '
realmethod = ('%s_widget' % method)
setattr(svc, realmethod, getattr(owner_service, ('%s_%s' % (method, resource_label)))) | def fill(svc, method):
'\n make a "shortcut service" for testing crud ops.\n @param svc a dotdict\n @param method the method name to add\n '
realmethod = ('%s_widget' % method)
setattr(svc, realmethod, getattr(owner_service, ('%s_%s' % (method, resource_label))))<|docstring|>make a "shortcut service" for testing crud ops.
@param svc a dotdict
@param method the method name to add<|endoftext|> |
efb64f8899575426d2f2be69cccc8f385e5ae235ac5eee1a0151cc370330294e | def getsvc_fun(self):
'\n self is an instance of the tester class\n '
if (not hasattr(self, '_utg_service_obj')):
service_itself = getattr(self, find_cv_func(self, service_type))
self._utg_service_obj = service_itself
assert self._utg_service_obj
return self._utg_service_obj | self is an instance of the tester class | ion/services/sa/test/helpers.py | getsvc_fun | ooici/coi-services | 3 | python | def getsvc_fun(self):
'\n \n '
if (not hasattr(self, '_utg_service_obj')):
service_itself = getattr(self, find_cv_func(self, service_type))
self._utg_service_obj = service_itself
assert self._utg_service_obj
return self._utg_service_obj | def getsvc_fun(self):
'\n \n '
if (not hasattr(self, '_utg_service_obj')):
service_itself = getattr(self, find_cv_func(self, service_type))
self._utg_service_obj = service_itself
assert self._utg_service_obj
return self._utg_service_obj<|docstring|>self is an instance of the tester class<|endoftext|> |
3c1e0b9370bd384695a3100e61d78eb4e66dc383500af8a9510f6eaa98c70527 | def getcrudmethod_fun(self, rsrc_lbl, method_str):
'\n self is an instance of the tester class\n method_str is a crud method name like "create" that will become "create_resource_label"\n '
svc = self._utg_getservice()
methodname = ('%s_%s' % (method_str, rsrc_lbl))
if (not hasattr(svc, methodname)):
raise SkipTest('CRUD method does not exist, skipping')
return getattr(svc, methodname) | self is an instance of the tester class
method_str is a crud method name like "create" that will become "create_resource_label" | ion/services/sa/test/helpers.py | getcrudmethod_fun | ooici/coi-services | 3 | python | def getcrudmethod_fun(self, rsrc_lbl, method_str):
'\n self is an instance of the tester class\n method_str is a crud method name like "create" that will become "create_resource_label"\n '
svc = self._utg_getservice()
methodname = ('%s_%s' % (method_str, rsrc_lbl))
if (not hasattr(svc, methodname)):
raise SkipTest('CRUD method does not exist, skipping')
return getattr(svc, methodname) | def getcrudmethod_fun(self, rsrc_lbl, method_str):
'\n self is an instance of the tester class\n method_str is a crud method name like "create" that will become "create_resource_label"\n '
svc = self._utg_getservice()
methodname = ('%s_%s' % (method_str, rsrc_lbl))
if (not hasattr(svc, methodname)):
raise SkipTest('CRUD method does not exist, skipping')
return getattr(svc, methodname)<|docstring|>self is an instance of the tester class
method_str is a crud method name like "create" that will become "create_resource_label"<|endoftext|> |
946674525f741731dc16ea538920b6069a1aec30df9eef4507fa49da365ecfcb | def fun(self):
'\n self is an instance of the tester class\n '
test_create_fun(self)
test_create_bad_wrongtype_fun(self)
test_create_bad_noname_fun(self)
test_read_fun(self)
test_read_bad_wrongtype_fun(self)
test_update_fun(self)
test_update_bad_wrongtype_fun(self)
test_delete_fun(self)
test_delete_bad_wrongtype_fun(self)
test_force_delete_fun(self)
test_force_delete_bad_wrongtype_fun(self) | self is an instance of the tester class | ion/services/sa/test/helpers.py | fun | ooici/coi-services | 3 | python | def fun(self):
'\n \n '
test_create_fun(self)
test_create_bad_wrongtype_fun(self)
test_create_bad_noname_fun(self)
test_read_fun(self)
test_read_bad_wrongtype_fun(self)
test_update_fun(self)
test_update_bad_wrongtype_fun(self)
test_delete_fun(self)
test_delete_bad_wrongtype_fun(self)
test_force_delete_fun(self)
test_force_delete_bad_wrongtype_fun(self) | def fun(self):
'\n \n '
test_create_fun(self)
test_create_bad_wrongtype_fun(self)
test_create_bad_noname_fun(self)
test_read_fun(self)
test_read_bad_wrongtype_fun(self)
test_update_fun(self)
test_update_bad_wrongtype_fun(self)
test_delete_fun(self)
test_delete_bad_wrongtype_fun(self)
test_force_delete_fun(self)
test_force_delete_bad_wrongtype_fun(self)<|docstring|>self is an instance of the tester class<|endoftext|> |
df227ca714cf3c175b735e5c72760a3ff7a7b8cf759f5f6c61635aae08053ca8 | def get_input_words(self):
'Prompt user for input file location, read the file, then return a list of the words\n it contains\n '
filename = self.prompt('Please enter the path of the text file to be analyzed (e.g., input/Text1.txt): ')
if os.path.isfile(filename):
input_text = open(filename, 'r').read()
return self.remove_punctuation(input_text)
else:
print('This file does not exist. Please try again.')
return [] | Prompt user for input file location, read the file, then return a list of the words
it contains | analyzer/analyzer.py | get_input_words | jasonflorack/text-analyzer | 0 | python | def get_input_words(self):
'Prompt user for input file location, read the file, then return a list of the words\n it contains\n '
filename = self.prompt('Please enter the path of the text file to be analyzed (e.g., input/Text1.txt): ')
if os.path.isfile(filename):
input_text = open(filename, 'r').read()
return self.remove_punctuation(input_text)
else:
print('This file does not exist. Please try again.')
return [] | def get_input_words(self):
'Prompt user for input file location, read the file, then return a list of the words\n it contains\n '
filename = self.prompt('Please enter the path of the text file to be analyzed (e.g., input/Text1.txt): ')
if os.path.isfile(filename):
input_text = open(filename, 'r').read()
return self.remove_punctuation(input_text)
else:
print('This file does not exist. Please try again.')
return []<|docstring|>Prompt user for input file location, read the file, then return a list of the words
it contains<|endoftext|> |
8d04cd6030c5329f6a7851ca138e94b98fb71548ef4a70962d5a045e01ce7be2 | @staticmethod
def remove_punctuation(text):
'Remove punctuation from text; return list of each word in text'
return re.sub('[^\\w\\s]', '', text).split() | Remove punctuation from text; return list of each word in text | analyzer/analyzer.py | remove_punctuation | jasonflorack/text-analyzer | 0 | python | @staticmethod
def remove_punctuation(text):
return re.sub('[^\\w\\s]', , text).split() | @staticmethod
def remove_punctuation(text):
return re.sub('[^\\w\\s]', , text).split()<|docstring|>Remove punctuation from text; return list of each word in text<|endoftext|> |
64219a35d3d0d37dfd99c1959ffc69ac9fd645d3c0111794f293f76378656b59 | def get_stopwords(self):
'Prompt user for stopwords file location, read the file, then return a list of words\n it contains\n '
stopwords_file = self.prompt('Please enter the path of the stopwords file (e.g., input/stopwords.txt): ')
if os.path.isfile(stopwords_file):
return open(stopwords_file, 'r').read().split()
else:
print('This file does not exist. Please try again.')
return [] | Prompt user for stopwords file location, read the file, then return a list of words
it contains | analyzer/analyzer.py | get_stopwords | jasonflorack/text-analyzer | 0 | python | def get_stopwords(self):
'Prompt user for stopwords file location, read the file, then return a list of words\n it contains\n '
stopwords_file = self.prompt('Please enter the path of the stopwords file (e.g., input/stopwords.txt): ')
if os.path.isfile(stopwords_file):
return open(stopwords_file, 'r').read().split()
else:
print('This file does not exist. Please try again.')
return [] | def get_stopwords(self):
'Prompt user for stopwords file location, read the file, then return a list of words\n it contains\n '
stopwords_file = self.prompt('Please enter the path of the stopwords file (e.g., input/stopwords.txt): ')
if os.path.isfile(stopwords_file):
return open(stopwords_file, 'r').read().split()
else:
print('This file does not exist. Please try again.')
return []<|docstring|>Prompt user for stopwords file location, read the file, then return a list of words
it contains<|endoftext|> |
5bbca7b3b20766bbd3498c0bba90c90fcf2ce8a79d20cc062b71b150c3304bac | @staticmethod
def remove_stop_words(input_words, stopwords):
"Return a list of 'filtered_words' from the provided list of 'input_words' by\n removing any words from the provided list of 'stopwords'\n "
filtered_words = []
for word in input_words:
if (not (word.lower() in stopwords)):
filtered_words.append(word)
return filtered_words | Return a list of 'filtered_words' from the provided list of 'input_words' by
removing any words from the provided list of 'stopwords' | analyzer/analyzer.py | remove_stop_words | jasonflorack/text-analyzer | 0 | python | @staticmethod
def remove_stop_words(input_words, stopwords):
"Return a list of 'filtered_words' from the provided list of 'input_words' by\n removing any words from the provided list of 'stopwords'\n "
filtered_words = []
for word in input_words:
if (not (word.lower() in stopwords)):
filtered_words.append(word)
return filtered_words | @staticmethod
def remove_stop_words(input_words, stopwords):
"Return a list of 'filtered_words' from the provided list of 'input_words' by\n removing any words from the provided list of 'stopwords'\n "
filtered_words = []
for word in input_words:
if (not (word.lower() in stopwords)):
filtered_words.append(word)
return filtered_words<|docstring|>Return a list of 'filtered_words' from the provided list of 'input_words' by
removing any words from the provided list of 'stopwords'<|endoftext|> |
4834019120669fce43c6ffc144cf0e521be3268f4e41282cee9d6102f57c5ea3 | @staticmethod
def stem(words):
"Return a list of 'stemmed_words' from the provided list of 'words' by\n using a Porter Stemming Algorithm to stem all words to their\n morphological root (e.g., jumping, jumps, jumped -> jump)\n "
p = porter_stemmer.PorterStemmer()
stemmed_words = []
for word in words:
stemmed_words.append(p.stem(word, 0, (len(word) - 1)))
return stemmed_words | Return a list of 'stemmed_words' from the provided list of 'words' by
using a Porter Stemming Algorithm to stem all words to their
morphological root (e.g., jumping, jumps, jumped -> jump) | analyzer/analyzer.py | stem | jasonflorack/text-analyzer | 0 | python | @staticmethod
def stem(words):
"Return a list of 'stemmed_words' from the provided list of 'words' by\n using a Porter Stemming Algorithm to stem all words to their\n morphological root (e.g., jumping, jumps, jumped -> jump)\n "
p = porter_stemmer.PorterStemmer()
stemmed_words = []
for word in words:
stemmed_words.append(p.stem(word, 0, (len(word) - 1)))
return stemmed_words | @staticmethod
def stem(words):
"Return a list of 'stemmed_words' from the provided list of 'words' by\n using a Porter Stemming Algorithm to stem all words to their\n morphological root (e.g., jumping, jumps, jumped -> jump)\n "
p = porter_stemmer.PorterStemmer()
stemmed_words = []
for word in words:
stemmed_words.append(p.stem(word, 0, (len(word) - 1)))
return stemmed_words<|docstring|>Return a list of 'stemmed_words' from the provided list of 'words' by
using a Porter Stemming Algorithm to stem all words to their
morphological root (e.g., jumping, jumps, jumped -> jump)<|endoftext|> |
5eab89e82e6b64e253b93b113443cff2ffd6a1852463d685cce682e2c509be85 | @staticmethod
def compute_term_frequency(words):
"Return a 'frequency' dict from the provided list of 'words' which contains\n each word (key) and the number of times it appears (value)\n "
frequency = dict()
for word in words:
if (word not in frequency.keys()):
frequency[word] = 1
else:
frequency[word] += 1
return frequency | Return a 'frequency' dict from the provided list of 'words' which contains
each word (key) and the number of times it appears (value) | analyzer/analyzer.py | compute_term_frequency | jasonflorack/text-analyzer | 0 | python | @staticmethod
def compute_term_frequency(words):
"Return a 'frequency' dict from the provided list of 'words' which contains\n each word (key) and the number of times it appears (value)\n "
frequency = dict()
for word in words:
if (word not in frequency.keys()):
frequency[word] = 1
else:
frequency[word] += 1
return frequency | @staticmethod
def compute_term_frequency(words):
"Return a 'frequency' dict from the provided list of 'words' which contains\n each word (key) and the number of times it appears (value)\n "
frequency = dict()
for word in words:
if (word not in frequency.keys()):
frequency[word] = 1
else:
frequency[word] += 1
return frequency<|docstring|>Return a 'frequency' dict from the provided list of 'words' which contains
each word (key) and the number of times it appears (value)<|endoftext|> |
6d59ebfeff8c9f6868b2ca09d4b8f4204355b32bdc395f93209303a40b694222 | @staticmethod
def sort_top_terms(frequency, count):
"Return a 'top_common_terms' list of tuples from the provided 'frequency' dict\n which contains the top 'count' number of key/value pairs, in descending order\n "
top_common_terms = []
all_common_terms = sorted(frequency.items(), key=(lambda x: x[1]), reverse=True)
for i in range(count):
top_common_terms.append(all_common_terms[i])
return top_common_terms | Return a 'top_common_terms' list of tuples from the provided 'frequency' dict
which contains the top 'count' number of key/value pairs, in descending order | analyzer/analyzer.py | sort_top_terms | jasonflorack/text-analyzer | 0 | python | @staticmethod
def sort_top_terms(frequency, count):
"Return a 'top_common_terms' list of tuples from the provided 'frequency' dict\n which contains the top 'count' number of key/value pairs, in descending order\n "
top_common_terms = []
all_common_terms = sorted(frequency.items(), key=(lambda x: x[1]), reverse=True)
for i in range(count):
top_common_terms.append(all_common_terms[i])
return top_common_terms | @staticmethod
def sort_top_terms(frequency, count):
"Return a 'top_common_terms' list of tuples from the provided 'frequency' dict\n which contains the top 'count' number of key/value pairs, in descending order\n "
top_common_terms = []
all_common_terms = sorted(frequency.items(), key=(lambda x: x[1]), reverse=True)
for i in range(count):
top_common_terms.append(all_common_terms[i])
return top_common_terms<|docstring|>Return a 'top_common_terms' list of tuples from the provided 'frequency' dict
which contains the top 'count' number of key/value pairs, in descending order<|endoftext|> |
84ae90c616c6ec2272bc1ac347a354e202643198aee33a242ecca595401fb2b9 | @staticmethod
def print_top_terms(terms):
"Print the provided 'terms' list of tuples"
print('')
print('After filtering out stopwords, the provided text contains these 20 most commonly occurring root terms:')
print('------------------------------------------------------------------------------------------------------')
for term in terms:
print((((term[0] + ' : ') + str(term[1])) + ' occurrences'))
print('') | Print the provided 'terms' list of tuples | analyzer/analyzer.py | print_top_terms | jasonflorack/text-analyzer | 0 | python | @staticmethod
def print_top_terms(terms):
print()
print('After filtering out stopwords, the provided text contains these 20 most commonly occurring root terms:')
print('------------------------------------------------------------------------------------------------------')
for term in terms:
print((((term[0] + ' : ') + str(term[1])) + ' occurrences'))
print() | @staticmethod
def print_top_terms(terms):
print()
print('After filtering out stopwords, the provided text contains these 20 most commonly occurring root terms:')
print('------------------------------------------------------------------------------------------------------')
for term in terms:
print((((term[0] + ' : ') + str(term[1])) + ' occurrences'))
print()<|docstring|>Print the provided 'terms' list of tuples<|endoftext|> |
0887d740d4e8e93e0a72e7570979336e207edc86b492dbbf166a115b2d9dba56 | def tick(self, time_passed):
' Triggers the entities StateMachine and locomotion '
self.brain.think()
if ((self.speed > 0) and (self.location != self.destination)):
self._check_collisions_(time_passed)
self._move_(time_passed) | Triggers the entities StateMachine and locomotion | entities/base_entity.py | tick | jonesmat/outbreak_z | 1 | python | def tick(self, time_passed):
' '
self.brain.think()
if ((self.speed > 0) and (self.location != self.destination)):
self._check_collisions_(time_passed)
self._move_(time_passed) | def tick(self, time_passed):
' '
self.brain.think()
if ((self.speed > 0) and (self.location != self.destination)):
self._check_collisions_(time_passed)
self._move_(time_passed)<|docstring|>Triggers the entities StateMachine and locomotion<|endoftext|> |
673b4f4057fb96811a9874eb356fdf50c00b9fdbe22d7e318e9d937e274b73bb | def get_random_destination(self):
' Returns a random vector within the viewport '
return Vector2(randint(0, self.game.scene.viewport_rect.right), randint(0, self.game.scene.viewport_rect.bottom)) | Returns a random vector within the viewport | entities/base_entity.py | get_random_destination | jonesmat/outbreak_z | 1 | python | def get_random_destination(self):
' '
return Vector2(randint(0, self.game.scene.viewport_rect.right), randint(0, self.game.scene.viewport_rect.bottom)) | def get_random_destination(self):
' '
return Vector2(randint(0, self.game.scene.viewport_rect.right), randint(0, self.game.scene.viewport_rect.bottom))<|docstring|>Returns a random vector within the viewport<|endoftext|> |
6025acf9fb0f856a4aa48e20ed5db4b63caacbe0dea151e748e106526706aed5 | def _check_collisions_(self, time_passed):
' Checks to see if the entities current location is too close\n to another entity, if so then the entity will attempt to spread out a bit.'
if (self.redirect_timer is None):
collision_distance = 10
blocking_entity = self.game.get_close_entity(None, self.location, collision_distance, self.id)
if (blocking_entity is not None):
if self.debug_mode:
print(f'{self.name}-{self.id}: Too close to {blocking_entity.name}-{blocking_entity.id}, avoiding!')
self.prev_destination = self.destination
self.destination = self.get_random_destination()
self.redirect_timer = 0.2
elif (self.redirect_timer > 0):
if self.debug_mode:
print(f'{self.name}-{self.id}: Still avoiding for {self.redirect_timer}!')
self.redirect_timer -= time_passed
else:
if self.debug_mode:
print(f'{self.name}-{self.id}: Completed avoidance.')
self.destination = self.prev_destination
self.prev_destination = None
self.redirect_timer = None | Checks to see if the entities current location is too close
to another entity, if so then the entity will attempt to spread out a bit. | entities/base_entity.py | _check_collisions_ | jonesmat/outbreak_z | 1 | python | def _check_collisions_(self, time_passed):
' Checks to see if the entities current location is too close\n to another entity, if so then the entity will attempt to spread out a bit.'
if (self.redirect_timer is None):
collision_distance = 10
blocking_entity = self.game.get_close_entity(None, self.location, collision_distance, self.id)
if (blocking_entity is not None):
if self.debug_mode:
print(f'{self.name}-{self.id}: Too close to {blocking_entity.name}-{blocking_entity.id}, avoiding!')
self.prev_destination = self.destination
self.destination = self.get_random_destination()
self.redirect_timer = 0.2
elif (self.redirect_timer > 0):
if self.debug_mode:
print(f'{self.name}-{self.id}: Still avoiding for {self.redirect_timer}!')
self.redirect_timer -= time_passed
else:
if self.debug_mode:
print(f'{self.name}-{self.id}: Completed avoidance.')
self.destination = self.prev_destination
self.prev_destination = None
self.redirect_timer = None | def _check_collisions_(self, time_passed):
' Checks to see if the entities current location is too close\n to another entity, if so then the entity will attempt to spread out a bit.'
if (self.redirect_timer is None):
collision_distance = 10
blocking_entity = self.game.get_close_entity(None, self.location, collision_distance, self.id)
if (blocking_entity is not None):
if self.debug_mode:
print(f'{self.name}-{self.id}: Too close to {blocking_entity.name}-{blocking_entity.id}, avoiding!')
self.prev_destination = self.destination
self.destination = self.get_random_destination()
self.redirect_timer = 0.2
elif (self.redirect_timer > 0):
if self.debug_mode:
print(f'{self.name}-{self.id}: Still avoiding for {self.redirect_timer}!')
self.redirect_timer -= time_passed
else:
if self.debug_mode:
print(f'{self.name}-{self.id}: Completed avoidance.')
self.destination = self.prev_destination
self.prev_destination = None
self.redirect_timer = None<|docstring|>Checks to see if the entities current location is too close
to another entity, if so then the entity will attempt to spread out a bit.<|endoftext|> |
396f3302daa3e1dc340adf1cac694b024083dcf6b049b1e98edfcc3e9f872735 | def _move_(self, time_passed):
' Provides locomotion for the entity while ensuring it stays within the viewport. '
vec_to_destination = (self.destination - self.location)
distance_to_destination = vec_to_destination.length()
heading = vec_to_destination.normalize()
travel_distance = min(distance_to_destination, (time_passed * self.speed))
self.location = (self.location + (travel_distance * heading))
if (self.location.x < 0):
self.location.x = 0
if (self.location.x > self.game.scene.viewport_rect.right):
self.location.x = self.game.scene.viewport_rect.right
if (self.location.y < 0):
self.location.y = 0
if (self.location.y > self.game.scene.viewport_rect.bottom):
self.location.y = self.game.scene.viewport_rect.bottom | Provides locomotion for the entity while ensuring it stays within the viewport. | entities/base_entity.py | _move_ | jonesmat/outbreak_z | 1 | python | def _move_(self, time_passed):
' '
vec_to_destination = (self.destination - self.location)
distance_to_destination = vec_to_destination.length()
heading = vec_to_destination.normalize()
travel_distance = min(distance_to_destination, (time_passed * self.speed))
self.location = (self.location + (travel_distance * heading))
if (self.location.x < 0):
self.location.x = 0
if (self.location.x > self.game.scene.viewport_rect.right):
self.location.x = self.game.scene.viewport_rect.right
if (self.location.y < 0):
self.location.y = 0
if (self.location.y > self.game.scene.viewport_rect.bottom):
self.location.y = self.game.scene.viewport_rect.bottom | def _move_(self, time_passed):
' '
vec_to_destination = (self.destination - self.location)
distance_to_destination = vec_to_destination.length()
heading = vec_to_destination.normalize()
travel_distance = min(distance_to_destination, (time_passed * self.speed))
self.location = (self.location + (travel_distance * heading))
if (self.location.x < 0):
self.location.x = 0
if (self.location.x > self.game.scene.viewport_rect.right):
self.location.x = self.game.scene.viewport_rect.right
if (self.location.y < 0):
self.location.y = 0
if (self.location.y > self.game.scene.viewport_rect.bottom):
self.location.y = self.game.scene.viewport_rect.bottom<|docstring|>Provides locomotion for the entity while ensuring it stays within the viewport.<|endoftext|> |
e59a41abf28f0894f2358eb66d91a66bf9f3773c17a93798cbcc776f696a0d36 | def entry_actions(self):
' Override this method with any actions that are to be preformed\n when this state begins. '
pass | Override this method with any actions that are to be preformed
when this state begins. | entities/base_entity.py | entry_actions | jonesmat/outbreak_z | 1 | python | def entry_actions(self):
' Override this method with any actions that are to be preformed\n when this state begins. '
pass | def entry_actions(self):
' Override this method with any actions that are to be preformed\n when this state begins. '
pass<|docstring|>Override this method with any actions that are to be preformed
when this state begins.<|endoftext|> |
621bf03aac764d63b5438add256eb89161dbb5fbb39d82a634a551b1f1f4ff2b | def do_actions(self):
' Override this method with any actions you want to be preformed\n every tick.'
pass | Override this method with any actions you want to be preformed
every tick. | entities/base_entity.py | do_actions | jonesmat/outbreak_z | 1 | python | def do_actions(self):
' Override this method with any actions you want to be preformed\n every tick.'
pass | def do_actions(self):
' Override this method with any actions you want to be preformed\n every tick.'
pass<|docstring|>Override this method with any actions you want to be preformed
every tick.<|endoftext|> |
0748693e40db5f49946fe67805f41d5ede48de16bcd2e4c834242c602ecd23b4 | def check_conditions(self):
' Override this method with conditional checks for leaving this\n state. '
pass | Override this method with conditional checks for leaving this
state. | entities/base_entity.py | check_conditions | jonesmat/outbreak_z | 1 | python | def check_conditions(self):
' Override this method with conditional checks for leaving this\n state. '
pass | def check_conditions(self):
' Override this method with conditional checks for leaving this\n state. '
pass<|docstring|>Override this method with conditional checks for leaving this
state.<|endoftext|> |
c195e154b58d4e43981ac0afbfd3c0fd25fa1724e52bf16c3043682cc902209f | def exit_actions(self):
' Override this method with any actions that are to be preformed\n as this state is exiting. '
pass | Override this method with any actions that are to be preformed
as this state is exiting. | entities/base_entity.py | exit_actions | jonesmat/outbreak_z | 1 | python | def exit_actions(self):
' Override this method with any actions that are to be preformed\n as this state is exiting. '
pass | def exit_actions(self):
' Override this method with any actions that are to be preformed\n as this state is exiting. '
pass<|docstring|>Override this method with any actions that are to be preformed
as this state is exiting.<|endoftext|> |
c9873a8fac72178b12b9cba7b651a70dc13acbe30b0f61866befb5b2f8e31294 | def add_state(self, state):
' Add a state to the internal dictionary '
self.states[state.name] = state | Add a state to the internal dictionary | entities/base_entity.py | add_state | jonesmat/outbreak_z | 1 | python | def add_state(self, state):
' '
self.states[state.name] = state | def add_state(self, state):
' '
self.states[state.name] = state<|docstring|>Add a state to the internal dictionary<|endoftext|> |
3a131674d05543f80f4a27307fa437563153dc466ff05254f9657af0aa276d41 | def think(self):
' Perform the actions of the active state and check conditions '
if (self.active_state is None):
return
self.active_state.do_actions()
new_state_name = self.active_state.check_conditions()
if (new_state_name is not None):
self.set_state(new_state_name) | Perform the actions of the active state and check conditions | entities/base_entity.py | think | jonesmat/outbreak_z | 1 | python | def think(self):
' '
if (self.active_state is None):
return
self.active_state.do_actions()
new_state_name = self.active_state.check_conditions()
if (new_state_name is not None):
self.set_state(new_state_name) | def think(self):
' '
if (self.active_state is None):
return
self.active_state.do_actions()
new_state_name = self.active_state.check_conditions()
if (new_state_name is not None):
self.set_state(new_state_name)<|docstring|>Perform the actions of the active state and check conditions<|endoftext|> |
5143fc93ddb1d8b7a657d0ee09858833c36a80d10c03d111d725581f46fa7f3f | def set_state(self, new_state_name):
' Change states and perform any exit / entry actions '
if (self.active_state is not None):
self.active_state.exit_actions()
self.active_state = self.states[new_state_name]
self.active_state.entry_actions() | Change states and perform any exit / entry actions | entities/base_entity.py | set_state | jonesmat/outbreak_z | 1 | python | def set_state(self, new_state_name):
' '
if (self.active_state is not None):
self.active_state.exit_actions()
self.active_state = self.states[new_state_name]
self.active_state.entry_actions() | def set_state(self, new_state_name):
' '
if (self.active_state is not None):
self.active_state.exit_actions()
self.active_state = self.states[new_state_name]
self.active_state.entry_actions()<|docstring|>Change states and perform any exit / entry actions<|endoftext|> |
6212a0e834f8934c7b137a0d9370f0da9f3c95f1d38f10ea6eef5f96452bfa3f | def run_algorithm(bytes_total, input_file, out_dir):
'Read the indicated number of bytes from input file and store in output directory\n\n :param bytes_total:\n :param input_file:\n :param out_dir:\n :return:\n '
bytes_read = 0
chunk_size = 512
logging.info(('Reading %s bytes from %s and storing at %s.' % (bytes_total, input_file, out_dir)))
output_file = os.path.join(out_dir, os.path.basename(input_file))
logging.info(('Data being stored in %s' % output_file))
with open(input_file, 'rb') as infile:
with open(output_file, 'wb') as outfile:
while (bytes_read <= bytes_total):
if ((bytes_read + chunk_size) > bytes_total):
chunk_size = (bytes_total - bytes_read)
chunk = infile.read(chunk_size)
if (not chunk):
break
outfile.write(chunk)
bytes_read += chunk_size
logging.info('Copy complete')
return output_file | Read the indicated number of bytes from input file and store in output directory
:param bytes_total:
:param input_file:
:param out_dir:
:return: | dockerfiles/examples/read-bytes/scale-job.py | run_algorithm | kfconsultant/scale | 121 | python | def run_algorithm(bytes_total, input_file, out_dir):
'Read the indicated number of bytes from input file and store in output directory\n\n :param bytes_total:\n :param input_file:\n :param out_dir:\n :return:\n '
bytes_read = 0
chunk_size = 512
logging.info(('Reading %s bytes from %s and storing at %s.' % (bytes_total, input_file, out_dir)))
output_file = os.path.join(out_dir, os.path.basename(input_file))
logging.info(('Data being stored in %s' % output_file))
with open(input_file, 'rb') as infile:
with open(output_file, 'wb') as outfile:
while (bytes_read <= bytes_total):
if ((bytes_read + chunk_size) > bytes_total):
chunk_size = (bytes_total - bytes_read)
chunk = infile.read(chunk_size)
if (not chunk):
break
outfile.write(chunk)
bytes_read += chunk_size
logging.info('Copy complete')
return output_file | def run_algorithm(bytes_total, input_file, out_dir):
'Read the indicated number of bytes from input file and store in output directory\n\n :param bytes_total:\n :param input_file:\n :param out_dir:\n :return:\n '
bytes_read = 0
chunk_size = 512
logging.info(('Reading %s bytes from %s and storing at %s.' % (bytes_total, input_file, out_dir)))
output_file = os.path.join(out_dir, os.path.basename(input_file))
logging.info(('Data being stored in %s' % output_file))
with open(input_file, 'rb') as infile:
with open(output_file, 'wb') as outfile:
while (bytes_read <= bytes_total):
if ((bytes_read + chunk_size) > bytes_total):
chunk_size = (bytes_total - bytes_read)
chunk = infile.read(chunk_size)
if (not chunk):
break
outfile.write(chunk)
bytes_read += chunk_size
logging.info('Copy complete')
return output_file<|docstring|>Read the indicated number of bytes from input file and store in output directory
:param bytes_total:
:param input_file:
:param out_dir:
:return:<|endoftext|> |
e24629f67a941679d43539f029c3f3289a3bd66972024952caac08ad511bafee | def make_app_bundle(dist_dir, make_lite=False):
'\n Make macOS application bundle.\n\n Parameters\n ----------\n dist_dir : pathlib.Path\n Directory in which to put the application bundle.\n make_lite : bool, optional\n Whether to create the application bundle with minimal packages.\n The default is False.\n '
from spyder.config.utils import EDIT_FILETYPES, _get_extensions
build_type = ('lite' if make_lite else 'full')
logger.info('Creating %s app bundle...', build_type)
from packages import PACKAGES, INCLUDES, EXCLUDES, SCIENTIFIC
if make_lite:
EXCLUDES.extend(SCIENTIFIC)
else:
INCLUDES.extend(SCIENTIFIC)
EDIT_EXT = [ext[1:] for ext in _get_extensions(EDIT_FILETYPES)]
OPTIONS = {'optimize': 0, 'packages': PACKAGES, 'includes': INCLUDES, 'excludes': EXCLUDES, 'iconfile': ICONFILE.as_posix(), 'dist_dir': dist_dir.as_posix(), 'emulate_shell_environment': True, 'plist': {'CFBundleDocumentTypes': [{'CFBundleTypeExtensions': EDIT_EXT, 'CFBundleTypeName': 'Text File', 'CFBundleTypeRole': 'Editor'}], 'CFBundleIdentifier': 'org.spyder-ide', 'CFBundleShortVersionString': SPYVER, 'NSRequiresAquaSystemAppearance': False}}
setup(name=APP_BASE_NAME, app=[APPSCRIPT.as_posix()], options={'py2app': OPTIONS})
return | Make macOS application bundle.
Parameters
----------
dist_dir : pathlib.Path
Directory in which to put the application bundle.
make_lite : bool, optional
Whether to create the application bundle with minimal packages.
The default is False. | installers/macOS/setup.py | make_app_bundle | Ajax-Light/spyder | 0 | python | def make_app_bundle(dist_dir, make_lite=False):
'\n Make macOS application bundle.\n\n Parameters\n ----------\n dist_dir : pathlib.Path\n Directory in which to put the application bundle.\n make_lite : bool, optional\n Whether to create the application bundle with minimal packages.\n The default is False.\n '
from spyder.config.utils import EDIT_FILETYPES, _get_extensions
build_type = ('lite' if make_lite else 'full')
logger.info('Creating %s app bundle...', build_type)
from packages import PACKAGES, INCLUDES, EXCLUDES, SCIENTIFIC
if make_lite:
EXCLUDES.extend(SCIENTIFIC)
else:
INCLUDES.extend(SCIENTIFIC)
EDIT_EXT = [ext[1:] for ext in _get_extensions(EDIT_FILETYPES)]
OPTIONS = {'optimize': 0, 'packages': PACKAGES, 'includes': INCLUDES, 'excludes': EXCLUDES, 'iconfile': ICONFILE.as_posix(), 'dist_dir': dist_dir.as_posix(), 'emulate_shell_environment': True, 'plist': {'CFBundleDocumentTypes': [{'CFBundleTypeExtensions': EDIT_EXT, 'CFBundleTypeName': 'Text File', 'CFBundleTypeRole': 'Editor'}], 'CFBundleIdentifier': 'org.spyder-ide', 'CFBundleShortVersionString': SPYVER, 'NSRequiresAquaSystemAppearance': False}}
setup(name=APP_BASE_NAME, app=[APPSCRIPT.as_posix()], options={'py2app': OPTIONS})
return | def make_app_bundle(dist_dir, make_lite=False):
'\n Make macOS application bundle.\n\n Parameters\n ----------\n dist_dir : pathlib.Path\n Directory in which to put the application bundle.\n make_lite : bool, optional\n Whether to create the application bundle with minimal packages.\n The default is False.\n '
from spyder.config.utils import EDIT_FILETYPES, _get_extensions
build_type = ('lite' if make_lite else 'full')
logger.info('Creating %s app bundle...', build_type)
from packages import PACKAGES, INCLUDES, EXCLUDES, SCIENTIFIC
if make_lite:
EXCLUDES.extend(SCIENTIFIC)
else:
INCLUDES.extend(SCIENTIFIC)
EDIT_EXT = [ext[1:] for ext in _get_extensions(EDIT_FILETYPES)]
OPTIONS = {'optimize': 0, 'packages': PACKAGES, 'includes': INCLUDES, 'excludes': EXCLUDES, 'iconfile': ICONFILE.as_posix(), 'dist_dir': dist_dir.as_posix(), 'emulate_shell_environment': True, 'plist': {'CFBundleDocumentTypes': [{'CFBundleTypeExtensions': EDIT_EXT, 'CFBundleTypeName': 'Text File', 'CFBundleTypeRole': 'Editor'}], 'CFBundleIdentifier': 'org.spyder-ide', 'CFBundleShortVersionString': SPYVER, 'NSRequiresAquaSystemAppearance': False}}
setup(name=APP_BASE_NAME, app=[APPSCRIPT.as_posix()], options={'py2app': OPTIONS})
return<|docstring|>Make macOS application bundle.
Parameters
----------
dist_dir : pathlib.Path
Directory in which to put the application bundle.
make_lite : bool, optional
Whether to create the application bundle with minimal packages.
The default is False.<|endoftext|> |
3c1b4273e6c4c1e988e06406fe735419885d487607368b92110fd13dda022b50 | def make_disk_image(dist_dir, make_lite=False):
"\n Make macOS disk image containing Spyder.app application bundle.\n\n Parameters\n ----------\n dist_dir : pathlib.Path\n Directory in which to put the disk image.\n make_lite : bool, optional\n Whether to append the disk image file and volume name with 'Lite'.\n The default is False.\n\n "
logger.info('Creating disk image...')
from dmgbuild import build_dmg
from dmgbuild.core import DMGError
volume_name = '{}-{} Py-{}.{}.{}'.format(APP_BASE_NAME, SPYVER, *PYVER)
dmg_name = 'Spyder'
if make_lite:
volume_name += ' Lite'
dmg_name += '-Lite'
dmg_name += '.dmg'
dmgfile = (dist_dir / dmg_name).as_posix()
settings_file = (THISDIR / 'dmg_settings.py').as_posix()
settings = {'files': [(dist_dir / MAC_APP_NAME).as_posix()], 'badge_icon': ICONFILE.as_posix(), 'icon_locations': {MAC_APP_NAME: (140, 120), 'Applications': (500, 120)}}
try:
build_dmg(dmgfile, volume_name, settings_file=settings_file, settings=settings, detach_retries=30)
logger.info('Building disk image complete.')
except DMGError as exc:
if (exc.args[0] == 'Unable to detach device cleanly'):
logger.warning(exc.args[0])
else:
raise exc
return | Make macOS disk image containing Spyder.app application bundle.
Parameters
----------
dist_dir : pathlib.Path
Directory in which to put the disk image.
make_lite : bool, optional
Whether to append the disk image file and volume name with 'Lite'.
The default is False. | installers/macOS/setup.py | make_disk_image | Ajax-Light/spyder | 0 | python | def make_disk_image(dist_dir, make_lite=False):
"\n Make macOS disk image containing Spyder.app application bundle.\n\n Parameters\n ----------\n dist_dir : pathlib.Path\n Directory in which to put the disk image.\n make_lite : bool, optional\n Whether to append the disk image file and volume name with 'Lite'.\n The default is False.\n\n "
logger.info('Creating disk image...')
from dmgbuild import build_dmg
from dmgbuild.core import DMGError
volume_name = '{}-{} Py-{}.{}.{}'.format(APP_BASE_NAME, SPYVER, *PYVER)
dmg_name = 'Spyder'
if make_lite:
volume_name += ' Lite'
dmg_name += '-Lite'
dmg_name += '.dmg'
dmgfile = (dist_dir / dmg_name).as_posix()
settings_file = (THISDIR / 'dmg_settings.py').as_posix()
settings = {'files': [(dist_dir / MAC_APP_NAME).as_posix()], 'badge_icon': ICONFILE.as_posix(), 'icon_locations': {MAC_APP_NAME: (140, 120), 'Applications': (500, 120)}}
try:
build_dmg(dmgfile, volume_name, settings_file=settings_file, settings=settings, detach_retries=30)
logger.info('Building disk image complete.')
except DMGError as exc:
if (exc.args[0] == 'Unable to detach device cleanly'):
logger.warning(exc.args[0])
else:
raise exc
return | def make_disk_image(dist_dir, make_lite=False):
"\n Make macOS disk image containing Spyder.app application bundle.\n\n Parameters\n ----------\n dist_dir : pathlib.Path\n Directory in which to put the disk image.\n make_lite : bool, optional\n Whether to append the disk image file and volume name with 'Lite'.\n The default is False.\n\n "
logger.info('Creating disk image...')
from dmgbuild import build_dmg
from dmgbuild.core import DMGError
volume_name = '{}-{} Py-{}.{}.{}'.format(APP_BASE_NAME, SPYVER, *PYVER)
dmg_name = 'Spyder'
if make_lite:
volume_name += ' Lite'
dmg_name += '-Lite'
dmg_name += '.dmg'
dmgfile = (dist_dir / dmg_name).as_posix()
settings_file = (THISDIR / 'dmg_settings.py').as_posix()
settings = {'files': [(dist_dir / MAC_APP_NAME).as_posix()], 'badge_icon': ICONFILE.as_posix(), 'icon_locations': {MAC_APP_NAME: (140, 120), 'Applications': (500, 120)}}
try:
build_dmg(dmgfile, volume_name, settings_file=settings_file, settings=settings, detach_retries=30)
logger.info('Building disk image complete.')
except DMGError as exc:
if (exc.args[0] == 'Unable to detach device cleanly'):
logger.warning(exc.args[0])
else:
raise exc
return<|docstring|>Make macOS disk image containing Spyder.app application bundle.
Parameters
----------
dist_dir : pathlib.Path
Directory in which to put the disk image.
make_lite : bool, optional
Whether to append the disk image file and volume name with 'Lite'.
The default is False.<|endoftext|> |
02f6586343d9bf582107f59cf43239bcba532de2531e0c7593fdc391eeafb30e | def __init__(self, mainEmissivity: float, secondaryEmissivity: float, table: tuple):
'This method creates a Radiation object.\n\n Notes\n -----\n This function can be accessed by:\n\n .. code-block:: python\n\n mdb.models[name].interactionProperties[name].Radiation\n \n Parameters\n ----------\n mainEmissivity\n A Float specifying the emissivity of the main surface. \n secondaryEmissivity\n A Float specifying the emissivity of the secondary surface. \n table\n A sequence of sequences of Floats specifying the following:Effective viewfactor, FF.Gap \n clearance, dd. \n\n Returns\n -------\n A Radiation object.\n '
pass | This method creates a Radiation object.
Notes
-----
This function can be accessed by:
.. code-block:: python
mdb.models[name].interactionProperties[name].Radiation
Parameters
----------
mainEmissivity
A Float specifying the emissivity of the main surface.
secondaryEmissivity
A Float specifying the emissivity of the secondary surface.
table
A sequence of sequences of Floats specifying the following:Effective viewfactor, FF.Gap
clearance, dd.
Returns
-------
A Radiation object. | src/abaqus/Interaction/Radiation.py | __init__ | Haiiliin/PyAbaqusBase | 7 | python | def __init__(self, mainEmissivity: float, secondaryEmissivity: float, table: tuple):
'This method creates a Radiation object.\n\n Notes\n -----\n This function can be accessed by:\n\n .. code-block:: python\n\n mdb.models[name].interactionProperties[name].Radiation\n \n Parameters\n ----------\n mainEmissivity\n A Float specifying the emissivity of the main surface. \n secondaryEmissivity\n A Float specifying the emissivity of the secondary surface. \n table\n A sequence of sequences of Floats specifying the following:Effective viewfactor, FF.Gap \n clearance, dd. \n\n Returns\n -------\n A Radiation object.\n '
pass | def __init__(self, mainEmissivity: float, secondaryEmissivity: float, table: tuple):
'This method creates a Radiation object.\n\n Notes\n -----\n This function can be accessed by:\n\n .. code-block:: python\n\n mdb.models[name].interactionProperties[name].Radiation\n \n Parameters\n ----------\n mainEmissivity\n A Float specifying the emissivity of the main surface. \n secondaryEmissivity\n A Float specifying the emissivity of the secondary surface. \n table\n A sequence of sequences of Floats specifying the following:Effective viewfactor, FF.Gap \n clearance, dd. \n\n Returns\n -------\n A Radiation object.\n '
pass<|docstring|>This method creates a Radiation object.
Notes
-----
This function can be accessed by:
.. code-block:: python
mdb.models[name].interactionProperties[name].Radiation
Parameters
----------
mainEmissivity
A Float specifying the emissivity of the main surface.
secondaryEmissivity
A Float specifying the emissivity of the secondary surface.
table
A sequence of sequences of Floats specifying the following:Effective viewfactor, FF.Gap
clearance, dd.
Returns
-------
A Radiation object.<|endoftext|> |
405a531c0be3bf8fd0a9a884b32a6ab4b137fdfb0d94ef16dcc0d1b44b2bcf0a | def setValues(self):
'This method modifies the Radiation object.\n '
pass | This method modifies the Radiation object. | src/abaqus/Interaction/Radiation.py | setValues | Haiiliin/PyAbaqusBase | 7 | python | def setValues(self):
'\n '
pass | def setValues(self):
'\n '
pass<|docstring|>This method modifies the Radiation object.<|endoftext|> |
f6ac1663b2f2f9268676d2a6940974e5dd0f9b21b6dd89589643be9d70a5f270 | def __init__(self, targets, loop=None):
'\n Initialize a `Flo` with the given `targets` channels.\n\n If `loop` is not given, a new loop will be created on the current\n thread, via `get_default_ioloop`.\n '
self.count = itertools.count()
self.targets = {}
if (loop is None):
loop = self.get_default_ioloop()
self.loop = loop
self.add_targets(targets) | Initialize a `Flo` with the given `targets` channels.
If `loop` is not given, a new loop will be created on the current
thread, via `get_default_ioloop`. | flowz/app.py | __init__ | ethanrowe/flowz | 2 | python | def __init__(self, targets, loop=None):
'\n Initialize a `Flo` with the given `targets` channels.\n\n If `loop` is not given, a new loop will be created on the current\n thread, via `get_default_ioloop`.\n '
self.count = itertools.count()
self.targets = {}
if (loop is None):
loop = self.get_default_ioloop()
self.loop = loop
self.add_targets(targets) | def __init__(self, targets, loop=None):
'\n Initialize a `Flo` with the given `targets` channels.\n\n If `loop` is not given, a new loop will be created on the current\n thread, via `get_default_ioloop`.\n '
self.count = itertools.count()
self.targets = {}
if (loop is None):
loop = self.get_default_ioloop()
self.loop = loop
self.add_targets(targets)<|docstring|>Initialize a `Flo` with the given `targets` channels.
If `loop` is not given, a new loop will be created on the current
thread, via `get_default_ioloop`.<|endoftext|> |
150a67532387d6bba4c6289f2195455c19c3744214ca1789671686513874184d | @gen.coroutine
def wrap_target(self, target):
'\n Forces app to stop on unhandled exceptions.\n '
result = None
try:
if hasattr(target, 'future'):
result = (yield target.future())
else:
try:
while True:
(yield target.next())
except channels.ChannelDone:
pass
except Exception as e:
self.exc_info = sys.exc_info()
self.loop.stop()
raise gen.Return(result) | Forces app to stop on unhandled exceptions. | flowz/app.py | wrap_target | ethanrowe/flowz | 2 | python | @gen.coroutine
def wrap_target(self, target):
'\n \n '
result = None
try:
if hasattr(target, 'future'):
result = (yield target.future())
else:
try:
while True:
(yield target.next())
except channels.ChannelDone:
pass
except Exception as e:
self.exc_info = sys.exc_info()
self.loop.stop()
raise gen.Return(result) | @gen.coroutine
def wrap_target(self, target):
'\n \n '
result = None
try:
if hasattr(target, 'future'):
result = (yield target.future())
else:
try:
while True:
(yield target.next())
except channels.ChannelDone:
pass
except Exception as e:
self.exc_info = sys.exc_info()
self.loop.stop()
raise gen.Return(result)<|docstring|>Forces app to stop on unhandled exceptions.<|endoftext|> |
f80c734aa8feaab9d39c8dcd63d9de20e1e2404bf6684d2f8c84a0a18fb41232 | def run(self):
'\n Runs the workflow, blocking until completion.\n\n Completion is achieved when either:\n - an unhandled exception propagates past a channel.\n - all channels have been consumed.\n\n Once complete, the underlying `ioloop` has been stopped.\n\n No return value.\n '
self.loop.spawn_callback(self.main)
self.loop.start()
if self.exc_info:
six.reraise(*self.exc_info) | Runs the workflow, blocking until completion.
Completion is achieved when either:
- an unhandled exception propagates past a channel.
- all channels have been consumed.
Once complete, the underlying `ioloop` has been stopped.
No return value. | flowz/app.py | run | ethanrowe/flowz | 2 | python | def run(self):
'\n Runs the workflow, blocking until completion.\n\n Completion is achieved when either:\n - an unhandled exception propagates past a channel.\n - all channels have been consumed.\n\n Once complete, the underlying `ioloop` has been stopped.\n\n No return value.\n '
self.loop.spawn_callback(self.main)
self.loop.start()
if self.exc_info:
six.reraise(*self.exc_info) | def run(self):
'\n Runs the workflow, blocking until completion.\n\n Completion is achieved when either:\n - an unhandled exception propagates past a channel.\n - all channels have been consumed.\n\n Once complete, the underlying `ioloop` has been stopped.\n\n No return value.\n '
self.loop.spawn_callback(self.main)
self.loop.start()
if self.exc_info:
six.reraise(*self.exc_info)<|docstring|>Runs the workflow, blocking until completion.
Completion is achieved when either:
- an unhandled exception propagates past a channel.
- all channels have been consumed.
Once complete, the underlying `ioloop` has been stopped.
No return value.<|endoftext|> |
c185dc3a0fcd7c484768efcd5edb7f2aeb09cad157715f31608986cb145cf7e7 | def is_verification_file(path: pathlib.Path, *, basedir: Optional[pathlib.Path]=None) -> bool:
'`is_verification_file` is a thin wrapper for `Languge.is_verification_file`. This function automatically get the language.\n '
basedir = (basedir or pathlib.Path.cwd())
language = onlinejudge_verify.languages.list.get(path)
return ((language is not None) and language.is_verification_file(path, basedir=basedir)) | `is_verification_file` is a thin wrapper for `Languge.is_verification_file`. This function automatically get the language. | onlinejudge_verify/utils.py | is_verification_file | ryo-n/verification-helper | 0 | python | def is_verification_file(path: pathlib.Path, *, basedir: Optional[pathlib.Path]=None) -> bool:
'\n '
basedir = (basedir or pathlib.Path.cwd())
language = onlinejudge_verify.languages.list.get(path)
return ((language is not None) and language.is_verification_file(path, basedir=basedir)) | def is_verification_file(path: pathlib.Path, *, basedir: Optional[pathlib.Path]=None) -> bool:
'\n '
basedir = (basedir or pathlib.Path.cwd())
language = onlinejudge_verify.languages.list.get(path)
return ((language is not None) and language.is_verification_file(path, basedir=basedir))<|docstring|>`is_verification_file` is a thin wrapper for `Languge.is_verification_file`. This function automatically get the language.<|endoftext|> |
ee9247d8ee2f45fdc51faaad336c55e8d09fbaa25e9ccb590507355e2bbb9c27 | def get_object(filename, fileformat=None):
'Read serialized object from file. Detect file format if not specified'
if (not fileformat):
fileformat = detect_format(filename)
loaders = {'JSON': load_json, 'StrictYAML': load_strict_yaml, 'YAML': load_yaml}
return loaders[fileformat](filename) | Read serialized object from file. Detect file format if not specified | hods/_lib/files.py | get_object | sio/hods | 0 | python | def get_object(filename, fileformat=None):
if (not fileformat):
fileformat = detect_format(filename)
loaders = {'JSON': load_json, 'StrictYAML': load_strict_yaml, 'YAML': load_yaml}
return loaders[fileformat](filename) | def get_object(filename, fileformat=None):
if (not fileformat):
fileformat = detect_format(filename)
loaders = {'JSON': load_json, 'StrictYAML': load_strict_yaml, 'YAML': load_yaml}
return loaders[fileformat](filename)<|docstring|>Read serialized object from file. Detect file format if not specified<|endoftext|> |
239f223ccad8b2db955d0d44e5bd50a71583d4399eff9b891060bd2209aeb00c | def write_object(obj, filename, fileformat=None, suffix='.hods~'):
'Write serialized object to file. Detect file format if not specified'
if (not filename):
raise ValueError('can not write data without filename')
if (not fileformat):
fileformat = detect_format(filename)
writers = {'JSON': write_json, 'StrictYAML': write_strict_yaml, 'YAML': write_yaml}
with backup(filename, suffix):
writers[fileformat](obj, filename) | Write serialized object to file. Detect file format if not specified | hods/_lib/files.py | write_object | sio/hods | 0 | python | def write_object(obj, filename, fileformat=None, suffix='.hods~'):
if (not filename):
raise ValueError('can not write data without filename')
if (not fileformat):
fileformat = detect_format(filename)
writers = {'JSON': write_json, 'StrictYAML': write_strict_yaml, 'YAML': write_yaml}
with backup(filename, suffix):
writers[fileformat](obj, filename) | def write_object(obj, filename, fileformat=None, suffix='.hods~'):
if (not filename):
raise ValueError('can not write data without filename')
if (not fileformat):
fileformat = detect_format(filename)
writers = {'JSON': write_json, 'StrictYAML': write_strict_yaml, 'YAML': write_yaml}
with backup(filename, suffix):
writers[fileformat](obj, filename)<|docstring|>Write serialized object to file. Detect file format if not specified<|endoftext|> |
a4eb62db6fd17c35b90c90b07b56b3f1d7983aaf42e64caa39d0212a73350b65 | @contextmanager
def backup(filename, suffix='.hods~'):
'Context manager to execute dangerous file operations with backup'
suffix_for_duplicates = '{num}~'
backup_created = False
if suffix:
backup_name = (filename + suffix)
backup_number = 0
while os.path.exists(backup_name):
backup_number += 1
backup_name = ((filename + suffix) + suffix_for_duplicates.format(num=backup_number))
try:
shutil.copyfile(filename, backup_name)
backup_created = True
except FileNotFoundError:
pass
(yield)
if backup_created:
os.remove(backup_name) | Context manager to execute dangerous file operations with backup | hods/_lib/files.py | backup | sio/hods | 0 | python | @contextmanager
def backup(filename, suffix='.hods~'):
suffix_for_duplicates = '{num}~'
backup_created = False
if suffix:
backup_name = (filename + suffix)
backup_number = 0
while os.path.exists(backup_name):
backup_number += 1
backup_name = ((filename + suffix) + suffix_for_duplicates.format(num=backup_number))
try:
shutil.copyfile(filename, backup_name)
backup_created = True
except FileNotFoundError:
pass
(yield)
if backup_created:
os.remove(backup_name) | @contextmanager
def backup(filename, suffix='.hods~'):
suffix_for_duplicates = '{num}~'
backup_created = False
if suffix:
backup_name = (filename + suffix)
backup_number = 0
while os.path.exists(backup_name):
backup_number += 1
backup_name = ((filename + suffix) + suffix_for_duplicates.format(num=backup_number))
try:
shutil.copyfile(filename, backup_name)
backup_created = True
except FileNotFoundError:
pass
(yield)
if backup_created:
os.remove(backup_name)<|docstring|>Context manager to execute dangerous file operations with backup<|endoftext|> |
855e4137c854a841c187ebb19fa7877ff9d218cb4c9316d365b3edd921260623 | def get_files(directory='.', recursive=False):
'Detect metadata files in given directory'
if recursive:
traverse = os.walk(directory)
else:
traverse = (next(os.walk(directory)),)
for (parent, dirs, files) in traverse:
for filename in files:
full_path = os.path.join(parent, filename)
if is_metadata(full_path):
(yield full_path) | Detect metadata files in given directory | hods/_lib/files.py | get_files | sio/hods | 0 | python | def get_files(directory='.', recursive=False):
if recursive:
traverse = os.walk(directory)
else:
traverse = (next(os.walk(directory)),)
for (parent, dirs, files) in traverse:
for filename in files:
full_path = os.path.join(parent, filename)
if is_metadata(full_path):
(yield full_path) | def get_files(directory='.', recursive=False):
if recursive:
traverse = os.walk(directory)
else:
traverse = (next(os.walk(directory)),)
for (parent, dirs, files) in traverse:
for filename in files:
full_path = os.path.join(parent, filename)
if is_metadata(full_path):
(yield full_path)<|docstring|>Detect metadata files in given directory<|endoftext|> |
bb817b29be38feaf467947571c1ac70c0ca542bba36b36d957c93e07f8985e94 | def test_save_patch_existing_receiver(self):
'\n This tests if all previous preferences are deleted and new ones are attached\n '
all_preferences = Preferences.objects.bulk_create([Preferences(hobby='first preference'), Preferences(hobby='second preference'), Preferences(hobby='Third preference')])
current_receiver = Receiver(email='[email protected]', first_name='first name', last_name='last name', age=12, user=self.user)
current_receiver.save()
current_receiver.preferences.add(all_preferences[0])
patch_payload = {'email': current_receiver.email, 'first_name': 'updated first name', 'last_name': 'updated last name', 'age': 22, 'preferences': all_preferences[1:]}
form = ReceiverForm(patch_payload, user=self.user)
self.assertTrue(form.is_valid())
form.save()
updated_receiver = Receiver.objects.filter(email=current_receiver.email)[0]
self.assertEqual(updated_receiver.email, patch_payload['email'])
self.assertEqual(updated_receiver.first_name, patch_payload['first_name'])
self.assertEqual(updated_receiver.last_name, patch_payload['last_name'])
self.assertEqual(updated_receiver.age, patch_payload['age'])
for (index, preference) in enumerate(updated_receiver.preferences.all()):
self.assertEqual(preference, patch_payload['preferences'][index]) | This tests if all previous preferences are deleted and new ones are attached | Emailer/main/tests/forms/many_to_many_forms/test_receiver.py | test_save_patch_existing_receiver | Pavel-Petkov03/Emailer | 0 | python | def test_save_patch_existing_receiver(self):
'\n \n '
all_preferences = Preferences.objects.bulk_create([Preferences(hobby='first preference'), Preferences(hobby='second preference'), Preferences(hobby='Third preference')])
current_receiver = Receiver(email='[email protected]', first_name='first name', last_name='last name', age=12, user=self.user)
current_receiver.save()
current_receiver.preferences.add(all_preferences[0])
patch_payload = {'email': current_receiver.email, 'first_name': 'updated first name', 'last_name': 'updated last name', 'age': 22, 'preferences': all_preferences[1:]}
form = ReceiverForm(patch_payload, user=self.user)
self.assertTrue(form.is_valid())
form.save()
updated_receiver = Receiver.objects.filter(email=current_receiver.email)[0]
self.assertEqual(updated_receiver.email, patch_payload['email'])
self.assertEqual(updated_receiver.first_name, patch_payload['first_name'])
self.assertEqual(updated_receiver.last_name, patch_payload['last_name'])
self.assertEqual(updated_receiver.age, patch_payload['age'])
for (index, preference) in enumerate(updated_receiver.preferences.all()):
self.assertEqual(preference, patch_payload['preferences'][index]) | def test_save_patch_existing_receiver(self):
'\n \n '
all_preferences = Preferences.objects.bulk_create([Preferences(hobby='first preference'), Preferences(hobby='second preference'), Preferences(hobby='Third preference')])
current_receiver = Receiver(email='[email protected]', first_name='first name', last_name='last name', age=12, user=self.user)
current_receiver.save()
current_receiver.preferences.add(all_preferences[0])
patch_payload = {'email': current_receiver.email, 'first_name': 'updated first name', 'last_name': 'updated last name', 'age': 22, 'preferences': all_preferences[1:]}
form = ReceiverForm(patch_payload, user=self.user)
self.assertTrue(form.is_valid())
form.save()
updated_receiver = Receiver.objects.filter(email=current_receiver.email)[0]
self.assertEqual(updated_receiver.email, patch_payload['email'])
self.assertEqual(updated_receiver.first_name, patch_payload['first_name'])
self.assertEqual(updated_receiver.last_name, patch_payload['last_name'])
self.assertEqual(updated_receiver.age, patch_payload['age'])
for (index, preference) in enumerate(updated_receiver.preferences.all()):
self.assertEqual(preference, patch_payload['preferences'][index])<|docstring|>This tests if all previous preferences are deleted and new ones are attached<|endoftext|> |
26a8fe0b9c55f54dc19d8e6619b6baf1abf842edc051b1733f063e51d8d60687 | @timer
def Do(driver, task_list, error_list, logger):
'\n\n :param task: dict\n :return: list—>[str,dict]\n '
end_task = 0
for task in task_list:
task['msg'] = '0000'
userinfo = task['user']
airline = task['company']
url = 'https://flights.ctrip.com/international/search/oneway-{start}-{end}?depdate={date}&cabin=y_s&adult=1&child=0&infant=0&directflight=1&airline={airline}'.format(start=task['start'], end=task['end'], date=task['date'], airline=airline[:2])
driver.delete_all_cookies()
driver.get(url)
element = WebDriverWait(driver, 30, 0.1)
driver.implicitly_wait(5)
try:
startRun = int(time.time())
while (not etree.HTML(driver.page_source).xpath('//div[@class="loading finish"]/@style')):
if ((int(time.time()) - startRun) > 30):
error_list.append(task)
driver.quit()
tag_index = (- 1)
html = etree.HTML(driver.page_source)
place_list = html.xpath('//span[@class="plane-No"]/text()')
print(place_list)
for (index, place) in enumerate(place_list):
if (task['company'] in place):
tag_index = index
break
if (tag_index != (- 1)):
price_list = html.xpath('//div[contains(@id,"price_{}")]/text()'.format(tag_index))
print('当前价格{},价格区间{}-{}'.format(price_list, task['min_price'], task['max_price']))
if (not price_list):
raise TimeoutException
price = None
pay_index = 0
for (price_index, temp_price) in enumerate(price_list):
if (int(task['min_price']) < int(temp_price) < int(task['max_price'])):
price = temp_price
pay_index = price_index
break
else:
raise ElementNotVisibleException
if price:
print(''.join(['开始预定========', price]))
WebDriverWait(driver, 3, 0.1).until(EC.element_to_be_clickable((By.ID, '{}_{}'.format(tag_index, pay_index)))).click()
if (len(driver.window_handles) > 1):
driver.switch_to_window(driver.window_handles[1])
driver.close()
driver.switch_to_window(driver.window_handles[0])
try:
WebDriverWait(driver, 3, 0.1).until(EC.element_to_be_clickable((By.ID, 'nologin'))).click()
except:
pass
try:
user_form(driver, userinfo)
except:
continue
element.until(EC.element_to_be_clickable((By.CLASS_NAME, 'btn-next'))).click()
startRun = int(time.time())
while (not ('护照:{}'.format(task['user']['passport']) in driver.page_source)):
if ((int(time.time()) - startRun) > 30):
driver.quit()
findStr = '{}/{}'.format(task['user']['surnames'], task['user']['name']).replace(' ', '')
if (((findStr in driver.page_source) or ('目前该舱位已售完' in driver.page_source)) and (not ('护照:{}'.format(task['user']['passport']) in driver.page_source))):
(yield task)
end_task = 1
break
if end_task:
re_task_list = []
for task_ in task_list:
if (task_['ts'] == task['ts']):
task_['min_price'] = str((int(price) + 1))
re_task_list.append(task_)
else:
re_task_list.append(task_)
task_list = re_task_list
continue
order = str(driver.current_url).split('/')[(- 2)]
js = 'window.open("https://flights.ctrip.com/online/orderdetail/index?oid={}");'.format(order)
driver.execute_script(js)
driver.switch_to_window(driver.window_handles[1])
startRun = int(time.time())
while (('没有查到您的订单信息' in driver.page_source) or ('繁忙' in driver.page_source)):
driver.refresh()
if ((int(time.time()) - startRun) > 30):
error_list.append(task)
driver.quit()
cookies = driver.get_cookies()
key_result = ''.join([task['date'].replace('-', ''), task['start'], task['end'], task['company']])
result = [key_result, {'order': order, 'cookies': cookies, 'modele_name': '1.1.2', 'type': 2, 'parent': task['ts'], 'up': int((time.time() * 1000)), 'baseTime': 1200000}, price]
driver.close()
(yield result)
driver.switch_to_window(driver.window_handles[0])
driver.delete_all_cookies()
else:
print('不在价格范围========================》')
task['msg'] = '0001'
(yield task)
except UnexpectedAlertPresentException:
driver.switch_to.alert.accept()
driver.delete_all_cookies()
traceback.print_exc()
length = len(driver.window_handles)
if (length > 1):
for index in range(1, length):
driver.switch_to_window(driver.window_handles[index])
driver.close()
driver.switch_to_window(driver.window_handles[0])
error_list.append(task)
except Exception:
driver.delete_all_cookies()
if alert_is_present(driver):
driver.switch_to.alert.accept()
traceback.print_exc()
length = len(driver.window_handles)
if (length > 1):
for index in range(1, length):
driver.switch_to_window(driver.window_handles[index])
driver.close()
driver.switch_to_window(driver.window_handles[0])
error_list.append(task) | :param task: dict
:return: list—>[str,dict] | py/spider/miscellany/Airlines_xiecheng_seating.py | Do | 7134g/mySpiderAll | 0 | python | @timer
def Do(driver, task_list, error_list, logger):
'\n\n :param task: dict\n :return: list—>[str,dict]\n '
end_task = 0
for task in task_list:
task['msg'] = '0000'
userinfo = task['user']
airline = task['company']
url = 'https://flights.ctrip.com/international/search/oneway-{start}-{end}?depdate={date}&cabin=y_s&adult=1&child=0&infant=0&directflight=1&airline={airline}'.format(start=task['start'], end=task['end'], date=task['date'], airline=airline[:2])
driver.delete_all_cookies()
driver.get(url)
element = WebDriverWait(driver, 30, 0.1)
driver.implicitly_wait(5)
try:
startRun = int(time.time())
while (not etree.HTML(driver.page_source).xpath('//div[@class="loading finish"]/@style')):
if ((int(time.time()) - startRun) > 30):
error_list.append(task)
driver.quit()
tag_index = (- 1)
html = etree.HTML(driver.page_source)
place_list = html.xpath('//span[@class="plane-No"]/text()')
print(place_list)
for (index, place) in enumerate(place_list):
if (task['company'] in place):
tag_index = index
break
if (tag_index != (- 1)):
price_list = html.xpath('//div[contains(@id,"price_{}")]/text()'.format(tag_index))
print('当前价格{},价格区间{}-{}'.format(price_list, task['min_price'], task['max_price']))
if (not price_list):
raise TimeoutException
price = None
pay_index = 0
for (price_index, temp_price) in enumerate(price_list):
if (int(task['min_price']) < int(temp_price) < int(task['max_price'])):
price = temp_price
pay_index = price_index
break
else:
raise ElementNotVisibleException
if price:
print(.join(['开始预定========', price]))
WebDriverWait(driver, 3, 0.1).until(EC.element_to_be_clickable((By.ID, '{}_{}'.format(tag_index, pay_index)))).click()
if (len(driver.window_handles) > 1):
driver.switch_to_window(driver.window_handles[1])
driver.close()
driver.switch_to_window(driver.window_handles[0])
try:
WebDriverWait(driver, 3, 0.1).until(EC.element_to_be_clickable((By.ID, 'nologin'))).click()
except:
pass
try:
user_form(driver, userinfo)
except:
continue
element.until(EC.element_to_be_clickable((By.CLASS_NAME, 'btn-next'))).click()
startRun = int(time.time())
while (not ('护照:{}'.format(task['user']['passport']) in driver.page_source)):
if ((int(time.time()) - startRun) > 30):
driver.quit()
findStr = '{}/{}'.format(task['user']['surnames'], task['user']['name']).replace(' ', )
if (((findStr in driver.page_source) or ('目前该舱位已售完' in driver.page_source)) and (not ('护照:{}'.format(task['user']['passport']) in driver.page_source))):
(yield task)
end_task = 1
break
if end_task:
re_task_list = []
for task_ in task_list:
if (task_['ts'] == task['ts']):
task_['min_price'] = str((int(price) + 1))
re_task_list.append(task_)
else:
re_task_list.append(task_)
task_list = re_task_list
continue
order = str(driver.current_url).split('/')[(- 2)]
js = 'window.open("https://flights.ctrip.com/online/orderdetail/index?oid={}");'.format(order)
driver.execute_script(js)
driver.switch_to_window(driver.window_handles[1])
startRun = int(time.time())
while (('没有查到您的订单信息' in driver.page_source) or ('繁忙' in driver.page_source)):
driver.refresh()
if ((int(time.time()) - startRun) > 30):
error_list.append(task)
driver.quit()
cookies = driver.get_cookies()
key_result = .join([task['date'].replace('-', ), task['start'], task['end'], task['company']])
result = [key_result, {'order': order, 'cookies': cookies, 'modele_name': '1.1.2', 'type': 2, 'parent': task['ts'], 'up': int((time.time() * 1000)), 'baseTime': 1200000}, price]
driver.close()
(yield result)
driver.switch_to_window(driver.window_handles[0])
driver.delete_all_cookies()
else:
print('不在价格范围========================》')
task['msg'] = '0001'
(yield task)
except UnexpectedAlertPresentException:
driver.switch_to.alert.accept()
driver.delete_all_cookies()
traceback.print_exc()
length = len(driver.window_handles)
if (length > 1):
for index in range(1, length):
driver.switch_to_window(driver.window_handles[index])
driver.close()
driver.switch_to_window(driver.window_handles[0])
error_list.append(task)
except Exception:
driver.delete_all_cookies()
if alert_is_present(driver):
driver.switch_to.alert.accept()
traceback.print_exc()
length = len(driver.window_handles)
if (length > 1):
for index in range(1, length):
driver.switch_to_window(driver.window_handles[index])
driver.close()
driver.switch_to_window(driver.window_handles[0])
error_list.append(task) | @timer
def Do(driver, task_list, error_list, logger):
'\n\n :param task: dict\n :return: list—>[str,dict]\n '
end_task = 0
for task in task_list:
task['msg'] = '0000'
userinfo = task['user']
airline = task['company']
url = 'https://flights.ctrip.com/international/search/oneway-{start}-{end}?depdate={date}&cabin=y_s&adult=1&child=0&infant=0&directflight=1&airline={airline}'.format(start=task['start'], end=task['end'], date=task['date'], airline=airline[:2])
driver.delete_all_cookies()
driver.get(url)
element = WebDriverWait(driver, 30, 0.1)
driver.implicitly_wait(5)
try:
startRun = int(time.time())
while (not etree.HTML(driver.page_source).xpath('//div[@class="loading finish"]/@style')):
if ((int(time.time()) - startRun) > 30):
error_list.append(task)
driver.quit()
tag_index = (- 1)
html = etree.HTML(driver.page_source)
place_list = html.xpath('//span[@class="plane-No"]/text()')
print(place_list)
for (index, place) in enumerate(place_list):
if (task['company'] in place):
tag_index = index
break
if (tag_index != (- 1)):
price_list = html.xpath('//div[contains(@id,"price_{}")]/text()'.format(tag_index))
print('当前价格{},价格区间{}-{}'.format(price_list, task['min_price'], task['max_price']))
if (not price_list):
raise TimeoutException
price = None
pay_index = 0
for (price_index, temp_price) in enumerate(price_list):
if (int(task['min_price']) < int(temp_price) < int(task['max_price'])):
price = temp_price
pay_index = price_index
break
else:
raise ElementNotVisibleException
if price:
print(.join(['开始预定========', price]))
WebDriverWait(driver, 3, 0.1).until(EC.element_to_be_clickable((By.ID, '{}_{}'.format(tag_index, pay_index)))).click()
if (len(driver.window_handles) > 1):
driver.switch_to_window(driver.window_handles[1])
driver.close()
driver.switch_to_window(driver.window_handles[0])
try:
WebDriverWait(driver, 3, 0.1).until(EC.element_to_be_clickable((By.ID, 'nologin'))).click()
except:
pass
try:
user_form(driver, userinfo)
except:
continue
element.until(EC.element_to_be_clickable((By.CLASS_NAME, 'btn-next'))).click()
startRun = int(time.time())
while (not ('护照:{}'.format(task['user']['passport']) in driver.page_source)):
if ((int(time.time()) - startRun) > 30):
driver.quit()
findStr = '{}/{}'.format(task['user']['surnames'], task['user']['name']).replace(' ', )
if (((findStr in driver.page_source) or ('目前该舱位已售完' in driver.page_source)) and (not ('护照:{}'.format(task['user']['passport']) in driver.page_source))):
(yield task)
end_task = 1
break
if end_task:
re_task_list = []
for task_ in task_list:
if (task_['ts'] == task['ts']):
task_['min_price'] = str((int(price) + 1))
re_task_list.append(task_)
else:
re_task_list.append(task_)
task_list = re_task_list
continue
order = str(driver.current_url).split('/')[(- 2)]
js = 'window.open("https://flights.ctrip.com/online/orderdetail/index?oid={}");'.format(order)
driver.execute_script(js)
driver.switch_to_window(driver.window_handles[1])
startRun = int(time.time())
while (('没有查到您的订单信息' in driver.page_source) or ('繁忙' in driver.page_source)):
driver.refresh()
if ((int(time.time()) - startRun) > 30):
error_list.append(task)
driver.quit()
cookies = driver.get_cookies()
key_result = .join([task['date'].replace('-', ), task['start'], task['end'], task['company']])
result = [key_result, {'order': order, 'cookies': cookies, 'modele_name': '1.1.2', 'type': 2, 'parent': task['ts'], 'up': int((time.time() * 1000)), 'baseTime': 1200000}, price]
driver.close()
(yield result)
driver.switch_to_window(driver.window_handles[0])
driver.delete_all_cookies()
else:
print('不在价格范围========================》')
task['msg'] = '0001'
(yield task)
except UnexpectedAlertPresentException:
driver.switch_to.alert.accept()
driver.delete_all_cookies()
traceback.print_exc()
length = len(driver.window_handles)
if (length > 1):
for index in range(1, length):
driver.switch_to_window(driver.window_handles[index])
driver.close()
driver.switch_to_window(driver.window_handles[0])
error_list.append(task)
except Exception:
driver.delete_all_cookies()
if alert_is_present(driver):
driver.switch_to.alert.accept()
traceback.print_exc()
length = len(driver.window_handles)
if (length > 1):
for index in range(1, length):
driver.switch_to_window(driver.window_handles[index])
driver.close()
driver.switch_to_window(driver.window_handles[0])
error_list.append(task)<|docstring|>:param task: dict
:return: list—>[str,dict]<|endoftext|> |
0399d5a6a598cc0a2b565a4056dfa4d71305fe67726dff9aad635ee6e54ae07a | def json_deserialize(json, unboxing_function: Any=None) -> Any:
'JSON Deerialization of a given string.\n\n Args:\n json: The JSON serialized string to deserialize.\n unboxing_function (Any): Function used to convert the json string\n to a class instance.\n Returns:\n An object representing the data contained in the JSON serialized string.\n '
if (json is None):
return None
try:
decoded = jsonpickle.decode(json)
except:
return json
if (not unboxing_function):
return decoded
elif isinstance(decoded, list):
return [unboxing_function(element) for element in decoded]
else:
return unboxing_function(decoded) | JSON Deerialization of a given string.
Args:
json: The JSON serialized string to deserialize.
unboxing_function (Any): Function used to convert the json string
to a class instance.
Returns:
An object representing the data contained in the JSON serialized string. | clumioapi/api_helper.py | json_deserialize | clumio-code/clumio-python-sdk | 0 | python | def json_deserialize(json, unboxing_function: Any=None) -> Any:
'JSON Deerialization of a given string.\n\n Args:\n json: The JSON serialized string to deserialize.\n unboxing_function (Any): Function used to convert the json string\n to a class instance.\n Returns:\n An object representing the data contained in the JSON serialized string.\n '
if (json is None):
return None
try:
decoded = jsonpickle.decode(json)
except:
return json
if (not unboxing_function):
return decoded
elif isinstance(decoded, list):
return [unboxing_function(element) for element in decoded]
else:
return unboxing_function(decoded) | def json_deserialize(json, unboxing_function: Any=None) -> Any:
'JSON Deerialization of a given string.\n\n Args:\n json: The JSON serialized string to deserialize.\n unboxing_function (Any): Function used to convert the json string\n to a class instance.\n Returns:\n An object representing the data contained in the JSON serialized string.\n '
if (json is None):
return None
try:
decoded = jsonpickle.decode(json)
except:
return json
if (not unboxing_function):
return decoded
elif isinstance(decoded, list):
return [unboxing_function(element) for element in decoded]
else:
return unboxing_function(decoded)<|docstring|>JSON Deerialization of a given string.
Args:
json: The JSON serialized string to deserialize.
unboxing_function (Any): Function used to convert the json string
to a class instance.
Returns:
An object representing the data contained in the JSON serialized string.<|endoftext|> |
c7e98f953b0532210ad6920213bc85f516722edf97af4c00d2254b76e5cd2f3c | def append_url_with_template_parameters(url: str, parameters: Mapping[(str, Any)], encode: bool=True) -> str:
'Replaces template parameters in the given url.\n\n Args:\n url: The query url string to replace the template parameters.\n parameters: The parameters to replace in the url.\n encode: Flag to indicate whether the request parameters should be encoded.\n Returns:\n URL with replaced parameters.\n '
if (not url):
raise ValueError('URL is None.')
if (not parameters):
return url
for key in parameters:
element = parameters[key]
if (not element):
replace_value = ''
elif isinstance(element, list):
replace_value = '/'.join(((utils.quote(str(x), safe='') if encode else str(x)) for x in element))
else:
replace_value = (utils.quote(str(element), safe='') if encode else str(element))
url = url.replace(f'{{{key}}}', str(replace_value))
return url | Replaces template parameters in the given url.
Args:
url: The query url string to replace the template parameters.
parameters: The parameters to replace in the url.
encode: Flag to indicate whether the request parameters should be encoded.
Returns:
URL with replaced parameters. | clumioapi/api_helper.py | append_url_with_template_parameters | clumio-code/clumio-python-sdk | 0 | python | def append_url_with_template_parameters(url: str, parameters: Mapping[(str, Any)], encode: bool=True) -> str:
'Replaces template parameters in the given url.\n\n Args:\n url: The query url string to replace the template parameters.\n parameters: The parameters to replace in the url.\n encode: Flag to indicate whether the request parameters should be encoded.\n Returns:\n URL with replaced parameters.\n '
if (not url):
raise ValueError('URL is None.')
if (not parameters):
return url
for key in parameters:
element = parameters[key]
if (not element):
replace_value =
elif isinstance(element, list):
replace_value = '/'.join(((utils.quote(str(x), safe=) if encode else str(x)) for x in element))
else:
replace_value = (utils.quote(str(element), safe=) if encode else str(element))
url = url.replace(f'{{{key}}}', str(replace_value))
return url | def append_url_with_template_parameters(url: str, parameters: Mapping[(str, Any)], encode: bool=True) -> str:
'Replaces template parameters in the given url.\n\n Args:\n url: The query url string to replace the template parameters.\n parameters: The parameters to replace in the url.\n encode: Flag to indicate whether the request parameters should be encoded.\n Returns:\n URL with replaced parameters.\n '
if (not url):
raise ValueError('URL is None.')
if (not parameters):
return url
for key in parameters:
element = parameters[key]
if (not element):
replace_value =
elif isinstance(element, list):
replace_value = '/'.join(((utils.quote(str(x), safe=) if encode else str(x)) for x in element))
else:
replace_value = (utils.quote(str(element), safe=) if encode else str(element))
url = url.replace(f'{{{key}}}', str(replace_value))
return url<|docstring|>Replaces template parameters in the given url.
Args:
url: The query url string to replace the template parameters.
parameters: The parameters to replace in the url.
encode: Flag to indicate whether the request parameters should be encoded.
Returns:
URL with replaced parameters.<|endoftext|> |
5457b9107db9fe6cefc5d7f087a385cb1a8918d00f3c281118959d55b17b73e4 | def to_dictionary(obj: Any) -> Dict[(str, Any)]:
'Creates a dictionary representation of a class instance. The\n keys are taken from the API description and may differ from language\n specific variable names of properties.\n\n Args:\n obj: The object to be converted into a dictionary.\n\n Returns:\n dictionary: A dictionary form of the model with properties in\n their API formats.\n '
dictionary = dict()
for name in obj._names:
value = getattr(obj, name)
attr_name = obj._names[name]
if isinstance(value, list):
dictionary[attr_name] = [_to_dictionary_or_value(item) for item in value]
elif isinstance(value, dict):
dictionary[attr_name] = {child_key: _to_dictionary_or_value(child_value) for (child_key, child_value) in value.items()}
elif isinstance(value, enum.Enum):
dictionary[attr_name] = value.name
else:
dictionary[attr_name] = _to_dictionary_or_value(value)
return dictionary | Creates a dictionary representation of a class instance. The
keys are taken from the API description and may differ from language
specific variable names of properties.
Args:
obj: The object to be converted into a dictionary.
Returns:
dictionary: A dictionary form of the model with properties in
their API formats. | clumioapi/api_helper.py | to_dictionary | clumio-code/clumio-python-sdk | 0 | python | def to_dictionary(obj: Any) -> Dict[(str, Any)]:
'Creates a dictionary representation of a class instance. The\n keys are taken from the API description and may differ from language\n specific variable names of properties.\n\n Args:\n obj: The object to be converted into a dictionary.\n\n Returns:\n dictionary: A dictionary form of the model with properties in\n their API formats.\n '
dictionary = dict()
for name in obj._names:
value = getattr(obj, name)
attr_name = obj._names[name]
if isinstance(value, list):
dictionary[attr_name] = [_to_dictionary_or_value(item) for item in value]
elif isinstance(value, dict):
dictionary[attr_name] = {child_key: _to_dictionary_or_value(child_value) for (child_key, child_value) in value.items()}
elif isinstance(value, enum.Enum):
dictionary[attr_name] = value.name
else:
dictionary[attr_name] = _to_dictionary_or_value(value)
return dictionary | def to_dictionary(obj: Any) -> Dict[(str, Any)]:
'Creates a dictionary representation of a class instance. The\n keys are taken from the API description and may differ from language\n specific variable names of properties.\n\n Args:\n obj: The object to be converted into a dictionary.\n\n Returns:\n dictionary: A dictionary form of the model with properties in\n their API formats.\n '
dictionary = dict()
for name in obj._names:
value = getattr(obj, name)
attr_name = obj._names[name]
if isinstance(value, list):
dictionary[attr_name] = [_to_dictionary_or_value(item) for item in value]
elif isinstance(value, dict):
dictionary[attr_name] = {child_key: _to_dictionary_or_value(child_value) for (child_key, child_value) in value.items()}
elif isinstance(value, enum.Enum):
dictionary[attr_name] = value.name
else:
dictionary[attr_name] = _to_dictionary_or_value(value)
return dictionary<|docstring|>Creates a dictionary representation of a class instance. The
keys are taken from the API description and may differ from language
specific variable names of properties.
Args:
obj: The object to be converted into a dictionary.
Returns:
dictionary: A dictionary form of the model with properties in
their API formats.<|endoftext|> |
3dcba305ed24ffbba6f72ba213faf4342ef8f5c14ed1f522f7572f4fe2826eb4 | def _to_dictionary_or_value(item: Any) -> Any:
'Convert to dictionary if it has the attribute _names or return as is.'
return (to_dictionary(item) if hasattr(item, '_names') else item) | Convert to dictionary if it has the attribute _names or return as is. | clumioapi/api_helper.py | _to_dictionary_or_value | clumio-code/clumio-python-sdk | 0 | python | def _to_dictionary_or_value(item: Any) -> Any:
return (to_dictionary(item) if hasattr(item, '_names') else item) | def _to_dictionary_or_value(item: Any) -> Any:
return (to_dictionary(item) if hasattr(item, '_names') else item)<|docstring|>Convert to dictionary if it has the attribute _names or return as is.<|endoftext|> |
840318f87d2732fc977f8e2c227875bb417c8aa371e0b9fb84aefcd06707da27 | def half_life(spread):
'" Optimal rolling mean window based on half life of deviation from mean'
spread_lag = spread.shift(1)
spread_lag.iloc[0] = spread_lag.iloc[1]
spread_ret = (spread - spread_lag)
spread_ret.iloc[0] = spread_ret.iloc[1]
spread_lag2 = add_constant(spread_lag)
model = OLS(spread_ret, spread_lag2)
res = model.fit()
halflife = int(round(((- np.log(2)) / res.params[1]), 0))
if (halflife <= 0):
halflife = 1
return halflife | " Optimal rolling mean window based on half life of deviation from mean | oil_trading/brent_wti_kalman_spread/kalman_signal/half_life.py | half_life | queiyanglim/trading_algorithm | 4 | python | def half_life(spread):
spread_lag = spread.shift(1)
spread_lag.iloc[0] = spread_lag.iloc[1]
spread_ret = (spread - spread_lag)
spread_ret.iloc[0] = spread_ret.iloc[1]
spread_lag2 = add_constant(spread_lag)
model = OLS(spread_ret, spread_lag2)
res = model.fit()
halflife = int(round(((- np.log(2)) / res.params[1]), 0))
if (halflife <= 0):
halflife = 1
return halflife | def half_life(spread):
spread_lag = spread.shift(1)
spread_lag.iloc[0] = spread_lag.iloc[1]
spread_ret = (spread - spread_lag)
spread_ret.iloc[0] = spread_ret.iloc[1]
spread_lag2 = add_constant(spread_lag)
model = OLS(spread_ret, spread_lag2)
res = model.fit()
halflife = int(round(((- np.log(2)) / res.params[1]), 0))
if (halflife <= 0):
halflife = 1
return halflife<|docstring|>" Optimal rolling mean window based on half life of deviation from mean<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.