Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update testing #8

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
AllCops:
DisplayCopNames: true

Lint/AmbiguousRegexpLiteral:
Enabled: false

Lint/UnusedMethodArgument:
Enabled: false

Metrics/AbcSize:
Enabled: false

Metrics/ClassLength:
Enabled: false

Metrics/LineLength:
Enabled: false

Metrics/MethodLength:
Enabled: false

Style/Documentation:
Enabled: false

Style/FileName:
Enabled: false

Style/IfUnlessModifier:
Enabled: false

Style/SpecialGlobalVars:
EnforcedStyle: use_perl_names

Style/StringLiterals:
EnforcedStyle: double_quotes
9 changes: 5 additions & 4 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
require "bundler/gem_tasks"
require "rspec/core/rake_task"
require "rubocop/rake_task"
require "github_changelog_generator/task"

RSpec::Core::RakeTask.new(:spec)


RuboCop::RakeTask.new(:rubocop)

GitHubChangelogGenerator::RakeTask.new :changelog do |config|
config.since_tag = 'v0.4.0'
config.future_release = 'v0.5.0'
config.since_tag = "v0.4.0"
config.future_release = "v0.5.0"
end

task default: :spec
task default: [:rubocop, :spec]
2 changes: 1 addition & 1 deletion lib/lita-stackstorm.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@

Lita::Handlers::Stackstorm.template_root File.expand_path(
File.join("..", "..", "templates"),
__FILE__
__FILE__
)
75 changes: 36 additions & 39 deletions lib/lita/handlers/stackstorm.rb
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
require 'json'
require 'net/http'
require 'yaml'
require "json"
require "net/http"
require "yaml"

class Array
def swap!(a,b)
def swap!(a, b)
self[a], self[b] = self[b], self[a]
self
end
end



module Lita
module Handlers
class Stackstorm < Handler
Expand Down Expand Up @@ -62,55 +60,55 @@ def stream_listen(payload)
if expired
authenticate
end
uri = URI("#{url_builder()}/stream")
Thread.new {
Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
uri = URI("#{url_builder}/stream")
Thread.new do
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http|
request = Net::HTTP::Get.new uri
request['X-Auth-Token'] = headers()['X-Auth-Token']
request['Content-Type'] = 'application/x-yaml'
request["X-Auth-Token"] = headers["X-Auth-Token"]
request["Content-Type"] = "application/x-yaml"
http.request request do |response|
io = StringIO.new
response.read_body do |chunk|
c = chunk.strip
if c.length > 0
unless c.empty?
io.write chunk
event = YAML.load(io.string)
if event['event'] =~ /st2\.announcement/
direct_post(event['data']['payload']['channel'],
event['data']['payload']['message'],
event['data']['payload']['user'])
if event["event"] =~ /st2\.announcement/
direct_post(event["data"]["payload"]["channel"],
event["data"]["payload"]["message"],
event["data"]["payload"]["user"])
end
io.reopen("")
end
end
end
end
}
end
end

def auth_builder
if Integer(config.auth_port) == 443 and config.url.start_with?('https')
if (Integer(config.auth_port) == 443) && config.url.start_with?("https")
"#{config.url}/auth"
else
"#{config.url}:#{config.auth_port}/v1"
end
end

def url_builder
if Integer(config.execution_port) == 443 and config.url.start_with?('https')
if (Integer(config.execution_port) == 443) && config.url.start_with?("https")
"#{config.url}/api"
else
"#{config.url}:#{config.execution_port}/v1"
end
end

def authenticate
resp = http.post("#{auth_builder()}/tokens") do |req|
resp = http.post("#{auth_builder}/tokens") do |req|
req.body = {}
req.headers['Authorization'] = http.set_authorization_header(:basic_auth, config.username, config.password)
req.headers["Authorization"] = http.set_authorization_header(:basic_auth, config.username, config.password)
end
self.class.token = JSON.parse(resp.body)['token']
self.class.expires = JSON.parse(resp.body)['expiry']
self.class.token = JSON.parse(resp.body)["token"]
self.class.expires = JSON.parse(resp.body)["expiry"]
resp
end

Expand All @@ -122,20 +120,20 @@ def call_alias(msg)
found = ""
redis.scan_each do |a|
possible = /#{a}/.match(command)
if not possible.nil?
unless possible.nil?
found = a
break
end
end

jobject = JSON.parse(redis.get(found))
payload = {
name: jobject['object']['name'],
format: jobject['format'],
name: jobject["object"]["name"],
format: jobject["format"],
command: command,
user: msg.user.name,
source_channel: 'chatops',
notification_channel: 'lita'
source_channel: "chatops",
notification_channel: "lita"
}
s = make_post_request("/aliasexecution", payload)
j = JSON.parse(s.body)
Expand All @@ -150,21 +148,21 @@ def list(msg)
if expired
authenticate
end
redis.keys.each {|k| redis.del k }
redis.keys.each { |k| redis.del k }
s = make_request("/actionalias", "")
if JSON.parse(s.body).empty?
msg.reply "No Action Aliases Registered"
else
j = JSON.parse(s.body)
a = ""
extra_params = '(\\s+(\\S+)\\s*=("([\\s\\S]*?)"|\'([\\s\\S]*?)\'|({[\\s\\S]*?})|(\\S+))\\s*)*'
j.take_while{|i| i['enabled'] }.each do |command|
command['formats'].each do |format|
j.take_while { |i| i["enabled"] }.each do |command|
command["formats"].each do |format|
f = format.gsub(/(\s*){{\s*\S+\s*=\s*(?:({.+?}|.+?))\s*}}(\s*)/, '\\s*([\\S]+)?\\s*')
f = f.gsub(/\s*{{.+?}}\s*/, '\\s*([\\S]+?)\\s*')
f = "^\\s*#{f}#{extra_params}\\s*$"
redis.set(f, {format: format, object: command}.to_json)
a+= "#{format} -> #{command['description']}\n"
redis.set(f, { format: format, object: command }.to_json)
a += "#{format} -> #{command['description']}\n"
end
end
msg.reply a
Expand All @@ -187,27 +185,26 @@ def expired
end

def make_request(path, body)
resp = http.get("#{url_builder()}#{path}") do |req|
resp = http.get("#{url_builder}#{path}") do |req|
req.headers = headers
req.body = body.to_json if not body.empty?
req.body = body.to_json unless body.empty?
end
resp
end

def make_post_request(path, body)
resp = http.post("#{url_builder()}#{path}") do |req|
resp = http.post("#{url_builder}#{path}") do |req|
req.body = {}
req.headers = headers
req.body = body.to_json
end
resp
end


def headers
headers = {}
headers['Content-Type'] = 'application/json'
headers['X-Auth-Token'] = "#{self.class.token}"
headers["Content-Type"] = "application/json"
headers["X-Auth-Token"] = self.class.token.to_s
headers
end

Expand Down
2 changes: 2 additions & 0 deletions lita-stackstorm.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,6 @@ Gem::Specification.new do |spec|
spec.add_development_dependency "fakeredis"
spec.add_development_dependency "github_changelog_generator"
spec.add_development_dependency "bump"
spec.add_development_dependency "rubocop"
spec.add_development_dependency "webmock"
end
65 changes: 62 additions & 3 deletions spec/lita/handlers/stackstorm_spec.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,66 @@
require "spec_helper"

describe Lita::Handlers::Stackstorm, lita_handler: true do
it { is_expected.to route_command('st2 login').to(:login) }
it { is_expected.to route_command('st2 list').to(:list) }
it { is_expected.to route_command('!pack info').to(:call_alias) }
let(:token_resp) do
{
"token" => "asdf"
}.to_json
end

let(:actionalias_resp) do
[
{
description: "Get StackStorm pack information via ChatOps",
extra: {},
ack: {},
enabled: true,
name: "pack_info",
result: {},
formats: [
"pack info {{pack}}"
],
action_ref: "packs.info",
pack: "packs",
ref: "packs.pack_info",
id: "583f0fc4e1382364659cc740",
uid: "action:packs:pack_info"
}
].to_json
end

before do
registry.configure do |config|
config.handlers.stackstorm.url = "https://st2.example.local"
config.handlers.stackstorm.username = "dummy_user"
config.handlers.stackstorm.password = "dummy_pass"
end

allow(described_class).to receive(:new).and_return(subject)

stub_request(:post, "https://st2.example.local:9100/v1/tokens")
.with(
headers: {
"Authorization" => "Basic ZHVtbXlfdXNlcjpkdW1teV9wYXNz"
}
)
.to_return(status: 200, body: token_resp, headers: {})
end

it { is_expected.to route_command("st2 login").to(:login) }
it { is_expected.to route_command("st2 list").to(:list) }
it { is_expected.to route_command("!pack info").to(:call_alias) }

it "should reply correctly to 'st2 list'" do
stub_request(:get, "https://st2.example.local:9101/v1/actionalias")
.with(
headers: {
"Content-Type" => "application/json",
"X-Auth-Token" => "asdf"
}
)
.to_return(status: 200, body: actionalias_resp, headers: {})

send_command("st2 list")
expect(replies.last).to include("pack info {{pack}} -> Get StackStorm pack information via ChatOps")
end
end
3 changes: 2 additions & 1 deletion spec/spec_helper.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
require "lita-stackstorm"
require "lita/rspec"
require 'fakeredis/rspec'
require "fakeredis/rspec"
require "webmock/rspec"

# A compatibility mode is provided for older plugins upgrading from Lita 3. Since this plugin
# was generated with Lita 4, the compatibility mode should be left disabled.
Expand Down