Tried this code but it wont return the expected output. The list that i have doesnt have single quote.
def curlCmd = sh(script: "<some curl cmd POST>", returnStdout:true).trim()
def parsedResponse = readJSON text: curlCmd
def response = parsedResponse['fruit']
// Output of response is [apple123, apple124, apple125]
def maxValue = response.max()
echo "maxValue: ${maxValue}"
Actual Output:
maxValue: []
Expected Output:
maxValue: [apple125]
This works fine:
def curlCmd = sh(script: "<some curl cmd POST>", returnStdout:true).trim()
def parsedResponse = readJSON text: curlCmd
def response = parsedResponse['fruit'] as ArrayList
// Output of response is [apple123, apple124, apple125]
def maxValue = Collections.max(response)
echo "maxValue: ${maxValue}"
Output:
maxValue: apple125
Related
I have the the following method in a RedisDriver class:
def get(self, key):
key_str = str(key)
try:
master = self.connection.master_for(self.service)
value = master.get(key_str)
except RedisError as err:
error_str = "Error while retrieving value from redis : " + str(err)
return {"success": False, "error": error_str}
I want to check is the error message is correct:
I tried the following:
#mock.patch("code.redis_driver.redis_sentinel")
#mock.patch("code.redis_driver.RedisDriver.get", side_effect=RedisError)
def test_redis_driver_delete(mocked_sentinel, mock_redis_sentinel):
mocked_master = mock.Mock()
mock_redis_sentinel.master_for.return_value = mocked_master
redis_driver = RedisDriver(mock_redis_sentinel)
result = redis_driver.get("test")
assert result == {"success": False, "error": "test"}
This does not work since an exception is raised:
E redis.exceptions.RedisError
Since this does not work I try the following:
#mock.patch("code.redis_driver.redis_sentinel")
#mock.patch("code.redis_driver.RedisDriver.get", side_effect=RedisError)
def test_redis_driver_delete(mocked_sentinel, mock_redis_sentinel):
mocked_master = mock.Mock()
mock_redis_sentinel.master_for.return_value = mocked_master
redis_driver = RedisDriver(mock_redis_sentinel)
with pytest.raises(RedisError) as exception:
result = redis_driver.get("test")
assert result == {"success": False, "error": str(exception)}
This always passes, whatever I set result to. How can I catch the expected output?
Solved it by mocking the whole class and use side_effect on the get method:
#mock.patch("code.redis_driver.RedisDriver")
def test_redis_driver_delete(mock_redis_sentinel):
mocked_master = mock.Mock()
mocked_master.get.side_effect = RedisError("error")
mock_redis_sentinel.master_for.return_value = mocked_master
redis_driver = RedisDriver(mock_redis_sentinel)
result = redis_driver.get("test")
assert result == {"success": False, "error": "Error while retrieving value from redis : error"}
Im unsure how to use Maps with a template engine. Can someone tell me what im doing wrong here?
def engine = new groovy.text.SimpleTemplateEngine()
def binding = [jobs:[[name:'job1',action:'build'], [name:'job2', action:'build']]]
def text = '''
println ${jobs}
println ${jobs[0].name}
${jobs}.each{ job ->
println "name " + job.name
}
'''
def template = engine.createTemplate(text).make(binding)
println template
produces this output
Result
println [[name:job1, action:build], [name:job2, action:build]]
println job1
[[name:job1, action:build], [name:job2, action:build]].each{ job ->
println "name " + job.name
}
The 2nd println shows job1 from this ${jobs[0].name} which looks good except I want to do that in the iterator, but I'm not sure what that each is showing me. I would expect to get
name job1
name job2
from the iterator. Any ideas how to do this?
all from documentation: https://docs.groovy-lang.org/latest/html/api/groovy/text/SimpleTemplateEngine.html
def engine = new groovy.text.SimpleTemplateEngine()
def binding = [jobs:[[name:'job1',action:'build'], [name:'job2', action:'build']]]
def text = '''
jobs[0].name = ${jobs[0].name}
<% jobs.each{ job -> %>\
name = ${job.name}
<%}%>
'''
def template = engine.createTemplate(text).make(binding)
println template
result:
jobs[0].name = job1
name = job1
name = job2
When i call the below function through API;
In both try and except conditions I have to keep log in separate table named api.log.
While the function enters in except condition, error occurs on creating record on api.log table
Here is the code:
#http.route('/tax_master',type="json",methodn ['POST'],auth="public",csrf=Falenter code herese)
def create_tax_master(self,**kw):
kw = http.request.params
obj_tax_master = request.env['tax.master']
obj_account_tax = request.env['account.tax']
flag = kw.get('flag')
vals = {}
result = False
if kw.get('name'):
vals['name'] = kw.get('name')
if kw.get('value'):
vals['value'] = kw.get('value')
if kw.get('scope'):
vals['scope'] = kw.get('scope')
if kw.get('is_excise'):
vals['is_excise'] = kw.get('is_excise')
if kw.get('description'):
vals['description'] = kw.get('description')
if kw.get('amount_type'):
vals['amount_type']= kw.get('amount_type')
if 'is_excise' in kw and kw.get('is_excise') not in [1,0]:
result = json.dumps({
"statusCode":02,
"statusDesc":"The value for the field is_excise should be 0 or 1"})
try:
if flag == 'create':
tax_id = obj_tax_master.sudo().create(vals).id
result = json.dumps({"id":tax_id,
"statusCode":01,
"statusDesc":"Successfully Created"
})
elif flag == 'write':
if kw.get('id'):
tax_id_rec = obj_tax_master.sudo().browse([int(kw.get('id'))])
if tax_id_rec.active == False:
result = json.dumps({
'statusCode': 02,
'statusDesc': 'The Tax is Archived.Updation is not possible now',
})
else:
tax_id_rec.sudo().write(vals)
tax_id = kw.get('id')
result = json.dumps({"id":tax_id,
"statusCode":01,
"statusDesc":"Successfully Updated"
})
else:
result = json.dumps({
'statusCode' : 02,
'statusDesc' : 'Please provide valid id to update the record',
})
elif flag == 'delete':
tax_id = obj_tax_master.sudo().browse(int(kw.get('id')))
if tax_id.active == False:
result = json.dumps({
'statusCode': 02,
'statusDesc': 'The record is already archived!!!',
})
else:
tax_id.write({'active':False})
taxes = obj_account_tax.sudo().search([('tax_master_id','=',kw.get('id'))])
for tax in taxes:
tax.write({'active':False})
result = json.dumps({
'statusCode' : 01,
'statusDesc' : 'The record is archived successfully!!!',
})
data = json.loads(result)
self.create_api_log('tax_master', flag, kw, data)
return data
except Exception,e:
result = json.dumps({'statusCode' : 02,'statusDesc' : str(e),})
data = json.loads(result)
self.create_api_log('tax_master', flag, kw, data)
return data
It is solved by using commit function.
I'm new to Devops and coding. I'm working on building a monitoring tool (grafana) with CloudWatch and Lambda.
I have a code which is not working properly. It pings the server. If it is returning 200 it will push 0 in the metrics and when the site is down it should push 1 but when I'm mentioning in the write metrics to write 1, instead of writing 1 its writing 100 and if I try to do any other values its greater than 100 its posting but less than 100 its just post 100.
Here is the code:
import boto3
import urllib2
def write_metric(value, metric):
d = boto3.client('cloudwatch')
d.put_metric_data(Namespace='WebsiteStatus',
MetricData=[
{
'MetricName':metric,
'Dimensions':[
{
'Name': 'Status',
'Value': 'WebsiteStatusCode',
},
],
'Value': value,
},
]
)
def check_site(url, metric):
STAT = 1
print("Checking %s " % url)
request = urllib2.Request("https://" +url)
try:
response = urllib2.urlopen(request)
response.close()
except urllib2.URLError as e:
if hasattr(e, 'code'):
print ("[Error:] Connection to %s failed with code: " %url +str(e.code))
STAT = 100
write_metric(STAT, metric)
if hasattr(e, 'reason'):
print ("[Error:] Connection to %s failed with code: " % url +str(e.reason))
STAT = 100
write_metric(STAT, metric)
except urllib2.HTTPError as e:
if hasattr(e, 'code'):
print ("[Error:] Connection to %s failed with code: " % url + str(e.code))
STAT = 100
write_metric(STAT, metric)
if hasattr(e, 'reason'):
print ("[Error:] Connection to %s failed with code: " % url + str(e.reason))
STAT = 100
write_metric(STAT, metric)
print('HTTPError!!!')
if STAT != 100:
STAT = response.getcode()
return STAT
def lambda_handler(event, context):
websiteurls = [
"website.com"
]
metricname = 'SiteAvailability'
for site in websiteurls:
r = check_site(site,metricname)
if r == 200:
print("Site %s is up" %site)
write_metric(0, metricname)
else:
print("[Error:] Site %s down" %site)
write_metric(1, metricname)
These lines:
STAT = 100
write_metric(STAT, metric)
will always send 100 as your value.
I try to do some stress test against my websocket server. On client side I run the following script from this site :
import time, sys
from twisted.internet import defer, reactor
from twisted.internet.defer import Deferred, returnValue, inlineCallbacks
from autobahn.twisted.websocket import connectWS, \
WebSocketClientFactory, \
WebSocketClientProtocol
class MassConnectProtocol(WebSocketClientProtocol):
didHandshake = False
def onOpen(self):
print("websocket connection opened")
self.factory.test.onConnected()
self.factory.test.protos.append(self)
self.didHandshake = True
class MassConnectFactory(WebSocketClientFactory):
protocol = MassConnectProtocol
def clientConnectionFailed(self, connector, reason):
if self.test.onFailed():
reactor.callLater(float(self.retrydelay)/1000., connector.connect)
def clientConnectionLost(self, connector, reason):
if self.test.onLost():
reactor.callLater(float(self.retrydelay)/1000., connector.connect)
class MassConnect:
def __init__(self, name, uri, connections, batchsize, batchdelay, retrydelay):
print('MassConnect init')
self.name = name
self.uri = uri
self.batchsize = batchsize
self.batchdelay = batchdelay
self.retrydelay = retrydelay
self.failed = 0
self.lost = 0
self.targetCnt = connections
self.currentCnt = 0
self.actual = 0
self.protos = []
def run(self):
print('MassConnect runned')
self.d = Deferred()
self.started = time.clock()
self.connectBunch()
return self.d
def onFailed(self):
self.failed += 1
sys.stdout.write("!")
return True
def onLost(self):
self.lost += 1
#sys.stdout.write("*")
return False
return True
def onConnected(self):
print("onconnected")
self.actual += 1
if self.actual % self.batchsize == 0:
sys.stdout.write(".")
if self.actual == self.targetCnt:
self.ended = time.clock()
duration = self.ended - self.started
print " connected %d clients to %s at %s in %s seconds (retries %d = failed %d + lost %d)" % (self.currentCnt, self.name, self.uri, duration, self.failed + self.lost, self.failed, self.lost)
result = {'name': self.name,
'uri': self.uri,
'connections': self.targetCnt,
'retries': self.failed + self.lost,
'lost': self.lost,
'failed': self.failed,
'duration': duration}
for p in self.protos:
p.sendClose()
#self.d.callback(result)
def connectBunch(self):
if self.currentCnt + self.batchsize < self.targetCnt:
c = self.batchsize
redo = True
else:
c = self.targetCnt - self.currentCnt
redo = False
for i in xrange(0, c):
factory = MassConnectFactory(self.uri)
factory.test = self
factory.retrydelay = self.retrydelay
connectWS(factory)
self.currentCnt += 1
if redo:
reactor.callLater(float(self.batchdelay)/1000., self.connectBunch)
class MassConnectTest:
def __init__(self, spec):
self.spec = spec
print('MassConnetest init')
#inlineCallbacks
def run(self):
print self.spec
res = []
for s in self.spec['servers']:
print s['uri']
t = MassConnect(s['name'],
s['uri'],
self.spec['options']['connections'],
self.spec['options']['batchsize'],
self.spec['options']['batchdelay'],
self.spec['options']['retrydelay'])
r = yield t.run()
res.append(r)
returnValue(res)
def startClient(spec, debug = False):
test = MassConnectTest(spec)
d = test.run()
return d
if __name__ == '__main__':
spec = {}
spec['servers'] = [{'name': 'test', 'uri':"ws://127.0.0.1:8080"} ]
spec['options'] ={'connections': 1000,'batchsize': 500, 'batchdelay': 1000, 'retrydelay': 200 }
startClient(spec,False)
But after running this script there are no connections established on the server side. Server seems to be configured properly, because when I connect to my server using different client side (for example web browser), it works fine and websocket connection is established. I also checked network sniffer and it seems that script doesn't produce any websocket connections.
What did I do wrong in this script?
The massconnect.py script you used was supposed to be invoked from another part of the autobahntestsuite, such as the wstest command:
$ echo '{"servers": [{"name": "test", "uri":"ws://127.0.0.1:8080"} ], "options": {"connections": 1000,"batchsize": 500, "batchdelay": 1000, "retrydelay": 200 }}' > spec.json
$ wstest -m massconnect --spec spec.json
If you want to copy massconnect directly, I think it's missing the command to start the Twisted deferred tasks:
if __name__ == '__main__':
spec = {}
spec['servers'] = [{'name': 'test', 'uri':"ws://127.0.0.1:8080"} ]
spec['options'] ={'connections': 1000,'batchsize': 500, 'batchdelay': 1000, 'retrydelay': 200 }
startClient(spec,False)
reactor.run() # <-- add this
And check your Python indentations, either some of them got corrupted when pasting here, or the original code had incorrect indentations in some class and function definitions.