From 1312a0491e6055cdb76c3163bdd8df96c3862203 Mon Sep 17 00:00:00 2001 From: Beth Skurrie Date: Mon, 14 Feb 2022 11:30:10 +1100 Subject: [PATCH] fix: handle DateTimes that come back from Sqlite as Strings Upgrading to ruby 2.7.5-alpine3.14 has changed something in Sqlite or Sequel --- .../api/decorators/format_date_time.rb | 10 +++++- .../api/decorators/format_date_time_spec.rb | 35 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 spec/lib/pact_broker/api/decorators/format_date_time_spec.rb diff --git a/lib/pact_broker/api/decorators/format_date_time.rb b/lib/pact_broker/api/decorators/format_date_time.rb index bfd81a9b3..5303a63be 100644 --- a/lib/pact_broker/api/decorators/format_date_time.rb +++ b/lib/pact_broker/api/decorators/format_date_time.rb @@ -2,8 +2,16 @@ module PactBroker module Api module Decorators module FormatDateTime + # Keep this in sync with Sequel.datetime_class. + # Needs to be upgraded from DateTime to Time as Time is deprecated + DATE_TIME_CLASS = DateTime + def self.call(date_time) - date_time.to_time.utc.to_datetime.xmlschema if date_time + if date_time.is_a?(String) + DATE_TIME_CLASS.strptime(date_time).to_time.utc.to_datetime.xmlschema + elsif date_time + date_time.to_time.utc.to_datetime.xmlschema if date_time + end end def format_date_time(date_time) diff --git a/spec/lib/pact_broker/api/decorators/format_date_time_spec.rb b/spec/lib/pact_broker/api/decorators/format_date_time_spec.rb new file mode 100644 index 000000000..8b148602e --- /dev/null +++ b/spec/lib/pact_broker/api/decorators/format_date_time_spec.rb @@ -0,0 +1,35 @@ +require "pact_broker/api/decorators/format_date_time" + +module PactBroker + module Api + module Decorators + module FormatDateTime + describe ".call" do + context "with a Time object" do + let(:date_time) { Time.parse("2022-02-14T15:18:00+14:00" )} + + it "converts the date to a string in utc" do + expect(FormatDateTime.call(date_time)).to eq "2022-02-14T01:18:00+00:00" + end + end + + context "with a DateTime object" do + let(:date_time) { DateTime.parse("2022-02-14T15:18:00+14:00" )} + + it "converts the date to a string in utc" do + expect(FormatDateTime.call(date_time)).to eq "2022-02-14T01:18:00+00:00" + end + end + + context "with a String - MySQL and Sqlite (as of the upgrade to Ruby 2.7.5) return date columns as strings. Postgres returns them as dates." do + let(:date_time) { "2022-02-14T15:18:00+14:00" } + + it "converts the date to a string in utc" do + expect(FormatDateTime.call(date_time)).to eq "2022-02-14T01:18:00+00:00" + end + end + end + end + end + end +end