I am trying to retrieve data from oracle db but getting No such property: expected for class: Script1343 (in groovy script); error
import java.util.Properties;
import java.io.InputStream;
import groovy.sql.Sql;
def url = 'jdbc:oracle:thin:#//localhost:1521/TEST'
def user = 'DB'
def password = 'DB'
def driver = 'oracle.jdbc.driver.OracleDriver'
def sql = Sql.newInstance('url', 'User', 'password','oracle.jdbc.driver.OracleDriver')
sql.withStatement {
stmt -> stmt.queryTimeout = 30
print "Request TimeOut"
}
def rowNum = 0
sql.eachRow("SELECT DISTINCT CST_START_DT_PF,CST_ITEM_NUM_PF FROM COST "){ row ->
def first = row[0]
def middle = row.CST_START_DT_PF
def one = row.CST_ITEM_NUM_PF
assert expected[rowNum] == "$CST_START_DT_PF, $CST_ITEM_NUM_PF"
}
There are several things wrong. The specific error you asked about is the result of the following:
assert expected[rowNum] == "$CST_START_DT_PF, $CST_ITEM_NUM_PF"
You are referencing a variable expected which doesn't exist.
You didn't ask about the things below but other problems you are going to run into...
Referencing $CST_START_DT_PF and $CST_ITEM_NUM_PF is going to be a problem because they also don't exist, at least not in a way that your code will work.
You also are probably going to get unexpected results related to the fact that you are never incrementing rowNum.
Related
This is my sample code:
from path.lib import DBInterface
class MyClass:
def __init__(self):
self.something = "something"
def _my_method(self, some_key, new_setup):
with DBInterface(self.something) as ic:
current_setup = ic.get(some_key)
if current_setup != new_setup:
with DBInterface(self.something) as ic:
ic.set(new_setup)
def public_method(self, some_key, new_setup):
return self._my_method(some_key, new_setup)
(my actual code is bit more complex, but i cant put it here on public :)
Now, what I want to do is, I want to completely mock the imported class DBInterface, because I do not want my unittests to do anything in DB.
BUT I also need the ic.get(some_key) to return some value, or to be more precise, I need to set the value it returns, because thats the point of my unittests, to test if the method behave properly according to value returned from DB.
This is how far I got:
class TestMyClass:
def test_extractor_register(self, mocker):
fake_db = mocker.patch.object('my_path.my_lib.DBInterface')
fake_db.get.return_value = None
# spy_obj = mocker.spy(MyClass, "_my_method")
test_class = MyClass()
# Test new registration in _extractor_register
result = test_class.public_method(Tconf.test_key, Tconf.test_key_setup)
fake_db.assert_has_calls([call().__enter__().get(Tconf.test_key),
call().__enter__().set(Tconf.test_key, Tconf.test_key_setup)])
# spy_obj.assert_called_with(ANY, Tconf.test_key, Tconf.test_key_setup)
assert result.result_status.status_code == Tconf.status_ok.status_code
assert result.result_data == MyMethodResult.new_reg
But i am unable to set return value for call().__enter__().get(Tconf.test_key).
I have been trying many approaches:
fake_db.get.return_value = None
fake_db.__enter__().get.return_value = None
fake_db.__enter__.get = Mock(return_value=None)
mocker.patch.object(MyClass.DBInterface, "get").return_value = None
None of that is actually working and I am running out of options I can think about.
Without having more code or errors that are being produced, it's tough to provide a conclusive answer.
However, if you truly only need to specify a return value for set() I would recommend using MagicMock by virtue of patch --
from unittest.mock import patch
#patch("<MyClassFile>.DBInterface", autospec=True)
def test_extractor_register(mock_db):
mock_db.set.return_value = "some key"
# Rest of test code
I'm working on Insight automation groovy script, but I got stuck in one point.
I have Insight object called "Agreement".
This object has Inbound References called "Services".
Each Agreement can have any number of Services. I need to get list of all Services for any Agreement. I found the method findObjectInboundReferencedBeans(int id) in the docs, but apparently, I'm missing something as when I run the script, I get an error in log:
AutomationRuleGroovyScriptAction, Unexpected error: No signature of method: com.riadalabs.jira.plugins.insight.channel.external.api.facade.impl.ObjectFacadeImpl.findObjectInboundReferencedBeans() is applicable for argument types: (java.lang.Integer) values: [15748]
Here is my script:
import com.atlassian.jira.component.ComponentAccessor;
import com.riadalabs.jira.plugins.insight.services.model.ObjectAttributeBean;
import com.riadalabs.jira.plugins.insight.services.model.ObjectBean;
import com.riadalabs.jira.plugins.insight.services.model.MutableObjectAttributeBean;
import com.riadalabs.jira.plugins.insight.services.model.MutableObjectBean;
Class objectFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade")
def objectFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectFacadeClass)
// def agreementStatusId = 2641
// def serviceStatusId = 2180
// def activeStatus = 1
// def stoppedStatus = 6
def attributeRef = "Status smlouvy"
def objectKey = object.getObjectKey();
def insightObject = objectFacade.loadObjectBean(objectKey)
int objectId = insightObject.getId()
----------------------------------
**// Here is the line I need help with
def inRef = objectFacade.findObjectInboundReferencedBeans(objectId)**
----------------------------------
def objectAttribute = objectFacade.loadObjectAttributeBean(objectId, attributeRef)
def objectAttributeValue = objectAttribute.getObjectAttributeValueBeans()[0].getValue()
log.warn(objectKey.toString())
log.warn(insightObject.toString())
log.warn(inRef)
I use this script also to get attribute value from Agreement object, which works fine.
I guess the problem is that I call the method on wrong object, but when I try to call in dirrectly on "insightObject" , I got the same error.
Thank you!
As answered on the Atlassian Community Page.
The method was removed with the release of Insight 5.1, see the upgrade notes here.
However, you can just use this to solve your issue:
def inRef = iqlFacade.findObjects(/object HAVING outboundReferences(Key = ${objectKey})/)
I have tried several different groovy script methods form various examples as I am not a coder, but have come close but no real success. I have thrown my hands up and am wondering if some smart person out there knows how to do this.
I simply need to show all total work logged for a specific link type of parent issues and their sub tasks to a single issue as a grand total. See diagram.
Correcting the posted answer:
This got answered for me from another community member here: https://community.atlassian.com/t5/Jira-Questions/JIRA-tally-all-logged-work-from-linked-issues-and-sub-tasks-to/qaq-p/1434260#U1435384
The script provided that worked for me was the following:
// Template: Duration (either of the 2)
import com.atlassian.jira.component.ComponentAccessor
def issueLinkmanager = ComponentAccessor.getIssueLinkManager()
def subtaskManager = ComponentAccessor.getSubTaskManager()
def workLogManager = ComponentAccessor.getWorklogManager()
def linkName = "Work"
def linkCollection = issueLinkmanager.getLinkCollectionOverrideSecurity(issue)
def linkedIssues = linkCollection?.getInwardIssues(linkName) //Inward or Outward? Verify and change if needed.
if (!linkedIssues) {
// no linked issues
return null
}
def totalTimeSpentFromWorkLinkedIssuesAndTheirSubtasks = []
for (def linkedIssue:linkedIssues) {
def worklogList = workLogManager.getByIssue(linkedIssue)
for (def worklog:worklogList) {
def timeSpent = worklog.getTimeSpent()
totalTimeSpentFromWorkLinkedIssuesAndTheirSubtasks.add(timeSpent)
}
def subTasks = subtaskManager.getSubTaskObjects(linkedIssue)
for (def subTask:subTasks) {
def worklogListSubTask = workLogManager.getByIssue(subTask)
for (def worklogSubTask:worklogListSubTask) {
def timeSpent = worklogSubTask.getTimeSpent()
totalTimeSpentFromWorkLinkedIssuesAndTheirSubtasks.add(timeSpent)
}
}
}
return totalTimeSpentFromWorkLinkedIssuesAndTheirSubtasks?.sum()
sqlalchemy and I'm trying to understand the finer workings of the way the objects work. I've got some test code that just seems to work differently than the tutorials and I am getting confused. I think this is a case of the tensorflow 1 vs 2 docs confusion happening
the code I posted, I'm told works for other people, and the last line of that is database.session.commit(), the code is the last code block.
This is a brand new Debian Stable VM with only VSCode, terminator and bpython installed beyond what is necessary for the application. THIS SHOULD WORK.
the database file is created but not populated. the tables are created but not columns or rows.
sqlite3 shell shows that nothing is in the database but the tables are there
database.session.flush()
does not add the stuff either
database.session.query(User).all()
also returns an empty thingamabob
and
database.session.query(User).filter(User.user_id)
returns : SQLAlchemy object has no attribute "query"
I'm trying to make a function that returns the user object based on its user_id and then change a variable in that user object using
object.field = "blorp"
I can make an object and access it like
user = User()
user.user_id
but for some strange reason, even though I have defaults set, it doesn't have those fields populated with those defaults. I have to explicitly define the fields during the declaration
but I can assign stuff like:
user.user_id = 2
this object returns ALL of the users right?
>>> asdf = database.session.query(User)
>>> asdf
<flask_sqlalchemy.BaseQuery object at 0x7f49aacff780>
the "all()" method returns an empty array for both class.query and database.session.query
>>> users = User.query.all()
>>> users
[]
>>> users = database.session.query(User).all()
>>> users
[]
Using the following test code:
from flask.config import Config
from flask import Flask, render_template, Response, Request ,Config
from flask_sqlalchemy import SQLAlchemy
HTTP_HOST = "gamebiscuits"
ADMIN_NAME = "Emperor of Sol"
ADMIN_PASSWORD = "password"
ADMIN_EMAIL = "game_admin"
DANGER_STRING= "TACOCAT"
class Config(object):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + HTTP_HOST + '.db'
SQLALCHEMY_TRACK_MODIFICATIONS = True
solar_empire_server = Flask(__name__ , template_folder="templates" )
solar_empire_server.config.from_object(Config)
database = SQLAlchemy(solar_empire_server)
def update_database(thing):
database.session.add(thing)
database.commit()
def user_by_id(id_of_user):
return User.query.filter_by(user_id = id_of_user).first()
#without the flask migrate module, you need to instantiate
# databases with default values. That module wont be loaded
# yet during the creation of a NEW game
class User(database.Model):
user_id = database.Column(database.Integer, default = 0, primary_key = True)
username = database.Column(database.String(64), default = "tourist", index=True, unique=True)
email = database.Column(database.String(120), default = DANGER_STRING , index=True, unique=True)
password_hash = database.Column(database.String(128), default = DANGER_STRING)
turns_run = database.Column(database.Integer, default = 0)
cash = database.Column(database.Integer, default = 1000)
def __repr__(self):
return '<User id:{} name: {} >'.format(self.user_id , self.username)
class UserShip(User):
ship_id = database.Column(database.String(128), default = "1")
ship_name = database.Column(database.String(128), default = "goodship moop")
def __repr__(self):
return '<User id:{} name: {} >'.format(self.ship_id , self.ship_name)
admin = User(username=ADMIN_NAME, user_id = 1, email=ADMIN_EMAIL , password_hash = ADMIN_PASSWORD)
guest = User(username='guest', user_id = 2, email='test#game.net' , password_hash = 'password')
user = User()
usership = UserShip()
adminship = UserShip()
guestship = UserShip()
database.create_all()
database.session.add(admin)
database.session.add(guest)
database.session.add(user)
database.session.add(usership)
database.session.add(adminship)
database.session.add(guestship)
database.session.commit()
Okay, so when you see default here it's going to be on INSERT (see the SQLAlchemy default documentation).
To quote the key part here:
Column INSERT and UPDATE defaults refer to functions that create a default value for a particular column in a row as an INSERT or UPDATE statement is proceeding against that row, in the case where no value was provided to the INSERT or UPDATE statement for that column.
So these defaults will only be initialized on adding to the database, flushing won't have any effect if an object that hasn't been added (session.add). So User() is only going to create an object, it will not create a DB row until you add (and flush / commit as necessary).
I am trying to retrieve a list of all instances of 'search' from a json response and set it so that any values that contains 'null' is changed to 0. However I am getting an error stating no such property: it for class. How can I fix this to ensure I get the code working so any instance of 'null' changes to 0?
import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def json = new JsonSlurper().parseText(response)
def resultItems = json.xxx.xxx.items
def resultSearchCostGroup = json.xxx.xxx.xxx.search
int totalSearchCostGroup = resultSearchCostGroup.flatten().collect(it ?:0 ).sum()
Your last line should read
int totalSearchCostGroup = resultSearchCostGroup.flatten().collect { it ?:0 }.sum()