From ac4bec8c901a1428b7195e47a7397faad2a03245 Mon Sep 17 00:00:00 2001 From: Radek Janicki <13463966+rdk08@users.noreply.github.com> Date: Fri, 10 Nov 2023 09:47:06 +0100 Subject: [PATCH] Adjust validation --- lib/plausible/helpers/value.ex | 2 +- test/plausible/helpers/value_test.exs | 56 +++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 test/plausible/helpers/value_test.exs diff --git a/lib/plausible/helpers/value.ex b/lib/plausible/helpers/value.ex index 93005005dafa..dcf3be392a8e 100644 --- a/lib/plausible/helpers/value.ex +++ b/lib/plausible/helpers/value.ex @@ -1,5 +1,5 @@ defmodule Plausible.ValueHelpers do - @prefix_pattern "[a-zA-Z]+" + @prefix_pattern "[a-zA-Z]+(-[a-zA-Z]+)*" @id_pattern "\\d+" @uuid_pattern "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}" diff --git a/test/plausible/helpers/value_test.exs b/test/plausible/helpers/value_test.exs new file mode 100644 index 000000000000..a34b1f9e45e9 --- /dev/null +++ b/test/plausible/helpers/value_test.exs @@ -0,0 +1,56 @@ +defmodule Plausible.ValueHelpersTest do + use Plausible.DataCase + use Timex + + alias Plausible.ValueHelpers + + describe "validate/2" do + test "returns prefixed value (with integer id) if it is successfully validated" do + value = "vendor-123" + + assert ValueHelpers.validate(value, type: :prefixed_id) == value + end + + test "returns prefixed value (with uuid) if it is successfully validated" do + value = "vendor-c2b5da86-851a-4aee-ac48-19d6069556c5" + + assert ValueHelpers.validate(value, type: :prefixed_id) == value + end + + test "returns prefixed value (with multipart prefix and id) if it is successfully validated" do + value = "other-vendor-prefix-456" + + assert ValueHelpers.validate(value, type: :prefixed_id) == value + end + + test "returns prefixed value (with multipart prefix and uuid id) if it is successfully validated" do + value = "other-vendor-prefix-782f008a-b478-4aac-8448-16569a0e4501" + + assert ValueHelpers.validate(value, type: :prefixed_id) == value + end + + test "returns nil if value does not match predefined pattern (missing id)" do + value = "vendor" + + refute ValueHelpers.validate(value, type: :prefixed_id) + end + + test "returns nil if value does not match predefined pattern (wrong id)" do + value = "vendor-123d" + + refute ValueHelpers.validate(value, type: :prefixed_id) + end + + test "returns nil if value does not match predefined pattern (wrong uuid)" do + value = "vendor-abcdefgh123-782f008a-b478-4aac-8448" + + refute ValueHelpers.validate(value, type: :prefixed_id) + end + + test "returns nil if value does not match predefined pattern (no prefix)" do + value = "123" + + refute ValueHelpers.validate(value, type: :prefixed_id) + end + end +end