Skip to content

Commit

Permalink
Replace boolean methods with isinstance
Browse files Browse the repository at this point in the history
  • Loading branch information
charmoniumQ committed Jun 15, 2023
1 parent 6730b6c commit 94f96b6
Show file tree
Hide file tree
Showing 8 changed files with 42 additions and 108 deletions.
7 changes: 1 addition & 6 deletions src/reposcanner/contrib.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,6 @@ class CommitInfoMiningRoutine(OfflineRepositoryRoutine):
authorship information, the commit message, and which files were interacted with.
"""

def getRequestType(self):
return CommitInfoMiningRoutineRequest

def offlineImplementation(self, request, session):

factory = DataEntityFactory()
Expand Down Expand Up @@ -335,10 +332,8 @@ def __init__(self):
try:
import gambit
except ImportError:
self.gambitIsAvailable = False
self.gambitImportRef = None
else:
self.gambitIsAvailable = True
self.gambitImportRef = gambit

def getRequestType(self):
Expand All @@ -350,7 +345,7 @@ def getRequestType(self):
def execute(self, request):

responseFactory = ResponseFactory()
if not self.gambitIsAvailable:
if not self.gambitImportRef is not None:
return responseFactory.createFailureResponse(message="Gambit is not \
installed, halting execution.")

Expand Down
48 changes: 25 additions & 23 deletions src/reposcanner/manager.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from reposcanner.git import CredentialKeychain
from reposcanner.data import DataEntityStore
from reposcanner.response import ResponseFactory
from reposcanner.requests import AnalysisRequestModel, ExternalCommandLineToolRoutineRequest, OnlineRoutineRequest, RepositoryRoutineRequestModel
from reposcanner.routines import RepositoryRoutine, ExternalCommandLineToolRoutine
from reposcanner.analyses import DataAnalysis
import warnings
Expand Down Expand Up @@ -63,7 +64,7 @@ def process(self, agents, store, notebook):
if selectedAgent is not None:
if notebook is not None:
notebook.onTaskStart(self, store, selectedAgent)
if self._request.isAnalysisRequestType():
if isinstance(self._request, AnalysisRequestModel):
self._request.fetchDataFromStore(store)
self._response = selectedAgent.run(self._request)
if notebook is not None:
Expand All @@ -73,7 +74,7 @@ def process(self, agents, store, notebook):
self._response = responseFactory.createFailureResponse(
message="No routine/analysis was found that could \
execute the request ({requestType}).".format(
requestType=type(request)))
requestType=type(self._request)))

@abstractmethod
def getResponseDescription(self):
Expand Down Expand Up @@ -348,27 +349,28 @@ def isGUIModeEnabled(self):
def buildTask(self, projectID, projectName, url, routineOrAnalysis):
"""Constructs a task to hold a request/response pair."""
requestType = routineOrAnalysis.getRequestType()
if requestType.isRoutineRequestType():
if requestType.isExternalCommandLineToolRequestType():
request = requestType(outputDirectory=self._outputDirectory)
task = ManagerExternalCommandLineToolTask(request)
return task
else:
if requestType.requiresOnlineAPIAccess():
request = requestType(repositoryURL=url,
outputDirectory=self._outputDirectory,
keychain=self._keychain)
else:
request = requestType(repositoryURL=url,
outputDirectory=self._outputDirectory,
workspaceDirectory=self._workspaceDirectory)
task = ManagerRepositoryRoutineTask(
projectID=projectID, projectName=projectName, url=url, request=request)
return task
elif requestType.isAnalysisRequestType():
request = requestType()
task = ManagerAnalysisTask(request)
return task
if issubclass(requestType, ExternalCommandLineToolRoutineRequest):
cmd_request = requestType(outputDirectory=self._outputDirectory)
cmd_task = ManagerExternalCommandLineToolTask(cmd_request)
return cmd_task
elif issubclass(requestType, OnlineRoutineRequest):
online_request = requestType(repositoryURL=url,
outputDirectory=self._outputDirectory,
keychain=self._keychain)
online_task = ManagerRepositoryRoutineTask(
projectID=projectID, projectName=projectName, url=url, request=online_request)
return online_task
elif issubclass(requestType, RepositoryRoutineRequestModel):
repo_request = requestType(repositoryURL=url,
outputDirectory=self._outputDirectory,
workspaceDirectory=self._workspaceDirectory)
repo_task = ManagerRepositoryRoutineTask(
projectID=projectID, projectName=projectName, url=url, request=repo_request)
return repo_task
elif issubclass(requestType, AnalysisRequestModel):
analysis_request = requestType()
analysis_task = ManagerAnalysisTask(analysis_request)
return analysis_task
else:
raise TypeError(
"Encountered unrecognized request type when building task: {requestType}.".format(
Expand Down
7 changes: 4 additions & 3 deletions src/reposcanner/provenance.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
import subprocess
import os
import reposcanner.data as dataEntities
from reposcanner.manager import ManagerRepositoryRoutineTask
from reposcanner.requests import AnalysisRequestModel

"""
trungdong/prov, a W3C-compliant provenance Data Model
Expand Down Expand Up @@ -265,8 +267,7 @@ def onTaskCreation(self, task):
task: The ManagerTask object.
"""
request = task.getRequest()
if request.isRoutineRequestType():
if isinstance(task, ManagerRepositoryRoutineTask):
task = self._document.activity("rs:task{taskid}".format(taskid=id(task)), other_attributes=(
('rs:requestType', task.getRequestClassName()),
('rs:projectID', task.getProjectID()),
Expand Down Expand Up @@ -300,7 +301,7 @@ def onTaskStart(self, task, store, agent):
# If the request is an analysis request, we can probe the request to see which
# files it intends to grab from the data store.
request = task.getRequest()
if request.isAnalysisRequestType():
if isinstance(request, AnalysisRequestModel):
filesToBeUsedInAnalysis = store.getByCriteria(request.getDataCriteria())
for entity in filesToBeUsedInAnalysis:
entityID = None
Expand Down
45 changes: 0 additions & 45 deletions src/reposcanner/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,8 @@ def hasErrors(self):
def getErrors(self):
return self._errors

@classmethod
def isRoutineRequestType(cls):
return False

@classmethod
def isAnalysisRequestType(cls):
return False


class AnalysisRequestModel(BaseRequestModel):

@classmethod
def isAnalysisRequestType(cls):
return True

def __init__(self, outputDirectory="./"):
super().__init__()
self._data = []
Expand Down Expand Up @@ -145,14 +132,6 @@ def __init__(self, outputDirectory):
def getOutputDirectory(self):
return self._outputDirectory

@classmethod
def isRoutineRequestType(cls):
return True

@classmethod
def isExternalCommandLineToolRequestType(cls):
return True


class RepositoryRoutineRequestModel(BaseRequestModel):
"""
Expand Down Expand Up @@ -213,29 +192,13 @@ def getRepositoryLocation(self):
def getOutputDirectory(self):
return self._outputDirectory

@classmethod
def isRoutineRequestType(cls):
return True

@classmethod
def isExternalCommandLineToolRequestType(cls):
return False


class OnlineRoutineRequest(RepositoryRoutineRequestModel):
"""
The base class for requests to routines that use an online API to compute results.
Request classes for OnlineRepositoryRoutine should inherit from this class.
"""

@classmethod
def requiresOnlineAPIAccess(cls):
"""
Tells the caller whether this request requires access to an online
version control API.
"""
return True

def __init__(
self,
repositoryURL,
Expand Down Expand Up @@ -286,14 +249,6 @@ class OfflineRoutineRequest(RepositoryRoutineRequestModel):
Request classes for OfflineRepositoryRoutine should inherit from this class.
"""

@classmethod
def requiresOnlineAPIAccess(cls):
"""
Tells the caller whether this request requires access to an online
version control API.
"""
return False

def __init__(self, repositoryURL, outputDirectory, workspaceDirectory):
"""
Additional Parameters:
Expand Down
9 changes: 5 additions & 4 deletions src/reposcanner/routines.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import pygit2
from reposcanner.git import GitEntityFactory, RepositoryLocation
from reposcanner.response import ResponseFactory
from reposcanner.requests import ExternalCommandLineToolRoutineRequest, OfflineRoutineRequest, OnlineRoutineRequest


class DataMiningRoutine(ABC):
Expand Down Expand Up @@ -112,14 +113,14 @@ def commandLineToolImplementation(self, request):

def execute(self, request):
responseFactory = ResponseFactory()
if not self.canHandleRequest(request):
if not self.canHandleRequest(request) or not isinstance(request, ExternalCommandLineToolRoutineRequest):
return responseFactory.createFailureResponse(
message="The routine was passed a request of the wrong type.")
elif request.hasErrors():
return responseFactory.createFailureResponse(
message="The request had errors in it and cannot be processed.",
attachments=request.getErrors())
elif not self.isExternalToolAvailable():
elif not isinstance(request, ExternalCommandLineToolRoutineRequest):
return responseFactory.createFailureResponse(
message="The command-line tool required by this routine is not available or\
is otherwise unable to be called.")
Expand All @@ -144,7 +145,7 @@ def execute(self, request):
overriding that methods.
"""
responseFactory = ResponseFactory()
if not self.canHandleRequest(request):
if not self.canHandleRequest(request) or not isinstance(request, OfflineRoutineRequest):
return responseFactory.createFailureResponse(
message="The routine was passed a request of the wrong type.")
elif request.hasErrors():
Expand Down Expand Up @@ -214,7 +215,7 @@ def execute(self, request):
overriding those methods.
"""
responseFactory = ResponseFactory()
if not self.canHandleRequest(request):
if not self.canHandleRequest(request) or not isinstance(request, OnlineRoutineRequest):
return responseFactory.createFailureResponse(
message="The routine was passed a request of the wrong type.")
elif request.hasErrors():
Expand Down
File renamed without changes.
14 changes: 7 additions & 7 deletions tests/test_baseRoutines.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,8 @@ def canAlwaysHandleRequest(self, request):
routines.OfflineRepositoryRoutine.canHandleRequest = canAlwaysHandleRequest
genericRoutine = routines.OfflineRepositoryRoutine()

genericRequest = requests.RepositoryRoutineRequestModel(
repositoryURL="https://github.com/owner/repo", outputDirectory="./")
genericRequest = requests.OfflineRoutineRequest(
repositoryURL="https://github.com/owner/repo", outputDirectory="./out", workspaceDirectory="./workspace")
genericRequest.addError(message="Something has gone horribly wrong.")
response = genericRoutine.run(genericRequest)
assert(not response.wasSuccessful())
Expand All @@ -161,8 +161,8 @@ def canNeverHandleRequest(self, request):
routines.OnlineRepositoryRoutine.canHandleRequest = canNeverHandleRequest
genericRoutine = routines.OnlineRepositoryRoutine()

genericRequest = requests.RepositoryRoutineRequestModel(
repositoryURL="https://github.com/owner/repo", outputDirectory="./")
genericRequest = requests.OnlineRoutineRequest(
repositoryURL="https://github.com/owner/repo", outputDirectory="./out")
response = genericRoutine.run(genericRequest)
assert(not response.wasSuccessful())
assert(response.hasMessage())
Expand All @@ -179,7 +179,7 @@ def canAlwaysHandleRequest(self, request):
routines.OnlineRepositoryRoutine.canHandleRequest = canAlwaysHandleRequest
genericRoutine = routines.OnlineRepositoryRoutine()

genericRequest = requests.RepositoryRoutineRequestModel(
genericRequest = requests.OnlineRoutineRequest(
repositoryURL="https://github.com/owner/repo", outputDirectory="./")
genericRequest.addError(message="Something has gone horribly wrong.")
response = genericRoutine.run(genericRequest)
Expand All @@ -203,8 +203,8 @@ def canAlwaysHandleRequest(self, request):
emptyAPICreator = gitEntityFactory.createVCSAPISessionCompositeCreator()
genericRoutine.sessionCreator = emptyAPICreator

genericRequest = requests.RepositoryRoutineRequestModel(
repositoryURL="https://github.com/owner/repo", outputDirectory="./")
genericRequest = requests.OnlineRoutineRequest(
repositoryURL="https://github.com/owner/repo", outputDirectory="./", username="foo", password="bar")
response = genericRoutine.run(genericRequest)
assert(not response.wasSuccessful())
assert(response.hasMessage())
Expand Down
20 changes: 0 additions & 20 deletions tests/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,6 @@ def test_AnalysisRequestModel_isDirectlyConstructible():
analysisRequest = requests.AnalysisRequestModel(outputDirectory="./")


def test_AnalysisRequestModel_isAnAnalysisRequestType():
analysisRequest = requests.AnalysisRequestModel(outputDirectory="./")
assert(analysisRequest.isAnalysisRequestType())
assert(not analysisRequest.isRoutineRequestType())


def test_AnalysisRequestModel_hasNoErrorsForValidInput():
analysisRequest = requests.AnalysisRequestModel(outputDirectory="./")
assert(not analysisRequest.hasErrors())
Expand Down Expand Up @@ -52,13 +46,6 @@ def test_ExternalCommandLineToolRoutineRequest_isDirectlyConstructible():
requests.ExternalCommandLineToolRoutineRequest(outputDirectory="./")


def test_ExternalCommandLineToolRoutineRequest_isARoutineRequestType():
commandLineToolRequest = requests.ExternalCommandLineToolRoutineRequest(
outputDirectory="./")
assert(not commandLineToolRequest.isAnalysisRequestType())
assert(commandLineToolRequest.isRoutineRequestType())


def test_ExternalCommandLineToolRoutineRequest_hasNoErrorsForValidInput():
commandLineToolRequest = requests.ExternalCommandLineToolRoutineRequest(
outputDirectory="./")
Expand Down Expand Up @@ -87,13 +74,6 @@ def test_RepositoryRoutineRequestModel_isDirectlyConstructible():
outputDirectory="./")


def test_AnalysisRequestModel_isARoutineRequestType():
routineRequest = requests.RepositoryRoutineRequestModel(
repositoryURL="https://github.com/owner/repo", outputDirectory="./")
assert(not routineRequest.isAnalysisRequestType())
assert(routineRequest.isRoutineRequestType())


def test_RepositoryRoutineRequestModel_hasNoErrorsForValidInput():
request = requests.RepositoryRoutineRequestModel(
repositoryURL="https://github.com/owner/repo", outputDirectory="./")
Expand Down

0 comments on commit 94f96b6

Please sign in to comment.