From 4c4fc7b85bf4a6e540f24550c8306f4e0390a664 Mon Sep 17 00:00:00 2001 From: Bob Forma <1178544+bforma@users.noreply.github.com> Date: Thu, 1 Feb 2024 09:16:41 +0100 Subject: [PATCH] Add login method to test if credentials are valid --- lib/easee/client.rb | 7 ++++++ spec/easee/client_spec.rb | 50 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/lib/easee/client.rb b/lib/easee/client.rb index 8f908c1..7f4e838 100644 --- a/lib/easee/client.rb +++ b/lib/easee/client.rb @@ -20,6 +20,13 @@ def initialize( @encryptor = encryptor end + # https://developer.easee.cloud/reference/post_api-accounts-login + def login + with_error_handling do + request_access_token + end + end + # https://developer.easee.cloud/reference/post_api-chargers-id-unpair def unpair(charger_id:, pin_code:) post("/api/chargers/#{charger_id}/unpair", query: { pinCode: pin_code }) diff --git a/spec/easee/client_spec.rb b/spec/easee/client_spec.rb index 412655a..f14bd9d 100644 --- a/spec/easee/client_spec.rb +++ b/spec/easee/client_spec.rb @@ -184,6 +184,56 @@ end end + describe "#login" do + it "returns the access token when credentials are valid" do + user_name = "easee" + password = "money" + + stub_request(:post, "https://api.easee.cloud/api/accounts/login") + .with( + body: { userName: user_name, password: }.to_json, + ) + .to_return( + status: 200, + body: { accessToken: "T123" }.to_json, + headers: { "Content-Type": "application/json" }, + ) + + client = Easee::Client.new(user_name:, password:) + + expect(client.login).to eq("accessToken" => "T123") + end + + it "raises InvalidCredentials when the credentials are invalid" do + user_name = "test" + password = "wrong" + + stub_request(:post, "https://api.easee.cloud/api/accounts/login") + .with( + body: { userName: user_name, password: }.to_json, + ) + .to_return( + status: 400, + body: { + errorCode: 100, + errorCodeName: "InvalidUserPassword", + type: nil, + title: "Username or password is invalid", + status: 400, + detail: "[Empty in production]", + instance: nil, + extensions: {}, + }.to_json, + headers: { "Content-Type": "application/json" }, + ) + + client = Easee::Client.new(user_name:, password:) + + expect { client.login } + .to raise_error(Easee::Errors::InvalidCredentials) + end + end + describe "#pair" do it "pairs a new charger" do token_cache = ActiveSupport::Cache::MemoryStore.new