Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

[#64347] calculated value model specs

Tobias Dillmann9eb195442233
diff --git a/app/models/custom_field/calculated_value.rb b/app/models/custom_field/calculated_value.rb
index afb6d1a004c..dd70e5ebf65 100644
--- a/app/models/custom_field/calculated_value.rb
+++ b/app/models/custom_field/calculated_value.rb
@@ -33,23 +33,10 @@
module CustomField::CalculatedValue
def validate_formula
return unless field_format_calculated_value?
+ # An empty formula is okay.
+ return if formula_string.blank?
- # List of allowed characters in a formula. This only performs a very basic validation.
- # Allowed characters are:
- # + - / * ( ) whitespace digits and decimal points
- # Additionally, the formula may contain references to custom fields in the form of `cf_123` where 123 is the ID of
- # the custom field.
- # Once this basic validation passes, the formula will be parsed and validated by Dentaku, which builds an AST
- # and ensures that the formula is really valid. A welcome side effect of the basic validation done here is that
- # it prevents built-in functions from being used in the formula, which we do not want to allow.
- allowed_chars = %w[+ - / * ( )] + [" "]
- split_pattern = /\s|(\+)|(-)|(\*)|(\()|(\))/
- pattern = /^(cf_\d+|\d+\.?\d*|\.\d+.|[#{allowed_chars.join}]+)$/
- valid_formula_string = formula_string.split(split_pattern).reject(&:empty?).all? do |token|
- token.match?(pattern)
- end
-
- errors.add(:formula, :invalid) unless valid_formula_string
+ errors.add(:formula, :invalid) unless formula_contains_only_allowed_characters?
# WP-64348: check for valid (i.e., visible & enabled) custom field references (see #cf_ids_used_in_formula)
@@ -61,21 +48,40 @@ module CustomField::CalculatedValue
def formula=(value)
if value.is_a?(String)
- super({ formula: value, referenced_custom_fields: cf_ids_used_in_formula })
+ super({ formula: value, referenced_custom_fields: cf_ids_used_in_formula(value) })
else
super
end
end
+ # Returns the formula as a string. Will return an empty string if the formula is not set.
def formula_string
- formula.is_a?(Hash) ? formula["formula"] : formula
+ formula.is_a?(Hash) ? formula.fetch("formula", "") : formula.to_s
end
private
+ def formula_contains_only_allowed_characters?
+ # List of allowed characters in a formula. This only performs a very basic validation.
+ # Allowed characters are:
+ # + - / * ( ) whitespace digits and decimal points
+ # Additionally, the formula may contain references to custom fields in the form of `cf_123` where 123 is the ID of
+ # the custom field.
+ # Once this basic validation passes, the formula will be parsed and validated by Dentaku, which builds an AST
+ # and ensures that the formula is really valid. A welcome side effect of the basic validation done here is that
+ # it prevents built-in functions from being used in the formula, which we do not want to allow.
+ allowed_chars = %w[+ - / * ( )] + [" "]
+ split_pattern = /\s|(\+)|(-)|(\/)|(\*)|(\()|(\))/
+ allowed_tokens = /^(cf_\d+|\d+\.?\d*|\.\d+.|[#{allowed_chars.join}]+)$/
+
+ formula_string.split(split_pattern).reject(&:empty?).all? do |token|
+ token.match?(allowed_tokens)
+ end
+ end
+
# Returns a list of custom field IDs used in the formula.
# For a formula like `2 + cf_12 + cf_4` it returns `[12, 4]`.
- def cf_ids_used_in_formula
- (formula_string || "").scan(/cf_(\d+)/).flatten.map(&:to_i)
+ def cf_ids_used_in_formula(formula_str = formula_string)
+ formula_str.scan(/cf_(\d+)/).flatten.map(&:to_i)
end
end
diff --git a/spec/factories/custom_field_factory.rb b/spec/factories/custom_field_factory.rb
index 0dcb1686805..b5ef114a7b7 100644
--- a/spec/factories/custom_field_factory.rb
+++ b/spec/factories/custom_field_factory.rb
@@ -81,6 +81,10 @@ FactoryBot.define do
field_format { "int" }
end
+ trait :calculated_value do
+ field_format { "calculated_value" }
+ end
+
trait :float do
field_format { "float" }
end
@@ -96,7 +100,7 @@ FactoryBot.define do
end
field_format { "list" }
multi_value { false }
- possible_values { ["A", "B", "C", "D", "E", "F", "G"] }
+ possible_values { %w[A B C D E F G] }
# update custom options default value from the default_option transient
# field for non-multiselect field
@@ -203,6 +207,7 @@ FactoryBot.define do
factory :string_project_custom_field, traits: [:string]
factory :text_project_custom_field, traits: [:text]
factory :integer_project_custom_field, traits: [:integer]
+ factory :calculated_value_project_custom_field, traits: [:calculated_value]
factory :float_project_custom_field, traits: [:float]
factory :date_project_custom_field, traits: [:date]
factory :list_project_custom_field, traits: [:list]
diff --git a/spec/models/custom_field/calculated_value_spec.rb b/spec/models/custom_field/calculated_value_spec.rb
new file mode 100644
index 00000000000..1c645a5a745
--- /dev/null
+++ b/spec/models/custom_field/calculated_value_spec.rb
@@ -0,0 +1,116 @@
+# frozen_string_literal: true
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See COPYRIGHT and LICENSE files for more details.
+#++
+
+require "spec_helper"
+
+RSpec.describe CustomField::CalculatedValue, with_flag: { calculated_value_project_attribute: true } do
+ context "when calculated value" do
+ subject(:custom_field) { create(:calculated_value_project_custom_field) }
+
+ describe "#formula=" do
+ it "splits formula and referenced custom fields on persist if given a string" do
+ formula = "1 * cf_7 + cf_42"
+ subject.formula = formula
+
+ expect(subject.formula).to eq({ "formula" => formula, "referenced_custom_fields" => [7, 42] })
+ end
+
+ it "omits referenced custom fields if none are given" do
+ formula = "2 + 3 * (8 / 7)"
+ subject.formula = formula
+
+ expect(subject.formula).to eq({ "formula" => formula, "referenced_custom_fields" => [] })
+ end
+ end
+
+ describe "#formula_string" do
+ it "returns an empty string if no formula is set" do
+ expect(subject.formula_string).to eq("")
+ end
+
+ it "returns the formula as a string" do
+ formula = "1 * cf_7 + cf_42"
+ subject.formula = formula
+
+ expect(subject.formula_string).to eq(formula)
+ end
+ end
+
+ describe "#validate_formula" do
+ let(:formula) { "" }
+
+ before do
+ subject.formula = formula
+ subject.validate_formula
+ end
+
+ context "with an empty formula" do
+ it "is valid" do
+ expect(subject).to be_valid
+ end
+ end
+
+ context "with a formula containing only allowed characters" do
+ let(:formula) { "1 / 2 + (3 * 4.5) - 0.0" }
+
+ it "is valid" do
+ expect(subject).to be_valid
+ end
+ end
+
+ context "with a formula containing forbidden characters" do
+ let(:formula) { "abc + 2" }
+
+ it "is invalid" do
+ expect(subject).not_to be_valid
+ expect(subject.errors[:formula]).to include("is invalid.")
+ end
+ end
+
+ context "with a formula that is not a valid equation" do
+ let(:formula) { "1 / + - 3" }
+
+ it "is invalid" do
+ expect(subject).not_to be_valid
+ expect(subject.errors[:formula]).to include("is invalid.")
+ end
+ end
+
+ context "with a formula that causes a division by zero error" do
+ let(:formula) { "1 / 0" }
+
+ it "is invalid" do
+ expect(subject).not_to be_valid
+ expect(subject.errors[:formula]).to include("is invalid.")
+ end
+ end
+ end
+ end
+end
diff --git a/spec/models/custom_field_spec.rb b/spec/models/custom_field_spec.rb
index 7607c938203..2b28935f2d6 100644
--- a/spec/models/custom_field_spec.rb
+++ b/spec/models/custom_field_spec.rb
@@ -485,6 +485,15 @@ RSpec.describe CustomField do
end
end
+ context "with a project calculated value cf" do
+ let(:field) { build_stubbed(:calculated_value_project_custom_field) }
+
+ it "is false" do
+ expect(field)
+ .not_to be_multi_value_possible
+ end
+ end
+
context "with a time_entry user cf" do
let(:field) { build_stubbed(:time_entry_custom_field, :user) }