repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/kramdown-1.17.0/lib/kramdown/parser/kramdown/footnote.rb | _vendor/ruby/2.6.0/gems/kramdown-1.17.0/lib/kramdown/parser/kramdown/footnote.rb | # -*- coding: utf-8 -*-
#
#--
# Copyright (C) 2009-2016 Thomas Leitner <t_leitner@gmx.at>
#
# This file is part of kramdown which is licensed under the MIT.
#++
#
require 'kramdown/parser/kramdown/extensions'
require 'kramdown/parser/kramdown/blank_line'
require 'kramdown/parser/kramdown/codeblock'
module Kramdown
module Parser
class Kramdown
FOOTNOTE_DEFINITION_START = /^#{OPT_SPACE}\[\^(#{ALD_ID_NAME})\]:\s*?(.*?\n#{CODEBLOCK_MATCH})/
# Parse the foot note definition at the current location.
def parse_footnote_definition
start_line_number = @src.current_line_number
@src.pos += @src.matched_size
el = Element.new(:footnote_def, nil, nil, :location => start_line_number)
parse_blocks(el, @src[2].gsub(INDENT, ''))
warning("Duplicate footnote name '#{@src[1]}' on line #{start_line_number} - overwriting") if @footnotes[@src[1]]
@tree.children << new_block_el(:eob, :footnote_def)
(@footnotes[@src[1]] = {})[:content] = el
@footnotes[@src[1]][:eob] = @tree.children.last
true
end
define_parser(:footnote_definition, FOOTNOTE_DEFINITION_START)
FOOTNOTE_MARKER_START = /\[\^(#{ALD_ID_NAME})\]/
# Parse the footnote marker at the current location.
def parse_footnote_marker
start_line_number = @src.current_line_number
@src.pos += @src.matched_size
fn_def = @footnotes[@src[1]]
if fn_def
if fn_def[:eob]
update_attr_with_ial(fn_def[:eob].attr, fn_def[:eob].options[:ial] || {})
fn_def[:attr] = fn_def[:eob].attr
fn_def[:options] = fn_def[:eob].options
fn_def.delete(:eob)
end
fn_def[:marker] ||= []
fn_def[:marker].push(Element.new(:footnote, fn_def[:content], fn_def[:attr],
fn_def[:options].merge(:name => @src[1], :location => start_line_number)))
@tree.children << fn_def[:marker].last
else
warning("Footnote definition for '#{@src[1]}' not found on line #{start_line_number}")
add_text(@src.matched)
end
end
define_parser(:footnote_marker, FOOTNOTE_MARKER_START, '\[')
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/kramdown-1.17.0/lib/kramdown/parser/kramdown/html.rb | _vendor/ruby/2.6.0/gems/kramdown-1.17.0/lib/kramdown/parser/kramdown/html.rb | # -*- coding: utf-8 -*-
#
#--
# Copyright (C) 2009-2016 Thomas Leitner <t_leitner@gmx.at>
#
# This file is part of kramdown which is licensed under the MIT.
#++
#
require 'kramdown/parser/html'
module Kramdown
module Parser
class Kramdown
include Kramdown::Parser::Html::Parser
# Mapping of markdown attribute value to content model. I.e. :raw when "0", :default when "1"
# (use default content model for the HTML element), :span when "span", :block when block and
# for everything else +nil+ is returned.
HTML_MARKDOWN_ATTR_MAP = {"0" => :raw, "1" => :default, "span" => :span, "block" => :block}
TRAILING_WHITESPACE = /[ \t]*\n/
def handle_kramdown_html_tag(el, closed, handle_body)
if @block_ial
el.options[:ial] = @block_ial
@block_ial = nil
end
content_model = if @tree.type != :html_element || @tree.options[:content_model] != :raw
(@options[:parse_block_html] ? HTML_CONTENT_MODEL[el.value] : :raw)
else
:raw
end
if val = HTML_MARKDOWN_ATTR_MAP[el.attr.delete('markdown')]
content_model = (val == :default ? HTML_CONTENT_MODEL[el.value] : val)
end
@src.scan(TRAILING_WHITESPACE) if content_model == :block
el.options[:content_model] = content_model
el.options[:is_closed] = closed
if !closed && handle_body
if content_model == :block
if !parse_blocks(el)
warning("Found no end tag for '#{el.value}' (line #{el.options[:location]}) - auto-closing it")
end
elsif content_model == :span
curpos = @src.pos
if @src.scan_until(/(?=<\/#{el.value}\s*>)/mi)
add_text(extract_string(curpos...@src.pos, @src), el)
@src.scan(HTML_TAG_CLOSE_RE)
else
add_text(@src.rest, el)
@src.terminate
warning("Found no end tag for '#{el.value}' (line #{el.options[:location]}) - auto-closing it")
end
else
parse_raw_html(el, &method(:handle_kramdown_html_tag))
end
@src.scan(TRAILING_WHITESPACE) unless (@tree.type == :html_element && @tree.options[:content_model] == :raw)
end
end
HTML_BLOCK_START = /^#{OPT_SPACE}<(#{REXML::Parsers::BaseParser::UNAME_STR}|\?|!--|\/)/
# Parse the HTML at the current position as block-level HTML.
def parse_block_html
line = @src.current_line_number
if result = @src.scan(HTML_COMMENT_RE)
@tree.children << Element.new(:xml_comment, result, nil, :category => :block, :location => line)
@src.scan(TRAILING_WHITESPACE)
true
elsif result = @src.scan(HTML_INSTRUCTION_RE)
@tree.children << Element.new(:xml_pi, result, nil, :category => :block, :location => line)
@src.scan(TRAILING_WHITESPACE)
true
else
if result = @src.check(/^#{OPT_SPACE}#{HTML_TAG_RE}/) && !HTML_SPAN_ELEMENTS.include?(@src[1].downcase)
@src.pos += @src.matched_size
handle_html_start_tag(line, &method(:handle_kramdown_html_tag))
Kramdown::Parser::Html::ElementConverter.convert(@root, @tree.children.last) if @options[:html_to_native]
true
elsif result = @src.check(/^#{OPT_SPACE}#{HTML_TAG_CLOSE_RE}/) && !HTML_SPAN_ELEMENTS.include?(@src[1].downcase)
name = @src[1].downcase
if @tree.type == :html_element && @tree.value == name
@src.pos += @src.matched_size
throw :stop_block_parsing, :found
else
false
end
else
false
end
end
end
define_parser(:block_html, HTML_BLOCK_START)
HTML_SPAN_START = /<(#{REXML::Parsers::BaseParser::UNAME_STR}|\?|!--|\/)/
# Parse the HTML at the current position as span-level HTML.
def parse_span_html
line = @src.current_line_number
if result = @src.scan(HTML_COMMENT_RE)
@tree.children << Element.new(:xml_comment, result, nil, :category => :span, :location => line)
elsif result = @src.scan(HTML_INSTRUCTION_RE)
@tree.children << Element.new(:xml_pi, result, nil, :category => :span, :location => line)
elsif result = @src.scan(HTML_TAG_CLOSE_RE)
warning("Found invalidly used HTML closing tag for '#{@src[1]}' on line #{line}")
add_text(result)
elsif result = @src.scan(HTML_TAG_RE)
tag_name = @src[1]
tag_name.downcase! if HTML_ELEMENT[tag_name.downcase]
if HTML_BLOCK_ELEMENTS.include?(tag_name)
warning("Found block HTML tag '#{tag_name}' in span-level text on line #{line}")
add_text(result)
return
end
attrs = parse_html_attributes(@src[2], line, HTML_ELEMENT[tag_name])
attrs.each {|name, value| value.gsub!(/\n+/, ' ')}
do_parsing = (HTML_CONTENT_MODEL[tag_name] == :raw || @tree.options[:content_model] == :raw ? false : @options[:parse_span_html])
if val = HTML_MARKDOWN_ATTR_MAP[attrs.delete('markdown')]
if val == :block
warning("Cannot use block-level parsing in span-level HTML tag (line #{line}) - using default mode")
elsif val == :span
do_parsing = true
elsif val == :default
do_parsing = HTML_CONTENT_MODEL[tag_name] != :raw
elsif val == :raw
do_parsing = false
end
end
el = Element.new(:html_element, tag_name, attrs, :category => :span, :location => line,
:content_model => (do_parsing ? :span : :raw), :is_closed => !!@src[4])
@tree.children << el
stop_re = /<\/#{Regexp.escape(tag_name)}\s*>/
stop_re = Regexp.new(stop_re.source, Regexp::IGNORECASE) if HTML_ELEMENT[tag_name]
if !@src[4] && !HTML_ELEMENTS_WITHOUT_BODY.include?(el.value)
if parse_spans(el, stop_re, (do_parsing ? nil : [:span_html]))
@src.scan(stop_re)
else
warning("Found no end tag for '#{el.value}' (line #{line}) - auto-closing it")
add_text(@src.rest, el)
@src.terminate
end
end
Kramdown::Parser::Html::ElementConverter.convert(@root, el) if @options[:html_to_native]
else
add_text(@src.getch)
end
end
define_parser(:span_html, HTML_SPAN_START, '<')
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_plugins/read_time.rb | _plugins/read_time.rb | # Calculates reading time based on the formula used by Medium
# https://medium.com/the-story/read-time-and-you-bc2048ab620c
# Usage: {{ page.content | read_time }}
# Note: this requires img tags to be in the form of <img ... />. If you're
# using this on a post listing page, make sure to markdownify the post content
# first.
module ReadTimeFilter
def read_time(input)
words_per_minute = 245
# number of seconds per image to start at, default is 12s
img_time_max = 12
# time per image will decrease by 1 for every image, to a minimum
# of this time, default is 3s
img_time_min = 3
strings = input.split(/<img.* \/>/)
seconds = (strings.join(" ").split.size.to_f / (words_per_minute / 60))
# number of images minus one for correct number of iterations
(strings.size - 2).times do |i|
t = (img_time_max - i)
image_time = t > img_time_min ? t : img_time_min
seconds = seconds + image_time
end
minutes = (seconds / 60).ceil
"#{minutes} min read"
end
end
Liquid::Template.register_filter(ReadTimeFilter) | ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_plugins/authors.rb | _plugins/authors.rb | module Authors
class Generator < Jekyll::Generator
def generate(site)
# Small method to augment the author object with posts authored by them.
authors_posts = Hash.new { |h, k| h[k] = [] }
site.posts.docs.each do |post|
post['authors'].each do |author_id|
authors_posts[author_id] << post
end
end
site.data['authors'].each do |author_id, data|
data['posts'] = authors_posts[author_id]
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/.scripts/bump-version.rb | .scripts/bump-version.rb | file_name = "lib/fastlane/plugin/sentry/version.rb"
text = File.read(file_name)
# The whitespaces are important :P
new_contents = text.gsub(/^ VERSION = ".*"/, " VERSION = \"#{ARGV[1]}\"")
File.open(file_name, "w") {|file| file.puts new_contents }
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/spec/sentry_helper_spec.rb | spec/sentry_helper_spec.rb | describe Fastlane::Helper::SentryHelper do
describe "call_sentry_cli" do
it "uses cli path resolved by find_and_check_sentry_cli_path!" do
sentry_cli_path = 'path'
options = {}
expect(Fastlane::Helper::SentryHelper).to receive(:find_and_check_sentry_cli_path!).with(options).and_return(sentry_cli_path)
expect(Open3).to receive(:popen3).with({ 'SENTRY_PIPELINE' => "sentry-fastlane-plugin/#{Fastlane::Sentry::VERSION}" }, "#{sentry_cli_path} subcommand")
Fastlane::Helper::SentryHelper.call_sentry_cli(options, ["subcommand"])
end
end
describe "find_and_check_sentry_cli_path!" do
it "uses sentry_cli_path passed to check its version" do
bundled_sentry_cli_path = Fastlane::Helper::SentryHelper.bundled_sentry_cli_path
bundled_sentry_cli_version = `#{bundled_sentry_cli_path} --version`
sentry_cli_path = 'path'
expect(described_class).to receive(:`).with("#{bundled_sentry_cli_path} --version").and_return(bundled_sentry_cli_path) # Called for bundled version
expect(described_class).to receive(:`).with("#{sentry_cli_path} --version").and_return(bundled_sentry_cli_version) # Called sentry_cli_path parmeter
expect(Fastlane::Helper::SentryHelper.find_and_check_sentry_cli_path!({ sentry_cli_path: sentry_cli_path })).to eq(sentry_cli_path)
end
end
describe "bundled_sentry_cli_path" do
it "mac universal" do
expect(OS).to receive(:mac?).and_return(true)
expexted_file_path = File.expand_path('../bin/sentry-cli-Darwin-universal', File.dirname(__FILE__))
expect(Fastlane::Helper::SentryHelper.bundled_sentry_cli_path).to eq(expexted_file_path)
end
it "windows 64 bit" do
expect(OS).to receive(:mac?).and_return(false)
expect(OS).to receive(:windows?).and_return(true)
expect(OS).to receive(:bits).and_return(64)
expexted_file_path = File.expand_path('../bin/sentry-cli-Windows-x86_64.exe', File.dirname(__FILE__))
expect(Fastlane::Helper::SentryHelper.bundled_sentry_cli_path).to eq(expexted_file_path)
end
it "windows 32 bit" do
expect(OS).to receive(:mac?).and_return(false)
expect(OS).to receive(:windows?).and_return(true)
expect(OS).to receive(:bits).and_return(32)
expexted_file_path = File.expand_path('../bin/sentry-cli-Windows-i686.exe', File.dirname(__FILE__))
expect(Fastlane::Helper::SentryHelper.bundled_sentry_cli_path).to eq(expexted_file_path)
end
it "linux 64 bit" do
expect(OS).to receive(:mac?).and_return(false)
expect(OS).to receive(:windows?).and_return(false)
expect(OS).to receive(:bits).and_return(64)
expexted_file_path = File.expand_path('../bin/sentry-cli-Linux-x86_64', File.dirname(__FILE__))
expect(Fastlane::Helper::SentryHelper.bundled_sentry_cli_path).to eq(expexted_file_path)
end
it "linux 32 bit" do
expect(OS).to receive(:mac?).and_return(false)
expect(OS).to receive(:windows?).and_return(false)
expect(OS).to receive(:bits).and_return(32)
expexted_file_path = File.expand_path('../bin/sentry-cli-Linux-i686', File.dirname(__FILE__))
expect(Fastlane::Helper::SentryHelper.bundled_sentry_cli_path).to eq(expexted_file_path)
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/spec/sentry_upload_build_spec.rb | spec/sentry_upload_build_spec.rb | module Fastlane
module Actions
def self.lane_context
@lane_context ||= {}
end
end
module SharedValues
XCODEBUILD_ARCHIVE ||= :xcodebuild_archive
end
end
describe Fastlane do
describe Fastlane::FastFile do
describe "upload build" do
# We'll use the dSYM file as a mock xcarchive for testing since we need an existing file
let(:mock_xcarchive_path) { File.absolute_path './assets/SwiftExample.app.dSYM.zip' }
it "fails when xcarchive path does not exist" do
non_existent_path = './assets/NonExistent.xcarchive'
expect do
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_build(
auth_token: 'test-token',
org_slug: 'test-org',
project_slug: 'test-project',
xcarchive_path: '#{non_existent_path}')
end").runner.execute(:test)
end.to raise_error("Could not find xcarchive at path '#{non_existent_path}'")
end
it "fails when file is not an xcarchive" do
# Mock a file that exists but doesn't have .xcarchive extension
invalid_archive_path = './assets/test.zip'
allow(File).to receive(:exist?).and_call_original
expect(File).to receive(:exist?).with(invalid_archive_path).and_return(true)
expect do
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_build(
auth_token: 'test-token',
org_slug: 'test-org',
project_slug: 'test-project',
xcarchive_path: '#{invalid_archive_path}')
end").runner.execute(:test)
end.to raise_error("Path '#{invalid_archive_path}' is not an xcarchive")
end
it "calls sentry-cli with basic parameters" do
# Mock the file to have .xcarchive extension
mock_path = './assets/Test.xcarchive'
allow(File).to receive(:exist?).with(mock_path).and_return(true)
allow(File).to receive(:extname).with(mock_path).and_return('.xcarchive')
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(
anything,
["build", "upload", anything]
).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_build(
auth_token: 'test-token',
org_slug: 'test-org',
project_slug: 'test-project',
xcarchive_path: '#{mock_path}')
end").runner.execute(:test)
end
it "uses SharedValues::XCODEBUILD_ARCHIVE as default if xcarchive_path is not provided" do
require 'fastlane'
mock_path = './assets/Test.xcarchive'
# Set the shared value on the correct module BEFORE parsing the lane
Fastlane::Actions.lane_context[Fastlane::Actions::SharedValues::XCODEBUILD_ARCHIVE] = mock_path
# Stubs for file checks
allow(File).to receive(:exist?).with(mock_path).and_return(true)
allow(File).to receive(:exist?).with("").and_return(false)
allow(File).to receive(:extname).with(mock_path).and_return('.xcarchive')
allow(File).to receive(:extname).with("").and_return('')
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(
anything,
["build", "upload", anything]
).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_build(
auth_token: 'test-token',
org_slug: 'test-org',
project_slug: 'test-project')
end").runner.execute(:test)
end
it "calls sentry-cli with git parameters when provided" do
mock_path = './assets/Test.xcarchive'
allow(File).to receive(:exist?).with(mock_path).and_return(true)
allow(File).to receive(:extname).with(mock_path).and_return('.xcarchive')
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(
anything,
["build", "upload", anything, "--head-sha", "abc123", "--base-sha", "def456", "--vcs-provider", "github", "--head-repo-name", "test/repo", "--base-repo-name", "test/repo", "--head-ref", "feature", "--base-ref", "main", "--pr-number", "123", "--build-configuration", "Release"]
).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_build(
auth_token: 'test-token',
org_slug: 'test-org',
project_slug: 'test-project',
xcarchive_path: '#{mock_path}',
head_sha: 'abc123',
base_sha: 'def456',
vcs_provider: 'github',
head_repo_name: 'test/repo',
base_repo_name: 'test/repo',
head_ref: 'feature',
base_ref: 'main',
pr_number: '123',
build_configuration: 'Release')
end").runner.execute(:test)
end
it "reads git parameters from environment variables when set" do
mock_path = './assets/Test.xcarchive'
allow(File).to receive(:exist?).with(mock_path).and_return(true)
allow(File).to receive(:extname).with(mock_path).and_return('.xcarchive')
# Set environment variables
allow(ENV).to receive(:[]).and_call_original
allow(ENV).to receive(:[]).with('SENTRY_HEAD_SHA').and_return('env_abc123')
allow(ENV).to receive(:[]).with('SENTRY_BASE_SHA').and_return('env_def456')
allow(ENV).to receive(:[]).with('SENTRY_VCS_PROVIDER').and_return('env_gitlab')
allow(ENV).to receive(:[]).with('SENTRY_HEAD_REPO_NAME').and_return('env_test/repo')
allow(ENV).to receive(:[]).with('SENTRY_BASE_REPO_NAME').and_return('env_base/repo')
allow(ENV).to receive(:[]).with('SENTRY_HEAD_REF').and_return('env_feature')
allow(ENV).to receive(:[]).with('SENTRY_BASE_REF').and_return('env_main')
allow(ENV).to receive(:[]).with('SENTRY_PR_NUMBER').and_return('env_456')
allow(ENV).to receive(:[]).with('SENTRY_BUILD_CONFIGURATION').and_return('env_Debug')
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(
anything,
["build", "upload", anything, "--head-sha", "env_abc123", "--base-sha", "env_def456", "--vcs-provider", "env_gitlab", "--head-repo-name", "env_test/repo", "--base-repo-name", "env_base/repo", "--head-ref", "env_feature", "--base-ref", "env_main", "--pr-number", "env_456", "--build-configuration", "env_Debug"]
).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_build(
auth_token: 'test-token',
org_slug: 'test-org',
project_slug: 'test-project',
xcarchive_path: '#{mock_path}')
end").runner.execute(:test)
end
it "prefers explicit parameters over environment variables" do
mock_path = './assets/Test.xcarchive'
allow(File).to receive(:exist?).with(mock_path).and_return(true)
allow(File).to receive(:extname).with(mock_path).and_return('.xcarchive')
# Set environment variables
allow(ENV).to receive(:[]).and_call_original
allow(ENV).to receive(:[]).with('SENTRY_HEAD_SHA').and_return('env_should_not_be_used')
allow(ENV).to receive(:[]).with('SENTRY_BASE_SHA').and_return('env_should_not_be_used')
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(
anything,
["build", "upload", anything, "--head-sha", "explicit_abc123", "--base-sha", "explicit_def456"]
).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_build(
auth_token: 'test-token',
org_slug: 'test-org',
project_slug: 'test-project',
xcarchive_path: '#{mock_path}',
head_sha: 'explicit_abc123',
base_sha: 'explicit_def456')
end").runner.execute(:test)
end
it "uses mixed explicit parameters and environment variables" do
mock_path = './assets/Test.xcarchive'
allow(File).to receive(:exist?).with(mock_path).and_return(true)
allow(File).to receive(:extname).with(mock_path).and_return('.xcarchive')
# Set some environment variables
allow(ENV).to receive(:[]).and_call_original
allow(ENV).to receive(:[]).with('SENTRY_VCS_PROVIDER').and_return('env_github')
allow(ENV).to receive(:[]).with('SENTRY_PR_NUMBER').and_return('env_789')
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(
anything,
["build", "upload", anything, "--head-sha", "explicit_abc123", "--vcs-provider", "env_github", "--pr-number", "env_789"]
).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_build(
auth_token: 'test-token',
org_slug: 'test-org',
project_slug: 'test-project',
xcarchive_path: '#{mock_path}',
head_sha: 'explicit_abc123')
end").runner.execute(:test)
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/spec/sentry_set_commits_spec.rb | spec/sentry_set_commits_spec.rb | describe Fastlane do
describe Fastlane::FastFile do
describe "set commits" do
it "accepts app_identifier" do
allow(CredentialsManager::AppfileConfig).to receive(:try_fetch_value).with(:app_identifier).and_return(false)
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "set-commits", "app.idf@1.0"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_set_commits(
version: '1.0',
app_identifier: 'app.idf')
end").runner.execute(:test)
end
it "accepts build" do
allow(CredentialsManager::AppfileConfig).to receive(:try_fetch_value).with(:app_identifier).and_return(false)
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "set-commits", "1.0+123"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_set_commits(
version: '1.0',
build: '123')
end").runner.execute(:test)
end
it "does not prepend app_identifier if not specified" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "set-commits", "1.0"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_set_commits(
version: '1.0')
end").runner.execute(:test)
end
it "includes --auto when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "set-commits", "1.0", "--auto"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_set_commits(
version: '1.0',
auto: true)
end").runner.execute(:test)
end
it "omits --auto when not present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "set-commits", "1.0"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_set_commits(
version: '1.0')
end").runner.execute(:test)
end
it "omits --auto when false" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "set-commits", "1.0"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_set_commits(
version: '1.0',
auto: false)
end").runner.execute(:test)
end
it "includes --clear when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "set-commits", "1.0", "--clear"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_set_commits(
version: '1.0',
clear: true)
end").runner.execute(:test)
end
it "omits --clear when not present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "set-commits", "1.0"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_set_commits(
version: '1.0')
end").runner.execute(:test)
end
it "omits --clear when false" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "set-commits", "1.0"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_set_commits(
version: '1.0',
clear: false)
end").runner.execute(:test)
end
it "includes --commit when given" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "set-commits", "1.0", "--commit", "abc"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_set_commits(
version: '1.0',
commit: 'abc')
end").runner.execute(:test)
end
it "omits --commit when not not given" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "set-commits", "1.0"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_set_commits(
version: '1.0')
end").runner.execute(:test)
end
it "includes --ignore-missing when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "set-commits", "1.0", "--ignore-missing"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_set_commits(
version: '1.0',
ignore_missing: true)
end").runner.execute(:test)
end
it "omits --ignore-missing when not present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "set-commits", "1.0"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_set_commits(
version: '1.0')
end").runner.execute(:test)
end
it "omits --ignore-missing when false" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "set-commits", "1.0"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_set_commits(
version: '1.0',
ignore_missing: false)
end").runner.execute(:test)
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/spec/sentry_config_spec.rb | spec/sentry_config_spec.rb | describe Fastlane::Helper::SentryConfig do
describe "fallback .sentryclirc" do
it "auth failing calling sentry-cli info" do
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["info", "--config-status-json"]).and_return("{\"auth\":{\"type\":null,\"successful\":false}}")
expect(Fastlane::Helper::SentryConfig.fallback_sentry_cli_auth({})).to be_falsey
end
end
describe "parse_api_params" do
it "does not set env if no value" do
Fastlane::Helper::SentryConfig.parse_api_params({ api_key: 'fixture-api-key' })
expect(ENV['SENTRY_LOG_LEVEL']).to be_nil
end
it "sets debug env if Fastlane is set to verbose" do
FastlaneCore::Globals.verbose = true
Fastlane::Helper::SentryConfig.parse_api_params({ api_key: 'fixture-api-key' })
expect(ENV['SENTRY_LOG_LEVEL']).to eq('debug')
end
it "sets trace env" do
Fastlane::Helper::SentryConfig.parse_api_params({ api_key: 'fixture-api-key', log_level: 'trace' })
expect(ENV['SENTRY_LOG_LEVEL']).to eq('trace')
end
it "sets debug env" do
Fastlane::Helper::SentryConfig.parse_api_params({ api_key: 'fixture-api-key', log_level: 'debug' })
expect(ENV['SENTRY_LOG_LEVEL']).to eq('debug')
end
it "sets info env" do
Fastlane::Helper::SentryConfig.parse_api_params({ api_key: 'fixture-api-key', log_level: 'info' })
expect(ENV['SENTRY_LOG_LEVEL']).to eq('info')
end
it "sets warn env" do
Fastlane::Helper::SentryConfig.parse_api_params({ api_key: 'fixture-api-key', log_level: 'warn' })
expect(ENV['SENTRY_LOG_LEVEL']).to eq('warn')
end
it "sets error env" do
Fastlane::Helper::SentryConfig.parse_api_params({ api_key: 'fixture-api-key', log_level: 'error' })
expect(ENV['SENTRY_LOG_LEVEL']).to eq('error')
end
it "raise error on invalid log_level" do
expect do
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
api_key: 'fixture-api-key',
log_level: 'unknown'
)
end").runner.execute(:test)
end.to raise_error("Invalid log level 'unknown'")
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/spec/sentry_debug_files_upload_spec.rb | spec/sentry_debug_files_upload_spec.rb | describe Fastlane do
describe Fastlane::FastFile do
describe "debug-files upload" do
it "includes --path if present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path'
)
end").runner.execute(:test)
end
it "supports mupltiple paths as array" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "fixture-path-2"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: ['fixture-path', 'fixture-path-2']
)
end").runner.execute(:test)
end
it "supports mupltiple paths as comma seperated values" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "fixture-path-2"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path,fixture-path-2'
)
end").runner.execute(:test)
end
it "includes --path fallback if not present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "."]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload()
end").runner.execute(:test)
end
it "includes --type for value dsym" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--type", "dsym"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
type: 'dsym'
)
end").runner.execute(:test)
end
it "includes --type for value elf" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--type", "elf"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
type: 'elf'
)
end").runner.execute(:test)
end
it "includes --type for value breakpad" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--type", "breakpad"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
type: 'breakpad'
)
end").runner.execute(:test)
end
it "includes --type for value pdb" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--type", "pdb"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
type: 'pdb'
)
end").runner.execute(:test)
end
it "includes --type for value pe" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--type", "pe"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
type: 'pe'
)
end").runner.execute(:test)
end
it "includes --type for value sourcebundle" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--type", "sourcebundle"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
type: 'sourcebundle'
)
end").runner.execute(:test)
end
it "includes --type for value bcsymbolmap" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--type", "bcsymbolmap"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
type: 'bcsymbolmap'
)
end").runner.execute(:test)
end
it "fails with unknown --type value" do
dsym_path_1 = File.absolute_path './assets/this_does_not_exist.app.dSYM.zip'
expect do
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
type: 'unknown'
)
end").runner.execute(:test)
end.to raise_error("Invalid value 'unknown'")
end
it "includes --no_unwind when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--no-unwind"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
no_unwind: true
)
end").runner.execute(:test)
end
it "includes --no_debug when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--no-debug"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
no_debug: true
)
end").runner.execute(:test)
end
it "includes --no_sources when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--no-sources"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
no_sources: true
)
end").runner.execute(:test)
end
it "includes --ids if present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--ids", "fixture-ids"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
ids: 'fixture-ids'
)
end").runner.execute(:test)
end
it "includes --require_all when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--require-all"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
require_all: true
)
end").runner.execute(:test)
end
it "includes --symbol_maps if present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--symbol-maps", "fixture-symbol_maps"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
symbol_maps: 'fixture-symbol_maps'
)
end").runner.execute(:test)
end
it "includes --derived_data when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--derived-data"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
derived_data: true
)
end").runner.execute(:test)
end
it "includes --no_zips when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--no-zips"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
no_zips: true
)
end").runner.execute(:test)
end
it "includes --info_plist if present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--info-plist", "fixture-info_plist"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
info_plist: 'fixture-info_plist'
)
end").runner.execute(:test)
end
it "includes --no_reprocessing when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--no-reprocessing"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
no_reprocessing: true
)
end").runner.execute(:test)
end
it "includes --force_foreground when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--force-foreground"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
force_foreground: true
)
end").runner.execute(:test)
end
it "includes --include_sources when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--include-sources"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
include_sources: true
)
end").runner.execute(:test)
end
it "dont include --include_sources when false" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
include_sources: false
)
end").runner.execute(:test)
end
it "includes --wait when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--wait"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
wait: true
)
end").runner.execute(:test)
end
it "includes --upload_symbol_maps when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["debug-files", "upload", "fixture-path", "--upload-symbol-maps"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_debug_files_upload(
path: 'fixture-path',
upload_symbol_maps: true
)
end").runner.execute(:test)
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/spec/sentry_upload_dsym_spec.rb | spec/sentry_upload_dsym_spec.rb | describe Fastlane do
describe Fastlane::FastFile do
describe "upload dsym" do
it "fails with API key and auth token" do
dsym_path_1 = File.absolute_path './assets/SwiftExample.app.dSYM.zip'
expect do
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dsym(
org_slug: 'some_org',
api_key: 'something123',
auth_token: 'something123',
project_slug: 'some_project',
dsym_path: '#{dsym_path_1}')
end").runner.execute(:test)
end.to raise_error("Both API key and authentication token found for SentryAction given, please only give one")
end
it "fails with invalid dsym path" do
dsym_path_1 = File.absolute_path './assets/this_does_not_exist.app.dSYM.zip'
expect do
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dsym(
org_slug: 'some_org',
api_key: 'something123',
project_slug: 'some_project',
dsym_path: '#{dsym_path_1}')
end").runner.execute(:test)
end.to raise_error("Could not find Path to your symbols file at path '#{dsym_path_1}'")
end
it "should add bcsymbols to sentry-cli call" do
dsym_path_1 = File.absolute_path './assets/SwiftExample.app.dSYM.zip'
allow(File).to receive(:exist?).and_call_original
expect(File).to receive(:exist?).with("1.bcsymbol").and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dsym", "--symbol-maps", "1.bcsymbol", dsym_path_1]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dsym(
org_slug: 'some_org',
api_key: 'something123',
project_slug: 'some_project',
symbol_maps: '1.bcsymbol',
dsym_path: '#{dsym_path_1}')
end").runner.execute(:test)
end
it "multiple dsym paths" do
dsym_path_1 = File.absolute_path './assets/SwiftExample.app.dSYM.zip'
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dsym", dsym_path_1, dsym_path_1]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dsym(
org_slug: 'some_org',
api_key: 'something123',
project_slug: 'some_project',
dsym_paths: ['#{dsym_path_1}', '#{dsym_path_1}'])
end").runner.execute(:test)
end
it "Info.plist should exist" do
dsym_path_1 = File.absolute_path './assets/SwiftExample.app.dSYM.zip'
allow(File).to receive(:exist?).and_call_original
expect(File).to receive(:exist?).with("Info.plist").and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dsym", "--info-plist", "Info.plist", dsym_path_1]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dsym(
org_slug: 'some_org',
api_key: 'something123',
project_slug: 'some_project',
dsym_paths: ['#{dsym_path_1}'],
info_plist: 'Info.plist')
end").runner.execute(:test)
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/spec/sentry_check_cli_installed_spec.rb | spec/sentry_check_cli_installed_spec.rb | describe Fastlane do
describe Fastlane::FastFile do
describe "check cli installed" do
it "success when find_and_check_sentry_cli_path passes" do
expect(Fastlane::Helper::SentryHelper).to receive(:find_and_check_sentry_cli_path!).and_return('path')
Fastlane::FastFile.new.parse("lane :test do
sentry_check_cli_installed()
end").runner.execute(:test)
end
it "raise error on invalid sentry_cli_path" do
path = 'invalid_cli_path'
expect(FastlaneCore::Helper).to receive(:executable?).and_return(false)
expect do
Fastlane::FastFile.new.parse("lane :test do
sentry_check_cli_installed(
sentry_cli_path: '#{path}'
)
end").runner.execute(:test)
end.to raise_error("'#{path}' is not executable")
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/spec/sentry_upload_sourcemap_spec.rb | spec/sentry_upload_sourcemap_spec.rb | describe Fastlane do
describe Fastlane::FastFile do
describe "upload_sourcemap" do
it "fails with invalid sourcemap path" do
sourcemap_path = File.absolute_path './assets/this_does_not_exist.js.map'
expect do
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_sourcemap(
org_slug: 'some_org',
api_key: 'something123',
project_slug: 'some_project',
sourcemap: '#{sourcemap_path}')
end").runner.execute(:test)
end.to raise_error("Could not find sourcemap at path '#{sourcemap_path}'")
end
it "does not require dist to be specified" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["sourcemaps", "upload", "--release", "app.idf@1.0", "1.map", "--no-rewrite"]).and_return(true)
allow(File).to receive(:exist?).and_call_original
expect(File).to receive(:exist?).with("1.map").and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_sourcemap(
org_slug: 'some_org',
api_key: 'something123',
project_slug: 'some_project',
version: '1.0',
sourcemap: '1.map',
app_identifier: 'app.idf')
end").runner.execute(:test)
end
it "accepts app_identifier" do
allow(CredentialsManager::AppfileConfig).to receive(:try_fetch_value).with(:app_identifier).and_return(false)
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["sourcemaps", "upload", "--release", "app.idf@1.0", "1.map", "--no-rewrite", "--dist", "dem"]).and_return(true)
allow(File).to receive(:exist?).and_call_original
expect(File).to receive(:exist?).with("1.map").and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_sourcemap(
org_slug: 'some_org',
api_key: 'something123',
project_slug: 'some_project',
version: '1.0',
dist: 'dem',
sourcemap: '1.map',
app_identifier: 'app.idf')
end").runner.execute(:test)
end
it "accepts build" do
allow(CredentialsManager::AppfileConfig).to receive(:try_fetch_value).with(:app_identifier).and_return(false)
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["sourcemaps", "upload", "--release", "1.0+123", "1.map", "--no-rewrite", "--dist", "dem"]).and_return(true)
allow(File).to receive(:exist?).and_call_original
expect(File).to receive(:exist?).with("1.map").and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_sourcemap(
org_slug: 'some_org',
api_key: 'something123',
project_slug: 'some_project',
version: '1.0',
dist: 'dem',
sourcemap: '1.map',
build: '123')
end").runner.execute(:test)
end
it "uses input value for strip_prefix" do
allow(CredentialsManager::AppfileConfig).to receive(:try_fetch_value).with(:app_identifier).and_return(false)
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["sourcemaps", "upload", "--release", "app.idf@1.0", "1.map", "--no-rewrite", "--strip-prefix", "/Users/get-sentry/semtry-fastlane-plugin", "--dist", "dem"]).and_return(true)
allow(File).to receive(:exist?).and_call_original
expect(File).to receive(:exist?).with("1.map").and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_sourcemap(
org_slug: 'some_org',
api_key: 'something123',
project_slug: 'some_project',
version: '1.0',
dist: 'dem',
sourcemap: '1.map',
app_identifier: 'app.idf',
strip_prefix: '/Users/get-sentry/semtry-fastlane-plugin',
app_identifier: 'app.idf')
end").runner.execute(:test)
end
it "accepts strip_common_prefix" do
allow(CredentialsManager::AppfileConfig).to receive(:try_fetch_value).with(:app_identifier).and_return(false)
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["sourcemaps", "upload", "--release", "app.idf@1.0", "1.map", "--no-rewrite", "--strip-common-prefix", "--dist", "dem"]).and_return(true)
allow(File).to receive(:exist?).and_call_original
expect(File).to receive(:exist?).with("1.map").and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_sourcemap(
org_slug: 'some_org',
api_key: 'something123',
project_slug: 'some_project',
version: '1.0',
dist: 'dem',
sourcemap: '1.map',
strip_common_prefix: true,
app_identifier: 'app.idf')
end").runner.execute(:test)
end
it "does not prepend strip_common_prefix if not specified" do
allow(CredentialsManager::AppfileConfig).to receive(:try_fetch_value).with(:app_identifier).and_return(false)
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["sourcemaps", "upload", "--release", "app.idf@1.0", "1.map", "--no-rewrite", "--dist", "dem"]).and_return(true)
allow(File).to receive(:exist?).and_call_original
expect(File).to receive(:exist?).with("1.map").and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_sourcemap(
org_slug: 'some_org',
api_key: 'something123',
project_slug: 'some_project',
version: '1.0',
dist: 'dem',
sourcemap: '1.map',
app_identifier: 'app.idf')
end").runner.execute(:test)
end
it "does not prepend app_identifier if not specified" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["sourcemaps", "upload", "--release", "1.0", "1.map", "--no-rewrite", "--dist", "dem"]).and_return(true)
allow(File).to receive(:exist?).and_call_original
expect(File).to receive(:exist?).with("1.map").and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_sourcemap(
org_slug: 'some_org',
api_key: 'something123',
project_slug: 'some_project',
version: '1.0',
dist: 'dem',
sourcemap: '1.map')
end").runner.execute(:test)
end
it "default --no-rewrite is omitted when 'rewrite' is specified" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["sourcemaps", "upload", "--release", "1.0", "1.map", "--dist", "dem"]).and_return(true)
allow(File).to receive(:exist?).and_call_original
expect(File).to receive(:exist?).with("1.map").and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_sourcemap(
org_slug: 'some_org',
api_key: 'something123',
project_slug: 'some_project',
version: '1.0',
dist: 'dem',
sourcemap: '1.map',
rewrite: true)
end").runner.execute(:test)
end
it "accepts multiple source maps as an array" do
allow(CredentialsManager::AppfileConfig).to receive(:try_fetch_value).with(:app_identifier).and_return(false)
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["sourcemaps", "upload", "--release", "app.idf@1.0", "1.bundle", "1.map", "--no-rewrite", "--dist", "dem"]).and_return(true)
allow(File).to receive(:exist?).and_call_original
expect(File).to receive(:exist?).with("1.bundle").and_return(true)
expect(File).to receive(:exist?).with("1.map").and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_sourcemap(
org_slug: 'some_org',
api_key: 'something123',
project_slug: 'some_project',
version: '1.0',
dist: 'dem',
sourcemap: ['1.bundle', '1.map'],
app_identifier: 'app.idf')
end").runner.execute(:test)
end
it "accepts multiple source maps as a comma-separated string" do
allow(CredentialsManager::AppfileConfig).to receive(:try_fetch_value).with(:app_identifier).and_return(false)
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["sourcemaps", "upload", "--release", "app.idf@1.0", "1.bundle", "1.map", "--no-rewrite", "--dist", "dem"]).and_return(true)
allow(File).to receive(:exist?).and_call_original
expect(File).to receive(:exist?).with("1.bundle").and_return(true)
expect(File).to receive(:exist?).with("1.map").and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_sourcemap(
org_slug: 'some_org',
api_key: 'something123',
project_slug: 'some_project',
version: '1.0',
dist: 'dem',
sourcemap: '1.bundle,1.map',
app_identifier: 'app.idf')
end").runner.execute(:test)
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/spec/sentry_create_release_spec.rb | spec/sentry_create_release_spec.rb | describe Fastlane do
describe Fastlane::FastFile do
describe "create release" do
it "accepts app_identifier" do
allow(CredentialsManager::AppfileConfig).to receive(:try_fetch_value).with(:app_identifier).and_return(false)
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "new", "app.idf@1.0"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_create_release(
version: '1.0',
app_identifier: 'app.idf')
end").runner.execute(:test)
end
it "accepts build" do
allow(CredentialsManager::AppfileConfig).to receive(:try_fetch_value).with(:app_identifier).and_return(false)
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "new", "1.0+123"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_create_release(
version: '1.0',
build: '123')
end").runner.execute(:test)
end
it "does not prepend app_identifier if not specified" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "new", "1.0"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_create_release(
version: '1.0')
end").runner.execute(:test)
end
it "adds --finalize if set to true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "new", "1.0", "--finalize"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_create_release(
version: '1.0',
finalize: true)
end").runner.execute(:test)
end
it "does not add --finalize if not set" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "new", "1.0"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_create_release(
version: '1.0')
end").runner.execute(:test)
end
it "does not add --finalize if set to false" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "new", "1.0"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_create_release(
version: '1.0',
finalize: false)
end").runner.execute(:test)
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/spec/sentry_finalize_release_spec.rb | spec/sentry_finalize_release_spec.rb | describe Fastlane do
describe Fastlane::FastFile do
describe "finalize release" do
it "accepts app_identifier" do
allow(CredentialsManager::AppfileConfig).to receive(:try_fetch_value).with(:app_identifier).and_return(false)
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "finalize", "app.idf@1.0"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_finalize_release(
version: '1.0',
app_identifier: 'app.idf')
end").runner.execute(:test)
end
it "accepts build" do
allow(CredentialsManager::AppfileConfig).to receive(:try_fetch_value).with(:app_identifier).and_return(false)
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "finalize", "1.0+123"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_finalize_release(
version: '1.0',
build: '123')
end").runner.execute(:test)
end
it "does not prepend app_identifier if not specified" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "finalize", "1.0"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_finalize_release(
version: '1.0')
end").runner.execute(:test)
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/spec/sentry_upload_proguard_spec.rb | spec/sentry_upload_proguard_spec.rb | describe Fastlane do
describe Fastlane::FastFile do
describe "upload proguard" do
it "fails with API key and auth token" do
mapping_path = File.absolute_path './assets/AndroidExample.mapping.txt'
expect do
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_proguard(
org_slug: 'some_org',
api_key: 'something123',
auth_token: 'something123',
project_slug: 'some_project',
mapping_path: '#{mapping_path}')
end").runner.execute(:test)
end.to raise_error("Both API key and authentication token found for SentryAction given, please only give one")
end
it "fails with invalid mapping path" do
mapping_path = File.absolute_path './assets/this.does.not.exist.mapping.txt'
expect do
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_proguard(
org_slug: 'some_org',
api_key: 'something123',
project_slug: 'some_project',
mapping_path: '#{mapping_path}')
end").runner.execute(:test)
end.to raise_error("Could not find your mapping file at path '#{mapping_path}'")
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/spec/sentry_upload_dif_spec.rb | spec/sentry_upload_dif_spec.rb | describe Fastlane do
describe Fastlane::FastFile do
describe "upload-dif" do
it "includes --path if present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path'
)
end").runner.execute(:test)
end
it "supports mupltiple paths as array" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "fixture-path-2"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: ['fixture-path', 'fixture-path-2']
)
end").runner.execute(:test)
end
it "supports mupltiple paths as comma seperated values" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "fixture-path-2"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path,fixture-path-2'
)
end").runner.execute(:test)
end
it "includes --path fallback if not present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "."]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif()
end").runner.execute(:test)
end
it "includes --type for value dsym" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--type", "dsym"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
type: 'dsym'
)
end").runner.execute(:test)
end
it "includes --type for value elf" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--type", "elf"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
type: 'elf'
)
end").runner.execute(:test)
end
it "includes --type for value breakpad" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--type", "breakpad"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
type: 'breakpad'
)
end").runner.execute(:test)
end
it "includes --type for value pdb" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--type", "pdb"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
type: 'pdb'
)
end").runner.execute(:test)
end
it "includes --type for value pe" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--type", "pe"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
type: 'pe'
)
end").runner.execute(:test)
end
it "includes --type for value sourcebundle" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--type", "sourcebundle"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
type: 'sourcebundle'
)
end").runner.execute(:test)
end
it "includes --type for value bcsymbolmap" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--type", "bcsymbolmap"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
type: 'bcsymbolmap'
)
end").runner.execute(:test)
end
it "fails with unknown --type value" do
dsym_path_1 = File.absolute_path './assets/this_does_not_exist.app.dSYM.zip'
expect do
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
type: 'unknown'
)
end").runner.execute(:test)
end.to raise_error("Invalid value 'unknown'")
end
it "includes --no_unwind when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--no-unwind"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
no_unwind: true
)
end").runner.execute(:test)
end
it "includes --no_debug when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--no-debug"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
no_debug: true
)
end").runner.execute(:test)
end
it "includes --no_sources when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--no-sources"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
no_sources: true
)
end").runner.execute(:test)
end
it "includes --ids if present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--ids", "fixture-ids"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
ids: 'fixture-ids'
)
end").runner.execute(:test)
end
it "includes --require_all when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--require-all"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
require_all: true
)
end").runner.execute(:test)
end
it "includes --symbol_maps if present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--symbol-maps", "fixture-symbol_maps"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
symbol_maps: 'fixture-symbol_maps'
)
end").runner.execute(:test)
end
it "includes --derived_data when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--derived-data"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
derived_data: true
)
end").runner.execute(:test)
end
it "includes --no_zips when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--no-zips"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
no_zips: true
)
end").runner.execute(:test)
end
it "includes --info_plist if present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--info-plist", "fixture-info_plist"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
info_plist: 'fixture-info_plist'
)
end").runner.execute(:test)
end
it "includes --no_reprocessing when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--no-reprocessing"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
no_reprocessing: true
)
end").runner.execute(:test)
end
it "includes --force_foreground when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--force-foreground"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
force_foreground: true
)
end").runner.execute(:test)
end
it "includes --include_sources when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--include-sources"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
include_sources: true
)
end").runner.execute(:test)
end
it "dont include --include_sources when false" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
include_sources: false
)
end").runner.execute(:test)
end
it "includes --wait when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--wait"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
wait: true
)
end").runner.execute(:test)
end
it "includes --upload_symbol_maps when true" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["upload-dif", "fixture-path", "--upload-symbol-maps"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_upload_dif(
path: 'fixture-path',
upload_symbol_maps: true
)
end").runner.execute(:test)
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/spec/sentry_create_deploy_spec.rb | spec/sentry_create_deploy_spec.rb | describe Fastlane do
describe Fastlane::FastFile do
describe "create deploy" do
it "accepts app_identifier" do
allow(CredentialsManager::AppfileConfig).to receive(:try_fetch_value).with(:app_identifier).and_return(false)
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "deploys", "app.idf@1.0", "new", "--env", "staging"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_create_deploy(
version: '1.0',
app_identifier: 'app.idf',
env: 'staging')
end").runner.execute(:test)
end
it "accepts build" do
allow(CredentialsManager::AppfileConfig).to receive(:try_fetch_value).with(:app_identifier).and_return(false)
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "deploys", "1.0+123", "new", "--env", "staging"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_create_deploy(
version: '1.0',
build: '123',
env: 'staging')
end").runner.execute(:test)
end
it "does not prepend app_identifier if not specified" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "deploys", "1.0", "new", "--env", "staging"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_create_deploy(
version: '1.0',
env: 'staging')
end").runner.execute(:test)
end
it "includes --name if present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "deploys", "1.0", "new", "--env", "staging", "--name", "fixture-name"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_create_deploy(
version: '1.0',
env: 'staging',
name: 'fixture-name')
end").runner.execute(:test)
end
it "includes --url if present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "deploys", "1.0", "new", "--env", "staging", "--url", "http://www.sentry.io"]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_create_deploy(
version: '1.0',
env: 'staging',
deploy_url: 'http://www.sentry.io')
end").runner.execute(:test)
end
it "includes --started and --finished if present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "deploys", "1.0", "new", "--env", "staging", "--started", 1622630647, "--finished", 1622630700]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_create_deploy(
version: '1.0',
env: 'staging',
started: 1622630647,
finished: 1622630700)
end").runner.execute(:test)
end
it "includes --started if present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "deploys", "1.0", "new", "--env", "staging", "--started", 1622630647]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_create_deploy(
version: '1.0',
env: 'staging',
started: 1622630647)
end").runner.execute(:test)
end
it "includes --finished if present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "deploys", "1.0", "new", "--env", "staging", "--finished", 1622630700]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_create_deploy(
version: '1.0',
env: 'staging',
finished: 1622630700)
end").runner.execute(:test)
end
it "includes --time if present" do
expect(Fastlane::Helper::SentryConfig).to receive(:parse_api_params).and_return(true)
expect(Fastlane::Helper::SentryHelper).to receive(:call_sentry_cli).with(anything, ["releases", "deploys", "1.0", "new", "--env", "staging", "--time", 180]).and_return(true)
Fastlane::FastFile.new.parse("lane :test do
sentry_create_deploy(
version: '1.0',
env: 'staging',
time: 180)
end").runner.execute(:test)
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/spec/spec_helper.rb | spec/spec_helper.rb | $LOAD_PATH.unshift File.expand_path('../lib', __dir__)
# This module is only used to check the environment is currently a testing env
module SpecHelper
end
require 'fastlane' # to import the Action super class
require 'fastlane/plugin/sentry' # import the actual plugin
Fastlane.load_actions # load other actions (in case your plugin calls other actions or shared values)
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/lib/fastlane/plugin/sentry.rb | lib/fastlane/plugin/sentry.rb | require 'fastlane/plugin/sentry/version'
module Fastlane
module Sentry
# Return all .rb files inside the "actions" and "helper" directory
def self.all_classes
Dir[File.expand_path('**/{actions,helper}/*.rb', File.dirname(__FILE__))]
end
end
end
# By default we want to import all available actions and helpers
# A plugin can contain any number of actions and plugins
Fastlane::Sentry.all_classes.each do |current|
require current
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/lib/fastlane/plugin/sentry/version.rb | lib/fastlane/plugin/sentry/version.rb | module Fastlane
module Sentry
VERSION = "1.36.0"
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/lib/fastlane/plugin/sentry/actions/sentry_upload_sourcemap.rb | lib/fastlane/plugin/sentry/actions/sentry_upload_sourcemap.rb | module Fastlane
module Actions
class SentryUploadSourcemapAction < Action
def self.run(params)
require 'shellwords'
Helper::SentryConfig.parse_api_params(params)
version = params[:version]
version = "#{params[:app_identifier]}@#{params[:version]}" if params[:app_identifier]
version = "#{version}+#{params[:build]}" if params[:build]
sourcemaps = params[:sourcemap]
command = [
"sourcemaps",
"upload",
"--release",
version
]
command += sourcemaps
command.push('--no-rewrite') unless params[:rewrite]
command.push('--strip-prefix').push(params[:strip_prefix]) if params[:strip_prefix]
command.push('--strip-common-prefix') if params[:strip_common_prefix]
command.push('--url-prefix').push(params[:url_prefix]) unless params[:url_prefix].nil?
command.push('--dist').push(params[:dist]) unless params[:dist].nil?
unless params[:ignore].nil?
# normalize to array
unless params[:ignore].kind_of?(Enumerable)
params[:ignore] = [params[:ignore]]
end
# no nil or empty strings
params[:ignore].reject! do |e|
e.strip.empty?
rescue StandardError
true
end
params[:ignore].each do |pattern|
command.push('--ignore').push(pattern)
end
end
command.push('--ignore-file').push(params[:ignore_file]) unless params[:ignore_file].nil?
Helper::SentryHelper.call_sentry_cli(params, command)
UI.success("Successfully uploaded files to release: #{version}")
end
#####################################################
# @!group Documentation
#####################################################
def self.description
"Upload one or more sourcemap(s) to a release of a project on Sentry"
end
def self.details
[
"This action allows you to upload one or more sourcemap(s) to a release of a project on Sentry.",
"See https://docs.sentry.io/learn/cli/releases/#upload-sourcemaps for more information."
].join(" ")
end
def self.available_options
Helper::SentryConfig.common_api_config_items + [
FastlaneCore::ConfigItem.new(key: :version,
description: "Release version on Sentry"),
FastlaneCore::ConfigItem.new(key: :app_identifier,
short_option: "-a",
env_name: "SENTRY_APP_IDENTIFIER",
description: "App Bundle Identifier, prepended to version",
optional: true),
FastlaneCore::ConfigItem.new(key: :build,
short_option: "-b",
description: "Release build on Sentry",
optional: true),
FastlaneCore::ConfigItem.new(key: :dist,
description: "Distribution in release",
optional: true),
FastlaneCore::ConfigItem.new(key: :sourcemap,
description: "Path or an array of paths to the sourcemap(s) to upload",
type: Array,
verify_block: proc do |values|
[*values].each do |value|
UI.user_error! "Could not find sourcemap at path '#{value}'" unless File.exist?(value)
end
end),
FastlaneCore::ConfigItem.new(key: :rewrite,
description: "Rewrite the sourcemaps before upload",
default_value: false,
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :strip_prefix,
conflicting_options: [:strip_common_prefix],
description: "Chop-off a prefix from uploaded files",
default_value: false,
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :strip_common_prefix,
conflicting_options: [:strip_prefix],
description: "Automatically guess what the common prefix is and chop that one off",
default_value: false,
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :url_prefix,
description: "Sets a URL prefix in front of all files",
optional: true),
FastlaneCore::ConfigItem.new(key: :ignore,
description: "Ignores all files and folders matching the given glob or array of globs",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :ignore_file,
description: "Ignore all files and folders specified in the given ignore file, e.g. .gitignore",
optional: true)
]
end
def self.return_value
nil
end
def self.authors
["wschurman"]
end
def self.is_supported?(platform)
true
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/lib/fastlane/plugin/sentry/actions/sentry_create_deploy.rb | lib/fastlane/plugin/sentry/actions/sentry_create_deploy.rb | module Fastlane
module Actions
class SentryCreateDeployAction < Action
def self.run(params)
require 'shellwords'
Helper::SentryConfig.parse_api_params(params)
version = params[:version]
version = "#{params[:app_identifier]}@#{params[:version]}" if params[:app_identifier]
version = "#{version}+#{params[:build]}" if params[:build]
command = [
"releases",
"deploys",
version,
"new"
]
command.push('--env').push(params[:env]) unless params[:env].nil?
command.push('--name').push(params[:name]) unless params[:name].nil?
command.push('--url').push(params[:deploy_url]) unless params[:deploy_url].nil?
command.push('--started').push(params[:started]) unless params[:started].nil?
command.push('--finished').push(params[:finished]) unless params[:finished].nil?
command.push('--time').push(params[:time]) unless params[:time].nil?
Helper::SentryHelper.call_sentry_cli(params, command)
UI.success("Successfully created deploy: #{version}")
end
#####################################################
# @!group Documentation
#####################################################
def self.description
"Creates a new release deployment for a project on Sentry"
end
def self.details
[
"This action allows you to associate deploys to releases for a project on Sentry.",
"See https://docs.sentry.io/product/cli/releases/#creating-deploys for more information."
].join(" ")
end
def self.available_options
Helper::SentryConfig.common_api_config_items + [
FastlaneCore::ConfigItem.new(key: :version,
description: "Release version to associate the deploy with on Sentry"),
FastlaneCore::ConfigItem.new(key: :app_identifier,
short_option: "-a",
env_name: "SENTRY_APP_IDENTIFIER",
description: "App Bundle Identifier, prepended with the version.\nFor example bundle@version",
optional: true),
FastlaneCore::ConfigItem.new(key: :build,
short_option: "-b",
description: "Release build to associate the deploy with on Sentry",
optional: true),
FastlaneCore::ConfigItem.new(key: :env,
short_option: "-e",
description: "Set the environment for this release. This argument is required. Values that make sense here would be 'production' or 'staging'",
optional: false),
FastlaneCore::ConfigItem.new(key: :name,
short_option: "-n",
description: "Optional human readable name for this deployment",
optional: true),
FastlaneCore::ConfigItem.new(key: :deploy_url,
description: "Optional URL that points to the deployment",
optional: true),
FastlaneCore::ConfigItem.new(key: :started,
description: "Optional unix timestamp when the deployment started",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :finished,
description: "Optional unix timestamp when the deployment finished",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :time,
short_option: "-t",
description: "Optional deployment duration in seconds. This can be specified alternatively to `started` and `finished`",
is_string: false,
optional: true)
]
end
def self.return_value
nil
end
def self.authors
["denrase"]
end
def self.is_supported?(platform)
true
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/lib/fastlane/plugin/sentry/actions/sentry_check_cli_installed.rb | lib/fastlane/plugin/sentry/actions/sentry_check_cli_installed.rb | module Fastlane
module Actions
class SentryCheckCliInstalledAction < Action
def self.run(params)
Helper::SentryHelper.find_and_check_sentry_cli_path!(params)
UI.success("Successfully checked that sentry-cli is installed")
end
#####################################################
# @!group Documentation
#####################################################
def self.description
"Checks that sentry-cli with the correct version is installed"
end
def self.details
[
"This action checks that the senty-cli is installed and meets the mimum verson requirements.",
"You can use it at the start of your lane to ensure that sentry-cli is correctly installed."
].join(" ")
end
def self.return_value
nil
end
def self.authors
["matt-oakes"]
end
def self.is_supported?(platform)
true
end
def self.available_options
Helper::SentryConfig.common_cli_config_items
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/lib/fastlane/plugin/sentry/actions/sentry_upload_proguard.rb | lib/fastlane/plugin/sentry/actions/sentry_upload_proguard.rb | module Fastlane
module Actions
class SentryUploadProguardAction < Action
def self.run(params)
Helper::SentryConfig.parse_api_params(params)
mapping_path = params[:mapping_path]
# Verify file exists
UI.user_error!("Mapping file does not exist at path: #{mapping_path}") unless File.exist? mapping_path
command = [
"upload-proguard",
mapping_path
]
Helper::SentryHelper.call_sentry_cli(params, command)
UI.success("Successfully uploaded mapping file!")
end
#####################################################
# @!group Documentation
#####################################################
def self.description
"Upload mapping to a project on Sentry"
end
def self.details
[
"This action allows you to upload the proguard mapping file to Sentry.",
"See https://docs.sentry.io/product/cli/dif/#proguard-mapping-upload for more information."
].join(" ")
end
def self.available_options
Helper::SentryConfig.common_api_config_items + [
FastlaneCore::ConfigItem.new(key: :mapping_path,
env_name: "ANDROID_MAPPING_PATH",
description: "Path to your proguard mapping.txt file",
optional: false,
verify_block: proc do |value|
UI.user_error! "Could not find your mapping file at path '#{value}'" unless File.exist?(value)
end)
]
end
def self.return_value
nil
end
def self.authors
["mpp-anasa"]
end
def self.is_supported?(platform)
platform == :android
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/lib/fastlane/plugin/sentry/actions/sentry_upload_dif.rb | lib/fastlane/plugin/sentry/actions/sentry_upload_dif.rb | module Fastlane
module Actions
class SentryUploadDifAction < Action
def self.run(params)
require 'shellwords'
UI.deprecated("This action is deprecated. Please use the `sentry_debug_files_upload` action.")
Helper::SentryConfig.parse_api_params(params)
paths = params[:path]
paths = ['.'] if paths.nil?
command = [
"upload-dif"
]
command += paths
command.push('--type').push(params[:type]) unless params[:type].nil?
command.push('--no-unwind') unless params[:no_unwind].nil?
command.push('--no-debug') unless params[:no_debug].nil?
command.push('--no-sources') unless params[:no_sources].nil?
command.push('--ids').push(params[:ids]) unless params[:ids].nil?
command.push('--require-all') unless params[:require_all].nil?
command.push('--symbol-maps').push(params[:symbol_maps]) unless params[:symbol_maps].nil?
command.push('--derived-data') unless params[:derived_data].nil?
command.push('--no-zips') unless params[:no_zips].nil?
command.push('--info-plist').push(params[:info_plist]) unless params[:info_plist].nil?
command.push('--no-reprocessing') unless params[:no_reprocessing].nil?
command.push('--force-foreground') unless params[:force_foreground].nil?
command.push('--include-sources') unless params[:include_sources] != true
command.push('--wait') unless params[:wait].nil?
command.push('--upload-symbol-maps') unless params[:upload_symbol_maps].nil?
Helper::SentryHelper.call_sentry_cli(params, command)
UI.success("Successfully ran upload-dif")
end
#####################################################
# @!group Documentation
#####################################################
def self.description
"Upload debugging information files."
end
def self.details
[
"Files can be uploaded using the `upload-dif` command. This command will scan a given folder recursively for files and upload them to Sentry.",
"See https://docs.sentry.io/product/cli/dif/#uploading-files for more information."
].join(" ")
end
def self.available_options
Helper::SentryConfig.common_api_config_items + [
FastlaneCore::ConfigItem.new(key: :path,
description: "Path or an array of paths to search recursively for symbol files",
type: Array,
optional: true),
FastlaneCore::ConfigItem.new(key: :type,
short_option: "-t",
description: "Only consider debug information files of the given \
type. By default, all types are considered",
optional: true,
verify_block: proc do |value|
UI.user_error! "Invalid value '#{value}'" unless ['dsym', 'elf', 'breakpad', 'pdb', 'pe', 'sourcebundle', 'bcsymbolmap'].include? value
end),
FastlaneCore::ConfigItem.new(key: :no_unwind,
description: "Do not scan for stack unwinding information. Specify \
this flag for builds with disabled FPO, or when \
stackwalking occurs on the device. This usually \
excludes executables and dynamic libraries. They might \
still be uploaded, if they contain additional \
processable information (see other flags)",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :no_debug,
description: "Do not scan for debugging information. This will \
usually exclude debug companion files. They might \
still be uploaded, if they contain additional \
processable information (see other flags)",
conflicting_options: [:no_unwind],
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :no_sources,
description: "Do not scan for source information. This will \
usually exclude source bundle files. They might \
still be uploaded, if they contain additional \
processable information (see other flags)",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :ids,
description: "Search for specific debug identifiers",
optional: true),
FastlaneCore::ConfigItem.new(key: :require_all,
description: "Errors if not all identifiers specified with --id could be found",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :symbol_maps,
description: "Optional path to BCSymbolMap files which are used to \
resolve hidden symbols in dSYM files downloaded from \
iTunes Connect. This requires the dsymutil tool to be \
available",
optional: true),
FastlaneCore::ConfigItem.new(key: :derived_data,
description: "Search for debug symbols in Xcode's derived data",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :no_zips,
description: "Do not search in ZIP files",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :info_plist,
description: "Optional path to the Info.plist.{n}We will try to find this \
automatically if run from Xcode. Providing this information \
will associate the debug symbols with a specific ITC application \
and build in Sentry. Note that if you provide the plist \
explicitly it must already be processed",
optional: true),
FastlaneCore::ConfigItem.new(key: :no_reprocessing,
description: "Do not trigger reprocessing after uploading",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :force_foreground,
description: "Wait for the process to finish.{n}\
By default, the upload process will detach and continue in the \
background when triggered from Xcode. When an error happens, \
a dialog is shown. If this parameter is passed Xcode will wait \
for the process to finish before the build finishes and output \
will be shown in the Xcode build output",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :include_sources,
description: "Include sources from the local file system and upload \
them as source bundles",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :wait,
description: "Wait for the server to fully process uploaded files. Errors \
can only be displayed if --wait is specified, but this will \
significantly slow down the upload process",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :upload_symbol_maps,
description: "Upload any BCSymbolMap files found to allow Sentry to resolve \
hidden symbols, e.g. when it downloads dSYMs directly from App \
Store Connect or when you upload dSYMs without first resolving \
the hidden symbols using --symbol-maps",
is_string: false,
optional: true)
]
end
def self.return_value
nil
end
def self.authors
["denrase"]
end
def self.is_supported?(platform)
true
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/lib/fastlane/plugin/sentry/actions/sentry_upload_dsym.rb | lib/fastlane/plugin/sentry/actions/sentry_upload_dsym.rb | module Fastlane
module Actions
class SentryUploadDsymAction < Action
def self.run(params)
UI.deprecated("This action is deprecated. Please use the `sentry_debug_files_upload` action.")
Helper::SentryConfig.parse_api_params(params)
# Params - dSYM
dsym_path = params[:dsym_path]
dsym_paths = params[:dsym_paths] || []
# Verify dsym(s)
dsym_paths += [dsym_path] unless dsym_path.nil?
dsym_paths = dsym_paths.map { |path| File.absolute_path(path) }
dsym_paths.each do |path|
UI.user_error!("dSYM does not exist at path: #{path}") unless File.exist? path
end
command = ["upload-dsym"]
command.push("--symbol-maps") unless params[:symbol_maps].nil?
command.push(params[:symbol_maps]) unless params[:symbol_maps].nil?
command.push("--info-plist") unless params[:info_plist].nil?
command.push(params[:info_plist]) unless params[:info_plist].nil?
command += dsym_paths
Helper::SentryHelper.call_sentry_cli(params, command)
UI.success("Successfully uploaded dSYMs!")
end
#####################################################
# @!group Documentation
#####################################################
def self.description
"Upload dSYM symbolication files to Sentry"
end
def self.details
[
"This action allows you to upload symbolication files to Sentry.",
"It's extra useful if you use it to download the latest dSYM files from Apple when you",
"use Bitcode"
].join(" ")
end
def self.available_options
Helper::SentryConfig.common_api_config_items + [
FastlaneCore::ConfigItem.new(key: :dsym_path,
env_name: "SENTRY_DSYM_PATH",
description: "Path to your symbols file. For iOS and Mac provide path to app.dSYM.zip",
default_value: Actions.lane_context[SharedValues::DSYM_OUTPUT_PATH],
optional: true,
verify_block: proc do |value|
UI.user_error! "Could not find Path to your symbols file at path '#{value}'" unless File.exist?(value)
end),
FastlaneCore::ConfigItem.new(key: :dsym_paths,
env_name: "SENTRY_DSYM_PATHS",
description: "Path to an array of your symbols file. For iOS and Mac provide path to app.dSYM.zip",
default_value: Actions.lane_context[SharedValues::DSYM_PATHS],
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :symbol_maps,
env_name: "SENTRY_SYMBOL_MAPS",
description: "Optional path to bcsymbolmap files which are used to resolve hidden symbols in the actual dsym files. This requires the dsymutil tool to be available",
optional: true,
verify_block: proc do |value|
UI.user_error! "Could not find bcsymbolmap at path '#{value}'" unless File.exist?(value)
end),
FastlaneCore::ConfigItem.new(key: :info_plist,
env_name: "SENTRY_INFO_PLIST",
description: "Optional path to Info.plist to add version information when uploading debug symbols",
optional: true,
verify_block: proc do |value|
UI.user_error! "Could not find Info.plist at path '#{value}'" unless File.exist?(value)
end)
]
end
def self.return_value
nil
end
def self.authors
["joshdholtz", "HazAT"]
end
def self.is_supported?(platform)
[:ios, :mac].include?(platform)
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/lib/fastlane/plugin/sentry/actions/sentry_create_release.rb | lib/fastlane/plugin/sentry/actions/sentry_create_release.rb | module Fastlane
module Actions
class SentryCreateReleaseAction < Action
def self.run(params)
require 'shellwords'
Helper::SentryConfig.parse_api_params(params)
version = params[:version]
version = "#{params[:app_identifier]}@#{params[:version]}" if params[:app_identifier]
version = "#{version}+#{params[:build]}" if params[:build]
command = [
"releases",
"new",
version
]
command.push("--finalize") if params[:finalize] == true
Helper::SentryHelper.call_sentry_cli(params, command)
UI.success("Successfully created release: #{version}")
end
#####################################################
# @!group Documentation
#####################################################
def self.description
"Create new releases for a project on Sentry"
end
def self.details
[
"This action allows you to create new releases for a project on Sentry.",
"See https://docs.sentry.io/learn/cli/releases/#creating-releases for more information."
].join(" ")
end
def self.available_options
Helper::SentryConfig.common_api_config_items + [
FastlaneCore::ConfigItem.new(key: :version,
description: "Release version to create on Sentry"),
FastlaneCore::ConfigItem.new(key: :app_identifier,
short_option: "-a",
env_name: "SENTRY_APP_IDENTIFIER",
description: "App Bundle Identifier, prepended to version",
optional: true),
FastlaneCore::ConfigItem.new(key: :build,
short_option: "-b",
description: "Release build to create on Sentry",
optional: true),
FastlaneCore::ConfigItem.new(key: :finalize,
description: "Whether to finalize the release. If not provided or false, the release can be finalized using the finalize_release action",
default_value: false,
is_string: false,
optional: true)
]
end
def self.return_value
nil
end
def self.authors
["wschurman"]
end
def self.is_supported?(platform)
true
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/lib/fastlane/plugin/sentry/actions/sentry_debug_files_upload.rb | lib/fastlane/plugin/sentry/actions/sentry_debug_files_upload.rb | module Fastlane
module Actions
class SentryDebugFilesUploadAction < Action
def self.run(params)
require 'shellwords'
Helper::SentryConfig.parse_api_params(params)
paths = params[:path]
paths = ['.'] if paths.nil?
command = [
"debug-files",
"upload"
]
command += paths
command.push('--type').push(params[:type]) unless params[:type].nil?
command.push('--no-unwind') unless params[:no_unwind].nil?
command.push('--no-debug') unless params[:no_debug].nil?
command.push('--no-sources') unless params[:no_sources].nil?
command.push('--ids').push(params[:ids]) unless params[:ids].nil?
command.push('--require-all') unless params[:require_all].nil?
command.push('--symbol-maps').push(params[:symbol_maps]) unless params[:symbol_maps].nil?
command.push('--derived-data') unless params[:derived_data].nil?
command.push('--no-zips') unless params[:no_zips].nil?
command.push('--info-plist').push(params[:info_plist]) unless params[:info_plist].nil?
command.push('--no-reprocessing') unless params[:no_reprocessing].nil?
command.push('--force-foreground') unless params[:force_foreground].nil?
command.push('--include-sources') unless params[:include_sources] != true
command.push('--wait') unless params[:wait].nil?
command.push('--upload-symbol-maps') unless params[:upload_symbol_maps].nil?
Helper::SentryHelper.call_sentry_cli(params, command)
UI.success("Successfully ran debug-files upload")
end
#####################################################
# @!group Documentation
#####################################################
def self.description
"Upload debugging information files."
end
def self.details
[
"Files can be uploaded using the `debug-files upload` command. This command will scan a given folder recursively for files and upload them to Sentry.",
"See https://docs.sentry.io/product/cli/dif/#uploading-files for more information."
].join(" ")
end
def self.available_options
Helper::SentryConfig.common_api_config_items + [
FastlaneCore::ConfigItem.new(key: :path,
description: "Path or an array of paths to search recursively for symbol files",
type: Array,
optional: true),
FastlaneCore::ConfigItem.new(key: :type,
short_option: "-t",
description: "Only consider debug information files of the given \
type. By default, all types are considered",
optional: true,
verify_block: proc do |value|
UI.user_error! "Invalid value '#{value}'" unless ['dsym', 'elf', 'breakpad', 'pdb', 'pe', 'sourcebundle', 'bcsymbolmap'].include? value
end),
FastlaneCore::ConfigItem.new(key: :no_unwind,
description: "Do not scan for stack unwinding information. Specify \
this flag for builds with disabled FPO, or when \
stackwalking occurs on the device. This usually \
excludes executables and dynamic libraries. They might \
still be uploaded, if they contain additional \
processable information (see other flags)",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :no_debug,
description: "Do not scan for debugging information. This will \
usually exclude debug companion files. They might \
still be uploaded, if they contain additional \
processable information (see other flags)",
conflicting_options: [:no_unwind],
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :no_sources,
description: "Do not scan for source information. This will \
usually exclude source bundle files. They might \
still be uploaded, if they contain additional \
processable information (see other flags)",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :ids,
description: "Search for specific debug identifiers",
optional: true),
FastlaneCore::ConfigItem.new(key: :require_all,
description: "Errors if not all identifiers specified with --id could be found",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :symbol_maps,
description: "Optional path to BCSymbolMap files which are used to \
resolve hidden symbols in dSYM files downloaded from \
iTunes Connect. This requires the dsymutil tool to be \
available",
optional: true),
FastlaneCore::ConfigItem.new(key: :derived_data,
description: "Search for debug symbols in Xcode's derived data",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :no_zips,
description: "Do not search in ZIP files",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :info_plist,
description: "Optional path to the Info.plist.{n}We will try to find this \
automatically if run from Xcode. Providing this information \
will associate the debug symbols with a specific ITC application \
and build in Sentry. Note that if you provide the plist \
explicitly it must already be processed",
optional: true),
FastlaneCore::ConfigItem.new(key: :no_reprocessing,
description: "Do not trigger reprocessing after uploading",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :force_foreground,
description: "Wait for the process to finish.{n}\
By default, the upload process will detach and continue in the \
background when triggered from Xcode. When an error happens, \
a dialog is shown. If this parameter is passed Xcode will wait \
for the process to finish before the build finishes and output \
will be shown in the Xcode build output",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :include_sources,
description: "Include sources from the local file system and upload \
them as source bundles",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :wait,
description: "Wait for the server to fully process uploaded files. Errors \
can only be displayed if --wait is specified, but this will \
significantly slow down the upload process",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :upload_symbol_maps,
description: "Upload any BCSymbolMap files found to allow Sentry to resolve \
hidden symbols, e.g. when it downloads dSYMs directly from App \
Store Connect or when you upload dSYMs without first resolving \
the hidden symbols using --symbol-maps",
is_string: false,
optional: true)
]
end
def self.return_value
nil
end
def self.authors
["denrase"]
end
def self.is_supported?(platform)
true
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/lib/fastlane/plugin/sentry/actions/sentry_finalize_release.rb | lib/fastlane/plugin/sentry/actions/sentry_finalize_release.rb | module Fastlane
module Actions
class SentryFinalizeReleaseAction < Action
def self.run(params)
require 'shellwords'
Helper::SentryConfig.parse_api_params(params)
version = params[:version]
version = "#{params[:app_identifier]}@#{params[:version]}" if params[:app_identifier]
version = "#{version}+#{params[:build]}" if params[:build]
command = [
"releases",
"finalize",
version
]
Helper::SentryHelper.call_sentry_cli(params, command)
UI.success("Successfully finalized release: #{version}")
end
#####################################################
# @!group Documentation
#####################################################
def self.description
"Finalize a release for a project on Sentry"
end
def self.details
[
"This action allows you to finalize releases created for a project on Sentry.",
"See https://docs.sentry.io/learn/cli/releases/#finalizing-releases for more information."
].join(" ")
end
def self.available_options
Helper::SentryConfig.common_api_config_items + [
FastlaneCore::ConfigItem.new(key: :version,
description: "Release version to finalize on Sentry"),
FastlaneCore::ConfigItem.new(key: :app_identifier,
short_option: "-a",
env_name: "SENTRY_APP_IDENTIFIER",
description: "App Bundle Identifier, prepended to version",
optional: true),
FastlaneCore::ConfigItem.new(key: :build,
short_option: "-b",
description: "Release build to finalize on Sentry",
optional: true)
]
end
def self.return_value
nil
end
def self.authors
["wschurman"]
end
def self.is_supported?(platform)
true
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/lib/fastlane/plugin/sentry/actions/sentry_upload_build.rb | lib/fastlane/plugin/sentry/actions/sentry_upload_build.rb | module Fastlane
module Actions
class SentryUploadBuildAction < Action
def self.run(params)
Helper::SentryConfig.parse_api_params(params)
# Verify xcarchive path
xcarchive_path = params[:xcarchive_path]
UI.user_error!("Could not find xcarchive at path '#{xcarchive_path}'") unless File.exist?(xcarchive_path)
UI.user_error!("Path '#{xcarchive_path}' is not an xcarchive") unless File.extname(xcarchive_path) == '.xcarchive'
command = [
"build",
"upload",
File.absolute_path(xcarchive_path)
]
# Add git-related parameters if provided
command << "--head-sha" << params[:head_sha] if params[:head_sha]
command << "--base-sha" << params[:base_sha] if params[:base_sha]
command << "--vcs-provider" << params[:vcs_provider] if params[:vcs_provider]
command << "--head-repo-name" << params[:head_repo_name] if params[:head_repo_name]
command << "--base-repo-name" << params[:base_repo_name] if params[:base_repo_name]
command << "--head-ref" << params[:head_ref] if params[:head_ref]
command << "--base-ref" << params[:base_ref] if params[:base_ref]
command << "--pr-number" << params[:pr_number] if params[:pr_number]
command << "--build-configuration" << params[:build_configuration] if params[:build_configuration]
Helper::SentryHelper.call_sentry_cli(params, command)
UI.success("Successfully uploaded build archive: #{xcarchive_path}")
end
#####################################################
# @!group Documentation
#####################################################
def self.description
"Upload iOS build archive to Sentry with optional git context"
end
def self.details
"This action allows you to upload iOS build archives (.xcarchive) to Sentry with optional git-related parameters for enhanced context including commit SHAs, branch names, repository information, and pull request details."
end
def self.available_options
Helper::SentryConfig.common_api_config_items + [
FastlaneCore::ConfigItem.new(key: :xcarchive_path,
description: "Path to your iOS build archive (.xcarchive)",
default_value: Actions.lane_context[SharedValues::XCODEBUILD_ARCHIVE],
verify_block: proc do |value|
UI.user_error!("Could not find xcarchive at path '#{value}'") unless File.exist?(value)
UI.user_error!("Path '#{value}' is not an xcarchive") unless File.extname(value) == '.xcarchive'
end),
FastlaneCore::ConfigItem.new(key: :head_sha,
env_name: "SENTRY_HEAD_SHA",
description: "The SHA of the head of the current branch",
optional: true,
is_string: true),
FastlaneCore::ConfigItem.new(key: :base_sha,
env_name: "SENTRY_BASE_SHA",
description: "The SHA of the base branch",
optional: true,
is_string: true),
FastlaneCore::ConfigItem.new(key: :vcs_provider,
env_name: "SENTRY_VCS_PROVIDER",
description: "The version control system provider (e.g., 'github', 'gitlab')",
optional: true,
is_string: true),
FastlaneCore::ConfigItem.new(key: :head_repo_name,
env_name: "SENTRY_HEAD_REPO_NAME",
description: "The name of the head repository",
optional: true,
is_string: true),
FastlaneCore::ConfigItem.new(key: :base_repo_name,
env_name: "SENTRY_BASE_REPO_NAME",
description: "The name of the base repository",
optional: true,
is_string: true),
FastlaneCore::ConfigItem.new(key: :head_ref,
env_name: "SENTRY_HEAD_REF",
description: "The name of the head branch",
optional: true,
is_string: true),
FastlaneCore::ConfigItem.new(key: :base_ref,
env_name: "SENTRY_BASE_REF",
description: "The name of the base branch",
optional: true,
is_string: true),
FastlaneCore::ConfigItem.new(key: :pr_number,
env_name: "SENTRY_PR_NUMBER",
description: "The pull request number",
optional: true,
is_string: true),
FastlaneCore::ConfigItem.new(key: :build_configuration,
env_name: "SENTRY_BUILD_CONFIGURATION",
description: "The build configuration (e.g., 'Release', 'Debug')",
optional: true,
is_string: true)
]
end
def self.return_value
nil
end
def self.authors
["runningcode"]
end
def self.is_supported?(platform)
[:ios].include?(platform)
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/lib/fastlane/plugin/sentry/actions/sentry_set_commits.rb | lib/fastlane/plugin/sentry/actions/sentry_set_commits.rb | module Fastlane
module Actions
class SentrySetCommitsAction < Action
def self.run(params)
require 'shellwords'
Helper::SentryConfig.parse_api_params(params)
version = params[:version]
version = "#{params[:app_identifier]}@#{params[:version]}" if params[:app_identifier]
version = "#{version}+#{params[:build]}" if params[:build]
command = [
"releases",
"set-commits",
version
]
command.push('--auto') if params[:auto]
command.push('--clear') if params[:clear]
command.push('--ignore-missing') if params[:ignore_missing]
command.push('--commit').push(params[:commit]) unless params[:commit].nil?
Helper::SentryHelper.call_sentry_cli(params, command)
UI.success("Successfully set commits for release: #{version}")
end
#####################################################
# @!group Documentation
#####################################################
def self.description
"Set commits of a release"
end
def self.details
[
"This action allows you to set commits in a release for a project on Sentry.",
"See https://docs.sentry.io/cli/releases/#sentry-cli-commit-integration for more information."
].join(" ")
end
def self.available_options
Helper::SentryConfig.common_api_config_items + [
FastlaneCore::ConfigItem.new(key: :version,
description: "Release version on Sentry"),
FastlaneCore::ConfigItem.new(key: :app_identifier,
short_option: "-a",
env_name: "SENTRY_APP_IDENTIFIER",
description: "App Bundle Identifier, prepended to version",
optional: true),
FastlaneCore::ConfigItem.new(key: :build,
short_option: "-b",
description: "Release build on Sentry",
optional: true),
FastlaneCore::ConfigItem.new(key: :auto,
description: "Enable completely automated commit management",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :clear,
description: "Clear all current commits from the release",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :commit,
description: "Commit spec, see `sentry-cli releases help set-commits` for more information",
optional: true),
FastlaneCore::ConfigItem.new(key: :ignore_missing,
description: "When enabled, if the previous release commit was not found in the repository, will create a release with the default commits count (or the one specified with `--initial-depth`) instead of failing the command",
is_string: false,
default_value: false)
]
end
def self.return_value
nil
end
def self.authors
["brownoxford"]
end
def self.is_supported?(platform)
true
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/lib/fastlane/plugin/sentry/helper/sentry_config.rb | lib/fastlane/plugin/sentry/helper/sentry_config.rb | module Fastlane
module Helper
class SentryConfig
def self.common_cli_config_items
[
FastlaneCore::ConfigItem.new(key: :sentry_cli_path,
env_name: "SENTRY_CLI_PATH",
description: "Path to your sentry-cli. Defaults to `which sentry-cli`",
optional: true,
verify_block: proc do |value|
UI.user_error! "'#{value}' is not executable" unless FastlaneCore::Helper.executable?(value)
end)
]
end
def self.common_api_config_items
[
FastlaneCore::ConfigItem.new(key: :url,
env_name: "SENTRY_URL",
description: "Url for Sentry",
is_string: true,
optional: true),
FastlaneCore::ConfigItem.new(key: :auth_token,
env_name: "SENTRY_AUTH_TOKEN",
description: "Authentication token for Sentry",
optional: true),
FastlaneCore::ConfigItem.new(key: :api_key,
env_name: "SENTRY_API_KEY",
description: "API key for Sentry",
optional: true),
FastlaneCore::ConfigItem.new(key: :org_slug,
env_name: "SENTRY_ORG_SLUG",
description: "Organization slug for Sentry project",
optional: true),
FastlaneCore::ConfigItem.new(key: :project_slug,
env_name: "SENTRY_PROJECT_SLUG",
description: "Project slug for Sentry",
optional: true),
FastlaneCore::ConfigItem.new(key: :log_level,
env_name: "SENTRY_LOG_LEVEL",
description: "Configures the log level used by sentry-cli",
optional: true,
verify_block: proc do |value|
UI.user_error! "Invalid log level '#{value}'" unless ['trace', 'debug', 'info', 'warn', 'error'].include? value.downcase
end)
] + self.common_cli_config_items
end
def self.parse_api_params(params)
require 'shellwords'
url = params[:url]
auth_token = params[:auth_token]
api_key = params[:api_key]
org = params[:org_slug]
project = params[:project_slug]
log_level = params[:log_level]
has_org = !org.to_s.empty?
has_project = !project.to_s.empty?
has_api_key = !api_key.to_s.empty?
has_auth_token = !auth_token.to_s.empty?
ENV['SENTRY_URL'] = url unless url.to_s.empty?
if log_level.to_s.empty?
ENV['SENTRY_LOG_LEVEL'] = 'debug' if FastlaneCore::Globals.verbose?
else
ENV['SENTRY_LOG_LEVEL'] = log_level
end
# Fallback to .sentryclirc if possible when no auth token is provided
if !has_api_key && !has_auth_token && fallback_sentry_cli_auth(params)
UI.important("No auth config provided, will fallback to .sentryclirc")
else
# Will fail if none or both authentication methods are provided
if !has_api_key && !has_auth_token
UI.user_error!("No API key or authentication token found for SentryAction given, pass using `api_key: 'key'` or `auth_token: 'token'`")
elsif has_api_key && has_auth_token
UI.user_error!("Both API key and authentication token found for SentryAction given, please only give one")
elsif has_api_key && !has_auth_token
UI.deprecated("Please consider switching to auth_token ... api_key will be removed in the future")
end
ENV['SENTRY_API_KEY'] = api_key unless api_key.to_s.empty?
ENV['SENTRY_AUTH_TOKEN'] = auth_token unless auth_token.to_s.empty?
end
if has_org && has_project
ENV['SENTRY_ORG'] = Shellwords.escape(org) unless org.to_s.empty?
ENV['SENTRY_PROJECT'] = Shellwords.escape(project) unless project.to_s.empty?
elsif !has_org
UI.important("Missing 'org_slug' parameter. Provide both 'org_slug' and 'project_slug'. Falling back to .sentryclirc")
elsif !has_project
UI.important("Missing 'project_slug' parameter. Provide both 'org_slug' and 'project_slug'. Falling back to .sentryclirc")
end
end
def self.fallback_sentry_cli_auth(params)
sentry_cli_result = JSON.parse(SentryHelper.call_sentry_cli(
params,
[
"info",
"--config-status-json"
]
))
return (sentry_cli_result["auth"]["successful"] &&
!sentry_cli_result["auth"]["type"].nil?)
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
getsentry/sentry-fastlane-plugin | https://github.com/getsentry/sentry-fastlane-plugin/blob/1210921f1787d66ab0f0fa02c8e7dabc3d966480/lib/fastlane/plugin/sentry/helper/sentry_helper.rb | lib/fastlane/plugin/sentry/helper/sentry_helper.rb | require 'os'
module Fastlane
module Helper
class SentryHelper
def self.find_and_check_sentry_cli_path!(params)
bundled_sentry_cli_path = self.bundled_sentry_cli_path
bundled_sentry_cli_version = Gem::Version.new(`#{bundled_sentry_cli_path} --version`.scan(/(?:\d+\.?){3}/).first)
sentry_cli_path = params[:sentry_cli_path] || bundled_sentry_cli_path
sentry_cli_version = Gem::Version.new(`#{sentry_cli_path} --version`.scan(/(?:\d+\.?){3}/).first)
if sentry_cli_version < bundled_sentry_cli_version
UI.user_error!("Your sentry-cli is outdated, please upgrade to at least version #{bundled_sentry_cli_version} and start your lane again!")
end
UI.success("Using sentry-cli #{sentry_cli_version}")
sentry_cli_path
end
def self.call_sentry_cli(params, sub_command)
sentry_path = self.find_and_check_sentry_cli_path!(params)
command = [sentry_path] + sub_command
UI.message "Starting sentry-cli..."
require 'open3'
final_command = command.map { |arg| Shellwords.escape(arg) }.join(" ")
if FastlaneCore::Globals.verbose?
UI.command(final_command)
end
env = { 'SENTRY_PIPELINE' => "sentry-fastlane-plugin/#{Fastlane::Sentry::VERSION}" }
Open3.popen3(env, final_command) do |stdin, stdout, stderr, status_thread|
out_reader = Thread.new do
output = []
stdout.each_line do |line|
l = line.strip!
UI.message(l)
output << l
end
output.join
end
err_reader = Thread.new do
stderr.each_line do |line|
UI.message(line.strip!)
end
end
unless status_thread.value.success?
UI.user_error!('Error while calling Sentry CLI')
end
err_reader.join
out_reader.value
end
end
def self.bundled_sentry_cli_path
if OS.mac?
self.bin_folder('sentry-cli-Darwin-universal')
elsif OS.windows?
if OS.bits == 64
self.bin_folder('sentry-cli-Windows-x86_64.exe')
else
self.bin_folder('sentry-cli-Windows-i686.exe')
end
else
if OS.bits == 64
self.bin_folder('sentry-cli-Linux-x86_64')
else
self.bin_folder('sentry-cli-Linux-i686')
end
end
end
# Get path for files in bin folder. Paths are resolved relative to this file, for which there are also unit tests.
def self.bin_folder(filename)
File.expand_path("../../../../../bin/#{filename}", File.dirname(__FILE__))
end
end
end
end
| ruby | MIT | 1210921f1787d66ab0f0fa02c8e7dabc3d966480 | 2026-01-04T17:37:17.505722Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/benchmarks.rb | dev/test/benchmarks.rb | # frozen_string_literal: true
require "benchmark"
require_relative "../lib/product_taxonomy"
module ProductTaxonomy
# These benchmarks are not part of the test suite, but are useful as a sanity check during development.
# They're not part of the test suite because the runtimes fluctuate depending on the machine, so we can't reliably
# make assertions about them.
Benchmark.bm(40) do |x|
x.report("Load values") do
Value.load_from_source(YAML.safe_load_file("../data/values.yml"))
Value.reset
end
x.report("Load values and attributes") do
Value.load_from_source(YAML.safe_load_file("../data/values.yml"))
Attribute.load_from_source(YAML.safe_load_file("../data/attributes.yml"))
Value.reset
Attribute.reset
end
x.report("Load values, attributes, and categories") do
Value.load_from_source(YAML.safe_load_file("../data/values.yml"))
Attribute.load_from_source(YAML.safe_load_file("../data/attributes.yml"))
categories_source_data = Dir.glob("../data/categories/*.yml").each_with_object([]) do |file, array|
array.concat(YAML.safe_load_file(file))
end
Category.load_from_source(categories_source_data)
Value.reset
Attribute.reset
Category.reset
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/benchmark_test.rb | dev/test/benchmark_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class BenchmarkTest < Minitest::Benchmark
class << self
def bench_range
(1..10000).step(1000)
end
end
def bench_load_values
source_data = YAML.safe_load_file("../data/values.yml")
Value.load_from_source(source_data.first(10)) # warmup
Value.reset
assert_performance_linear do |n|
Value.load_from_source(source_data.first(n))
Value.reset
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/test_helper.rb | dev/test/test_helper.rb | # frozen_string_literal: true
$LOAD_PATH.unshift(File.expand_path("../lib", __dir__))
require "product_taxonomy"
require "product_taxonomy/cli"
require "active_support/testing/autorun"
require "minitest/benchmark"
require "minitest/pride"
require "minitest/hooks/default"
require "mocha/minitest"
module ProductTaxonomy
class TestCase < ActiveSupport::TestCase
teardown do
ProductTaxonomy::Value.reset
ProductTaxonomy::Attribute.reset
ProductTaxonomy::Category.reset
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/identifier_formatter_test.rb | dev/test/identifier_formatter_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class IdentifierFormatterTest < TestCase
test "format_friendly_id with special characters" do
assert_equal "apparel_accessories", IdentifierFormatter.format_friendly_id("Apparel & Accessories")
end
test "format_handle with special characters" do
assert_equal "apparel-accessories", IdentifierFormatter.format_handle("Apparel & Accessories")
end
test "format_handle with plus in name" do
assert_equal "c-plus-plus-programming", IdentifierFormatter.format_handle("C++ Programming")
end
test "format_handle with hashtag in name" do
assert_equal "trending-hashtag-products", IdentifierFormatter.format_handle("Trending #Products")
end
test "format_handle with multiple dashes" do
assert_equal "arcade-gaming", IdentifierFormatter.format_handle("Arcade --- & Gaming")
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/product_taxonomy_test.rb | dev/test/product_taxonomy_test.rb | # frozen_string_literal: true
require "test_helper"
class ProductTaxonomyTest < ActiveSupport::TestCase
test "it has a version number" do
assert true
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/localizations_validator_test.rb | dev/test/localizations_validator_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class LocalizationsValidatorTest < TestCase
setup do
@category = Category.new(id: "test-1", name: "Test Category")
@attribute = Attribute.new(
id: 1,
name: "Test Attribute",
friendly_id: "test_attr",
handle: "test_attr",
description: "Test description",
values: [],
)
@value = Value.new(
id: 1,
name: "Test Value",
friendly_id: "test_value",
handle: "test_value",
)
Category.stubs(:all).returns([@category])
Attribute.stubs(:all).returns([@attribute])
Value.stubs(:all).returns([@value])
@fr_categories_yaml = <<~YAML
fr:
categories:
"test-1":
name: "Catégorie de test"
YAML
@fr_attributes_yaml = <<~YAML
fr:
attributes:
"test_attr":
name: "Attribut de test"
description: "Description de test"
YAML
@fr_values_yaml = <<~YAML
fr:
values:
"test_value":
name: "Valeur de test"
YAML
@es_categories_yaml = <<~YAML
es:
categories:
"test-1":
name: "Categoría de prueba"
YAML
@es_attributes_yaml = <<~YAML
es:
attributes:
"test_attr":
name: "Atributo de prueba"
description: "Descripción de prueba"
YAML
@es_values_yaml = <<~YAML
es:
values:
"test_value":
name: "Valor de prueba"
YAML
ProductTaxonomy.stubs(:data_path).returns("/fake/path")
Dir.stubs(:glob)
.with("/fake/path/localizations/categories/*.yml")
.returns(["/fake/path/localizations/categories/fr.yml", "/fake/path/localizations/categories/es.yml"])
Dir.stubs(:glob)
.with("/fake/path/localizations/attributes/*.yml")
.returns(["/fake/path/localizations/attributes/fr.yml", "/fake/path/localizations/attributes/es.yml"])
Dir.stubs(:glob)
.with("/fake/path/localizations/values/*.yml")
.returns(["/fake/path/localizations/values/fr.yml", "/fake/path/localizations/values/es.yml"])
YAML.stubs(:safe_load_file)
.with("/fake/path/localizations/categories/fr.yml")
.returns(YAML.safe_load(@fr_categories_yaml))
YAML.stubs(:safe_load_file)
.with("/fake/path/localizations/categories/es.yml")
.returns(YAML.safe_load(@es_categories_yaml))
YAML.stubs(:safe_load_file)
.with("/fake/path/localizations/attributes/fr.yml")
.returns(YAML.safe_load(@fr_attributes_yaml))
YAML.stubs(:safe_load_file)
.with("/fake/path/localizations/attributes/es.yml")
.returns(YAML.safe_load(@es_attributes_yaml))
YAML.stubs(:safe_load_file)
.with("/fake/path/localizations/values/fr.yml")
.returns(YAML.safe_load(@fr_values_yaml))
YAML.stubs(:safe_load_file)
.with("/fake/path/localizations/values/es.yml")
.returns(YAML.safe_load(@es_values_yaml))
end
teardown do
Category.instance_variable_set(:@localizations, nil)
Attribute.instance_variable_set(:@localizations, nil)
Value.instance_variable_set(:@localizations, nil)
end
test "validate! passes when all required localizations are present" do
assert_nothing_raised do
LocalizationsValidator.validate!
LocalizationsValidator.validate!(["fr"])
LocalizationsValidator.validate!(["es"])
LocalizationsValidator.validate!(["fr", "es"])
end
end
test "validate! raises error when category localizations are missing" do
category2 = Category.new(id: "test-2", name: "Second Category")
Category.stubs(:all).returns([@category, category2])
assert_raises(ArgumentError) do
LocalizationsValidator.validate!(["fr"])
end
end
test "validate! raises error when attribute localizations are missing" do
attribute2 = Attribute.new(
id: 2,
name: "Second Attribute",
friendly_id: "test_attr2",
handle: "test_attr2",
description: "Test description 2",
values: [],
)
Attribute.stubs(:all).returns([@attribute, attribute2])
assert_raises(ArgumentError) do
LocalizationsValidator.validate!(["fr"])
end
end
test "validate! raises error when value localizations are missing" do
value2 = Value.new(
id: 2,
name: "Second Value",
friendly_id: "test_value2",
handle: "test_value2",
)
Value.stubs(:all).returns([@value, value2])
assert_raises(ArgumentError) do
LocalizationsValidator.validate!(["fr"])
end
end
test "validate! raises error when locales are inconsistent" do
Dir.unstub(:glob)
Dir.stubs(:glob)
.with("/fake/path/localizations/categories/*.yml")
.returns(["/fake/path/localizations/categories/fr.yml"])
Dir.stubs(:glob)
.with("/fake/path/localizations/attributes/*.yml")
.returns(["/fake/path/localizations/attributes/fr.yml"])
Dir.stubs(:glob)
.with("/fake/path/localizations/values/*.yml")
.returns([])
assert_raises(ArgumentError, "Not all model localizations have the same set of locales") do
LocalizationsValidator.validate!
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/integration/mapping_validation_test.rb | dev/test/integration/mapping_validation_test.rb | # frozen_string_literal: true
require_relative "../test_helper"
module ProductTaxonomy
class MappingValidationTest < TestCase
DIST_PATH = GenerateDistCommand::OUTPUT_PATH
def setup
@mappings_json_data = JSON.parse(File.read(File.expand_path("en/integrations/all_mappings.json", DIST_PATH)))
end
test "category IDs in mappings are valid" do
invalid_categories = []
raw_mappings_list = []
mapping_rule_files = Dir.glob(File.expand_path(
"integrations/*/*/mappings/*_shopify.yml",
ProductTaxonomy.data_path,
))
mapping_rule_files.each do |file|
raw_mappings_list << YAML.safe_load_file(file)
end
raw_mappings_list.each do |mapping|
["input", "output"].each do |input_or_output|
input_or_output_taxonomy = if input_or_output == "input"
mapping["input_taxonomy"]
else
mapping["output_taxonomy"]
end
invalid_category_ids = validate_mapping_category_ids(
mapping["rules"],
input_or_output,
input_or_output_taxonomy,
)
next if invalid_category_ids.empty?
invalid_categories << {
input_taxonomy: mapping["input_taxonomy"],
output_taxonomy: mapping["output_taxonomy"],
rules_input_or_output: input_or_output,
invalid_category_ids: invalid_category_ids,
}
end
end
unless invalid_categories.empty?
puts "Invalid category ids are found in mappings for the following integrations:"
invalid_categories.each_with_index do |item, index|
puts ""
puts "[#{index + 1}] #{item[:input_taxonomy]} to #{item[:output_taxonomy]} in the rules #{item[:rules_input_or_output]} (#{item[:invalid_category_ids].size} invalid ids)"
item[:invalid_category_ids].each do |category_id|
puts " - #{category_id}"
end
end
assert(invalid_categories.empty?, "Invalid category ids are found in mappings.")
end
end
test "every Shopify category has corresponding channel mappings" do
shopify_categories_lack_mappings = []
@mappings_json_data["mappings"].each do |mapping|
next unless mapping["input_taxonomy"].include?("shopify")
next if mapping["output_taxonomy"].include?("shopify") && mapping["output_taxonomy"] != "shopify/2022-02"
all_shopify_category_ids = category_ids_from_taxonomy(mapping["input_taxonomy"])
next if all_shopify_category_ids.nil?
unmapped_category_ids = unmapped_category_ids_for_mappings(
mapping["input_taxonomy"],
mapping["output_taxonomy"],
)
unmapped_category_ids = if !unmapped_category_ids.nil? &&
all_shopify_category_ids.first.include?("gid://shopify/TaxonomyCategory/")
unmapped_category_ids.map { |id| "gid://shopify/TaxonomyCategory/#{id}" }.to_set
end
shopify_category_ids_from_mappings_input = mapping["rules"]
.map { _1.dig("input", "category", "id") }
.to_set
missing_category_ids = all_shopify_category_ids - shopify_category_ids_from_mappings_input
unless unmapped_category_ids.nil?
missing_category_ids -= unmapped_category_ids
end
next if missing_category_ids.empty?
shopify_categories_lack_mappings << {
input_taxonomy: mapping["input_taxonomy"],
output_taxonomy: mapping["output_taxonomy"],
missing_category_ids: missing_category_ids.map { |id| id.split("/").last },
}
end
unless shopify_categories_lack_mappings.empty?
puts "Shopify Categories are missing mappings for the following integrations:"
shopify_categories_lack_mappings.each_with_index do |mapping, index|
puts ""
puts "[#{index + 1}] #{mapping[:input_taxonomy]} to #{mapping[:output_taxonomy]} (#{mapping[:missing_category_ids].size} missing)"
mapping[:missing_category_ids].each do |category_id|
puts " - #{category_id}"
end
end
assert(shopify_categories_lack_mappings.empty?, "Shopify Categories are missing mappings.")
end
end
test "category IDs cannot be presented in the rules input and unmapped_product_category_ids at the same time" do
overlapped_category_ids_in_mappings = []
@mappings_json_data["mappings"].each do |mapping|
category_ids_from_mappings_input = mapping["rules"]
.map { _1.dig("input", "category", "id").split("/").last }
.to_set
unmapped_category_ids = unmapped_category_ids_for_mappings(
mapping["input_taxonomy"],
mapping["output_taxonomy"],
)
next if unmapped_category_ids.nil?
overlapped_category_ids = category_ids_from_mappings_input & unmapped_category_ids.to_set
next if overlapped_category_ids.empty?
overlapped_category_ids_in_mappings << {
input_taxonomy: mapping["input_taxonomy"],
output_taxonomy: mapping["output_taxonomy"],
overlapped_category_ids: overlapped_category_ids,
}
end
unless overlapped_category_ids_in_mappings.empty?
puts "Category IDs cannot be presented in both rules input and unmapped_product_category_ids at the same time for the following integrations:"
overlapped_category_ids_in_mappings.each_with_index do |mapping, index|
puts ""
puts "[#{index + 1}] #{mapping[:input_taxonomy]} to #{mapping[:output_taxonomy]} (#{mapping[:overlapped_category_ids].size} overlapped)"
mapping[:overlapped_category_ids].each do |category_id|
puts " - #{category_id}"
end
end
assert(
overlapped_category_ids_in_mappings.empty?,
"Category IDs cannot be presented in both rules input and unmapped_product_category_ids at the same time for the following integrations.",
)
end
end
test "Shopify taxonomy version is consistent between VERSION file and mappings in the /data folder" do
shopify_taxonomy_version_from_file = "shopify/" + current_shopify_taxonomy_version
integration_versions_path = File.expand_path("integrations/shopify/*", ProductTaxonomy.data_path)
all_shopify_taxonomy_versions_on_disk = Dir.glob(integration_versions_path).map do |path|
version_name = File.basename(path)
"shopify/#{version_name}" if version_name.match?(/^\d{4}-\d{2}$/)
end.compact.sort
all_shopify_taxonomy_versions_on_disk << shopify_taxonomy_version_from_file
mapping_rule_files = Dir.glob(File.expand_path(
"integrations/*/*/mappings/*_shopify.yml",
ProductTaxonomy.data_path,
))
files_include_inconsistent_shopify_taxonomy_version = []
mapping_rule_files.each do |file|
raw_mappings = YAML.safe_load_file(file)
input_taxonomy = raw_mappings["input_taxonomy"]
output_taxonomy = raw_mappings["output_taxonomy"]
next if input_taxonomy == shopify_taxonomy_version_from_file
if all_shopify_taxonomy_versions_on_disk.include?(input_taxonomy)
expected_output_taxonomy = all_shopify_taxonomy_versions_on_disk[all_shopify_taxonomy_versions_on_disk.index(input_taxonomy) + 1]
next if expected_output_taxonomy == output_taxonomy
end
files_include_inconsistent_shopify_taxonomy_version << {
file_path: file,
taxonomy_version: shopify_taxonomy_version_from_file,
}
end
unless files_include_inconsistent_shopify_taxonomy_version.empty?
puts "The Shopify taxonomy version is #{shopify_taxonomy_version_from_file} based on the VERSION file"
puts "We detected inconsistent Shopify taxonomy versions in the following mapping files in the /data folder:"
files_include_inconsistent_shopify_taxonomy_version.each_with_index do |item|
puts "- mapping file #{item[:file_path]} has inconsistent Shopify taxonomy version #{item[:taxonomy_version]}"
end
assert(
files_include_inconsistent_shopify_taxonomy_version.empty?,
"Shopify taxonomy version is inconsistent between VERSION file and mappings in the /data folder.",
)
end
end
def validate_mapping_category_ids(mapping_rules, input_or_output, input_or_output_taxonomy)
category_ids = category_ids_from_taxonomy(input_or_output_taxonomy).map { _1.split("/").last }
return [] if category_ids.nil?
return [] if input_or_output == "output" && input_or_output_taxonomy.include?("shopify") &&
input_or_output_taxonomy != "shopify/#{current_shopify_taxonomy_version}"
invalid_category_ids = Set.new
mapping_rules.each do |rule|
product_category_ids = rule[input_or_output]["product_category_id"]
product_category_ids = [product_category_ids] unless product_category_ids.is_a?(Array)
product_category_ids.each do |product_category_id|
invalid_category_ids.add(product_category_id) unless category_ids.include?(product_category_id.to_s)
end
end
invalid_category_ids
end
def category_ids_from_taxonomy(input_or_output_taxonomy)
if input_or_output_taxonomy == "shopify/#{current_shopify_taxonomy_version}"
categories_json_data = JSON.parse(File.read(File.expand_path("en/categories.json", DIST_PATH)))
shopify_category_ids = Set.new
categories_json_data["verticals"].each do |vertical|
vertical["categories"].each do |category|
shopify_category_ids.add(category["id"])
end
end
shopify_category_ids
else
channel_category_ids = Set.new
file_path = File.expand_path(
"integrations/#{input_or_output_taxonomy}/full_names.yml",
ProductTaxonomy.data_path,
)
channel_taxonomy = YAML.safe_load_file(file_path)
channel_taxonomy.each do |entry|
channel_category_ids.add(entry["id"].to_s)
end
channel_category_ids
end
end
def unmapped_category_ids_for_mappings(mappings_input_taxonomy, mappings_output_taxonomy)
integration_mapping_path = if mappings_input_taxonomy.include?("shopify") &&
mappings_output_taxonomy.include?("shopify")
integration_version = "shopify/2022-02"
if mappings_input_taxonomy == "shopify/2022-02"
"#{integration_version}/mappings/to_shopify.yml"
else
"#{integration_version}/mappings/from_shopify.yml"
end
elsif mappings_input_taxonomy.include?("shopify")
integration_version = mappings_output_taxonomy
"#{integration_version}/mappings/from_shopify.yml"
else
integration_version = mappings_input_taxonomy
"#{integration_version}/mappings/to_shopify.yml"
end
file_path = File.expand_path("integrations/#{integration_mapping_path}", ProductTaxonomy.data_path)
return unless File.exist?(file_path)
mappings = YAML.safe_load_file(file_path)
mappings["unmapped_product_category_ids"] if mappings.key?("unmapped_product_category_ids")
end
def current_shopify_taxonomy_version
@current_shopify_taxonomy_version ||= File.read(File.expand_path("../VERSION", ProductTaxonomy.data_path)).strip
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/integration/distribution_matches_data_test.rb | dev/test/integration/distribution_matches_data_test.rb | # frozen_string_literal: true
require_relative "../test_helper"
module ProductTaxonomy
class DistributionMatchesDataTest < TestCase
include Minitest::Hooks
parallelize(workers: 1) # disable parallelization
DIST_PATH = GenerateDistCommand::OUTPUT_PATH
test "dist/ files match the system" do
dist_files_before = Dir.glob(File.expand_path("en/**/*.{json,txt}", DIST_PATH)).map do |path|
[path, File.read(path)]
end.to_h
GenerateDistCommand.new(locales: ["en"]).execute
dist_files_after = Dir.glob(File.expand_path("en/**/*.{json,txt}", DIST_PATH)).map do |path|
[path, File.read(path)]
end.to_h
files_added = dist_files_after.keys - dist_files_before.keys
files_removed = dist_files_before.keys - dist_files_after.keys
files_changed = dist_files_after.select { |k, v| dist_files_before[k] != v }.keys
assert_empty(files_added, <<~MSG)
Expected, but did not find, these files: #{files_added.join("\n")}.
If run locally, this test itself has fixed the issue.
MSG
assert_empty(files_removed, <<~MSG)
Found, but did not expect, these files:
#{files_removed.join("\n")}
If run locally, this test itself has fixed the issue
MSG
assert_empty(files_changed, <<~MSG)
Expected changes to these files:
#{files_changed.join("\n")}
If run locally, this test itself has fixed the issue
MSG
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/integration/all_data_files_import_test.rb | dev/test/integration/all_data_files_import_test.rb | # frozen_string_literal: true
require_relative "../test_helper"
module ProductTaxonomy
class AllDataFilesImportTest < ActiveSupport::TestCase
include Minitest::Hooks
parallelize(workers: 1) # disable parallelization
# I don't _actually_ suck ;-) we need this so that we can load the data a single time to use for all tests in this
# class using before_all, giving better performance.
i_suck_and_my_tests_are_order_dependent!
def before_all
@raw_values_data = YAML.safe_load_file(File.expand_path("values.yml", ProductTaxonomy.data_path))
@raw_attributes_data = YAML.safe_load_file(File.expand_path("attributes.yml", ProductTaxonomy.data_path))
@raw_verticals_data = Dir.glob(File.expand_path("categories/*.yml", ProductTaxonomy.data_path))
.map { |file| YAML.safe_load_file(file) }
@raw_integrations_data = YAML.safe_load_file(File.expand_path(
"integrations/integrations.yml",
ProductTaxonomy.data_path,
))
mapping_rule_files = Dir.glob(File.expand_path(
"integrations/*/*/mappings/*_shopify.yml",
ProductTaxonomy.data_path,
))
@raw_mapping_rules_data = mapping_rule_files.map { { content: YAML.safe_load_file(_1), file_name: _1 } }
Command.new(quiet: true).load_taxonomy
end
def after_all
Value.reset
Attribute.reset
Category.reset
end
test "Values are consistent with values.yml" do
@raw_values_data.each do |raw_value|
real_value = Value.find_by(id: raw_value.fetch("id"))
refute_nil real_value, "Value #{raw_value.fetch("id")} not found"
assert_equal raw_value["id"], real_value.id
assert_equal raw_value["name"], real_value.name
assert_equal raw_value["handle"], real_value.handle
assert_equal raw_value["friendly_id"], real_value.friendly_id
end
end
test "Attributes are consistent with attributes.yml" do
base_attributes = @raw_attributes_data["base_attributes"]
extended_attributes = @raw_attributes_data["extended_attributes"]
base_attributes.each do |raw_attribute|
real_attribute = Attribute.find_by(friendly_id: raw_attribute.fetch("friendly_id"))
refute_nil real_attribute, "Attribute #{raw_attribute.fetch("friendly_id")} not found"
assert_equal raw_attribute["name"], real_attribute.name
assert_equal raw_attribute["handle"], real_attribute.handle
assert_equal raw_attribute["description"], real_attribute.description
assert_equal raw_attribute["friendly_id"], real_attribute.friendly_id
assert_equal raw_attribute["values"], real_attribute.values.map(&:friendly_id)
end
extended_attributes.each do |raw_attribute|
real_attribute = Attribute.find_by(friendly_id: raw_attribute.fetch("friendly_id"))
refute_nil real_attribute, "Attribute #{raw_attribute.fetch("friendly_id")} not found"
assert_equal raw_attribute["name"], real_attribute.name
assert_equal raw_attribute["handle"], real_attribute.handle
assert_equal raw_attribute["description"], real_attribute.description
assert_equal raw_attribute["friendly_id"], real_attribute.friendly_id
assert_equal raw_attribute["values_from"], real_attribute.values_from.friendly_id
end
end
test "Categories are consistent with categories/*.yml" do
@raw_verticals_data.flatten.each do |raw_category|
real_category = Category.find_by(id: raw_category.fetch("id"))
refute_nil real_category, "Category #{raw_category.fetch("id")} not found"
assert_equal raw_category.fetch("id"), real_category.id
assert_equal raw_category.fetch("name"), real_category.name
assert_equal raw_category.fetch("children").size, real_category.children.count
assert_equal raw_category.fetch("children").sort, real_category.children.map(&:id).sort
assert_equal raw_category.fetch("attributes").sort, real_category.attributes.map(&:friendly_id).sort
assert_equal raw_category.fetch("secondary_children", []).sort, real_category.secondary_children.map(&:id).sort
end
end
# more fragile, but easier sanity check
test "Snowboards category <sg-4-17-2-17> is fully imported and modeled correctly" do
snowboard = Category.find_by(id: "sg-4-17-2-17")
assert_equal "Snowboards", snowboard.name
assert_empty snowboard.children
real_attribute_friendly_ids = snowboard.attributes.map(&:friendly_id)
assert_equal 8, real_attribute_friendly_ids.size
assert_includes real_attribute_friendly_ids, "age_group"
assert_includes real_attribute_friendly_ids, "color"
assert_includes real_attribute_friendly_ids, "pattern"
assert_includes real_attribute_friendly_ids, "recommended_skill_level"
assert_includes real_attribute_friendly_ids, "snowboard_design"
assert_includes real_attribute_friendly_ids, "snowboarding_style"
assert_includes real_attribute_friendly_ids, "target_gender"
assert_includes real_attribute_friendly_ids, "snowboard_construction"
end
# more fragile, but easier sanity check
test "Snowboard construction attribute <snowboard_construction> is fully imported and modeled correctly" do
snowboard_construction = Attribute.find_by(friendly_id: "snowboard_construction")
assert_equal "Snowboard construction", snowboard_construction.name
assert_equal "snowboard_construction", snowboard_construction.friendly_id
real_value_friendly_ids = snowboard_construction.values.map(&:friendly_id)
assert_equal 5, real_value_friendly_ids.size
assert_includes real_value_friendly_ids, "snowboard_construction__camber"
assert_includes real_value_friendly_ids, "snowboard_construction__flat"
assert_includes real_value_friendly_ids, "snowboard_construction__hybrid"
assert_includes real_value_friendly_ids, "snowboard_construction__rocker"
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/integration/generate_mappings_dist_test.rb | dev/test/integration/generate_mappings_dist_test.rb | # frozen_string_literal: true
require_relative "../test_helper"
require "tmpdir"
module ProductTaxonomy
class GenerateMappingsDistTest < TestCase
FIXTURES_PATH = File.expand_path("../fixtures", __dir__)
setup do
@tmp_path = Dir.mktmpdir
@current_shopify_version = "2025-01-unstable"
# Create categories so they can be resolved
aa = Category.new(id: "aa", name: "Apparel & Accessories")
aa_1 = Category.new(id: "aa-1", name: "Clothing")
aa_2 = Category.new(id: "aa-2", name: "Clothing Accessories")
aa_3 = Category.new(id: "aa-3", name: "Costumes & Accessories")
aa.add_child(aa_1)
aa.add_child(aa_2)
aa.add_child(aa_3)
Category.add(aa)
Category.add(aa_1)
Category.add(aa_2)
Category.add(aa_3)
end
teardown do
FileUtils.remove_entry(@tmp_path)
end
test "IntegrationVersion.generate_all_distributions generates all_mappings.json and distribution files for all integration versions" do
IntegrationVersion.generate_all_distributions(
output_path: @tmp_path,
current_shopify_version: @current_shopify_version,
logger: stub("logger", info: nil),
base_path: File.expand_path("data/integrations", FIXTURES_PATH),
)
assert_file_matches_fixture "all_mappings.json"
assert_file_matches_fixture "shopify/shopify_2020-01_to_shopify_2025-01.json"
assert_file_matches_fixture "shopify/shopify_2020-01_to_shopify_2025-01.txt"
assert_file_matches_fixture "shopify/shopify_2021-01_to_shopify_2025-01.json"
assert_file_matches_fixture "shopify/shopify_2021-01_to_shopify_2025-01.txt"
assert_file_matches_fixture "shopify/shopify_2022-01_to_shopify_2025-01.json"
assert_file_matches_fixture "shopify/shopify_2022-01_to_shopify_2025-01.txt"
assert_file_matches_fixture "foocommerce/shopify_2025-01_to_foocommerce_1.0.0.json"
assert_file_matches_fixture "foocommerce/shopify_2025-01_to_foocommerce_1.0.0.txt"
end
def assert_file_matches_fixture(file_path)
fixture_path = File.expand_path("dist/en/integrations/#{file_path}", FIXTURES_PATH)
expected_path = File.expand_path("en/integrations/#{file_path}", @tmp_path)
assert(File.exist?(expected_path), "Expected file to exist: #{expected_path}")
assert_equal(File.read(fixture_path), File.read(expected_path), "File contents don't match for: #{file_path}")
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/commands/dump_values_command_test.rb | dev/test/commands/dump_values_command_test.rb | # frozen_string_literal: true
require "test_helper"
require "tmpdir"
module ProductTaxonomy
class DumpValuesCommandTest < TestCase
setup do
@tmp_base_path = Dir.mktmpdir
@real_base_path = File.expand_path("..", ProductTaxonomy.data_path)
FileUtils.mkdir_p(File.expand_path("data", @tmp_base_path))
ProductTaxonomy.stubs(:data_path).returns(File.expand_path("data", @tmp_base_path))
Command.any_instance.stubs(:load_taxonomy)
end
teardown do
FileUtils.remove_entry(@tmp_base_path)
end
test "execute dumps values to YAML file" do
mock_data = [{ "id" => 1, "name" => "Test Value", "friendly_id" => "test__value", "handle" => "test__value" }]
Serializers::Value::Data::DataSerializer.stubs(:serialize_all)
.returns(mock_data)
command = DumpValuesCommand.new({})
command.execute
expected_path = File.expand_path("data/values.yml", @tmp_base_path)
expected_content = "---\n- id: 1\n name: Test Value\n friendly_id: test__value\n handle: test__value\n"
assert File.exist?(expected_path)
assert_equal expected_content, File.read(expected_path)
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/commands/command_test.rb | dev/test/commands/command_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class CommandTest < TestCase
class TestCommand < Command
def execute
logger.debug("Debug message")
logger.info("Info message")
logger.error("Error message")
end
end
test "run runs the command and prints the elapsed time" do
assert_output("Info message\nError message\nCompleted in 0.1 seconds\n") do
Benchmark.stubs(:realtime).returns(0.1).yields
TestCommand.new({}).run
end
end
test "run suppresses non-error output when quiet is true" do
assert_output("Error message\n") do
Benchmark.stubs(:realtime).returns(0.1).yields
TestCommand.new(quiet: true).run
end
end
test "run prints verbose output when verbose is true" do
assert_output("Debug message\nInfo message\nError message\nCompleted in 0.1 seconds\n") do
Benchmark.stubs(:realtime).returns(0.1).yields
TestCommand.new(verbose: true).run
end
end
test "load_taxonomy loads taxonomy resources and runs post-loading validations" do
ProductTaxonomy::Category.stubs(:all).returns([])
ProductTaxonomy.stubs(:data_path).returns("/fake/path")
YAML.stubs(:load_file).returns({})
Dir.stubs(:glob).returns(["/fake/path/categories/test.yml"])
YAML.stubs(:safe_load_file).returns([])
ProductTaxonomy::Value.expects(:load_from_source).once
ProductTaxonomy::Attribute.expects(:load_from_source).once
ProductTaxonomy::Category.expects(:load_from_source).once
command = TestCommand.new({})
mock_value = mock("value")
ProductTaxonomy::Value.expects(:all).returns([mock_value])
mock_value.expects(:validate!).with(:taxonomy_loaded)
command.load_taxonomy
end
test "load_taxonomy skips loading if categories already exist" do
ProductTaxonomy::Category.stubs(:all).returns([Category.new(id: "aa", name: "Test")])
ProductTaxonomy::Value.expects(:load_from_source).never
ProductTaxonomy::Attribute.expects(:load_from_source).never
ProductTaxonomy::Category.expects(:load_from_source).never
command = TestCommand.new({})
command.expects(:run_taxonomy_loaded_validations).never
command.load_taxonomy
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/commands/dump_categories_command_test.rb | dev/test/commands/dump_categories_command_test.rb | # frozen_string_literal: true
require "test_helper"
require "tmpdir"
module ProductTaxonomy
class DumpCategoriesCommandTest < TestCase
setup do
@tmp_base_path = Dir.mktmpdir
@real_base_path = File.expand_path("..", ProductTaxonomy.data_path)
FileUtils.mkdir_p(File.expand_path("data/categories", @tmp_base_path))
ProductTaxonomy.stubs(:data_path).returns(File.expand_path("data", @tmp_base_path))
Command.any_instance.stubs(:load_taxonomy)
@mock_vertical = stub(
id: "test_vertical",
name: "Test Vertical",
friendly_name: "tv_test_vertical",
root?: true,
)
end
teardown do
FileUtils.remove_entry(@tmp_base_path)
end
test "initialize sets verticals to all verticals when not specified" do
Category.stubs(:verticals).returns([@mock_vertical])
command = DumpCategoriesCommand.new({})
assert_equal ["test_vertical"], command.instance_variable_get(:@verticals)
end
test "initialize accepts custom verticals" do
command = DumpCategoriesCommand.new(verticals: ["custom_vertical"])
assert_equal ["custom_vertical"], command.instance_variable_get(:@verticals)
end
test "execute dumps specified vertical to YAML file" do
Category.stubs(:find_by).with(id: "test_vertical").returns(@mock_vertical)
Serializers::Category::Data::DataSerializer.stubs(:serialize_all)
.with(@mock_vertical)
.returns({ "test" => "data" })
command = DumpCategoriesCommand.new(verticals: ["test_vertical"])
command.execute
expected_path = File.expand_path("data/categories/tv_test_vertical.yml", @tmp_base_path)
assert File.exist?(expected_path)
assert_equal "---\ntest: data\n", File.read(expected_path)
end
test "execute raises error when vertical is not found" do
Category.stubs(:find_by).with(id: "nonexistent").returns(nil)
command = DumpCategoriesCommand.new(verticals: ["nonexistent"])
assert_raises(Indexed::NotFoundError) do
command.execute
end
end
test "execute raises error when category is not a vertical" do
non_vertical = stub(
id: "non_vertical",
name: "Non Vertical",
friendly_name: "nv_non_vertical",
root?: false,
)
Category.stubs(:find_by).with(id: "non_vertical").returns(non_vertical)
command = DumpCategoriesCommand.new(verticals: ["non_vertical"])
assert_raises(RuntimeError) do
command.execute
end
end
test "execute dumps multiple verticals" do
second_vertical = stub(
id: "second_vertical",
name: "Second Vertical",
friendly_name: "sv_second_vertical",
root?: true,
)
Category.stubs(:find_by).with(id: "test_vertical").returns(@mock_vertical)
Category.stubs(:find_by).with(id: "second_vertical").returns(second_vertical)
Serializers::Category::Data::DataSerializer.stubs(:serialize_all)
.with(@mock_vertical)
.returns({ "test" => "data1" })
Serializers::Category::Data::DataSerializer.stubs(:serialize_all)
.with(second_vertical)
.returns({ "test" => "data2" })
command = DumpCategoriesCommand.new(verticals: ["test_vertical", "second_vertical"])
command.execute
first_path = File.expand_path("data/categories/tv_test_vertical.yml", @tmp_base_path)
second_path = File.expand_path("data/categories/sv_second_vertical.yml", @tmp_base_path)
assert File.exist?(first_path)
assert File.exist?(second_path)
assert_equal "---\ntest: data1\n", File.read(first_path)
assert_equal "---\ntest: data2\n", File.read(second_path)
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/commands/add_category_command_test.rb | dev/test/commands/add_category_command_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class AddCategoryCommandTest < TestCase
setup do
@root_category = Category.new(id: "aa", name: "Root Category")
@child_category = Category.new(id: "aa-1", name: "Child Category", parent: @root_category)
@root_category.add_child(@child_category)
Category.add(@root_category)
Category.add(@child_category)
end
test "execute successfully adds a new category" do
DumpCategoriesCommand.any_instance.expects(:execute).once
SyncEnLocalizationsCommand.any_instance.expects(:execute).once
GenerateDocsCommand.any_instance.expects(:execute).once
AddCategoryCommand.new(name: "New Category", parent_id: "aa").execute
new_category = @root_category.children.find { |c| c.name == "New Category" }
assert_not_nil new_category
assert_equal "aa-2", new_category.id # Since aa-1 already exists
assert_equal "New Category", new_category.name
assert_equal @root_category, new_category.parent
assert_not_nil Category.find_by(id: "aa-2")
end
test "execute successfully adds a category with custom numeric ID" do
DumpCategoriesCommand.any_instance.expects(:execute).once
SyncEnLocalizationsCommand.any_instance.expects(:execute).once
GenerateDocsCommand.any_instance.expects(:execute).once
AddCategoryCommand.new(name: "Custom ID Category", parent_id: "aa", id: "aa-5").execute
new_category = @root_category.children.find { |c| c.name == "Custom ID Category" }
assert_not_nil new_category
assert_equal "aa-5", new_category.id
assert_equal "Custom ID Category", new_category.name
assert_equal @root_category, new_category.parent
assert_not_nil Category.find_by(id: "aa-5")
end
test "execute raises error when parent category not found" do
stub_commands
assert_raises(Indexed::NotFoundError) do
AddCategoryCommand.new(name: "New Category", parent_id: "nonexistent").execute
end
end
test "execute raises error when category ID already exists" do
stub_commands
assert_raises(ActiveModel::ValidationError) do
AddCategoryCommand.new(name: "Duplicate ID", parent_id: "aa", id: "aa-1").execute
end
end
test "execute raises error when category ID format is invalid" do
stub_commands
assert_raises(ActiveModel::ValidationError) do
AddCategoryCommand.new(name: "Invalid ID", parent_id: "aa", id: "aa-custom").execute
end
end
test "execute raises error when category name is invalid" do
stub_commands
assert_raises(ActiveModel::ValidationError) do
AddCategoryCommand.new(name: "", parent_id: "aa").execute
end
end
test "execute updates correct vertical based on parent category" do
DumpCategoriesCommand.expects(:new).with(verticals: ["aa"]).returns(stub(execute: true))
SyncEnLocalizationsCommand.any_instance.stubs(:execute)
GenerateDocsCommand.any_instance.stubs(:execute)
AddCategoryCommand.new(name: "New Category", parent_id: "aa").execute
new_category = @root_category.children.find { |c| c.name == "New Category" }
assert_not_nil new_category
assert_equal @root_category, new_category.parent
assert_not_nil Category.find_by(id: "aa-2")
end
test "execute generates sequential IDs correctly" do
stub_commands
AddCategoryCommand.new(name: "First New", parent_id: "aa").execute
AddCategoryCommand.new(name: "Second New", parent_id: "aa").execute
new_categories = @root_category.children.select { |c| c.name.include?("New") }.sort_by(&:id)
assert_equal 2, new_categories.size
assert_equal "aa-2", new_categories[0].id
assert_equal "aa-3", new_categories[1].id
assert_equal "First New", new_categories[0].name
assert_equal "Second New", new_categories[1].name
assert_not_nil Category.find_by(id: "aa-2")
assert_not_nil Category.find_by(id: "aa-3")
end
private
def stub_commands
DumpCategoriesCommand.any_instance.stubs(:execute)
SyncEnLocalizationsCommand.any_instance.stubs(:execute)
GenerateDocsCommand.any_instance.stubs(:execute)
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/commands/add_attribute_command_test.rb | dev/test/commands/add_attribute_command_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class AddAttributeCommandTest < TestCase
setup do
@base_attribute = Attribute.new(
id: 1,
name: "Color",
description: "Defines the primary color or pattern",
friendly_id: "color",
handle: "color",
values: [
Value.new(
id: 1,
name: "Black",
friendly_id: "color__black",
handle: "color__black",
),
],
)
Attribute.add(@base_attribute)
Value.add(@base_attribute.values.first)
AddAttributeCommand.any_instance.stubs(:load_taxonomy)
DumpAttributesCommand.any_instance.stubs(:load_taxonomy)
DumpValuesCommand.any_instance.stubs(:load_taxonomy)
SyncEnLocalizationsCommand.any_instance.stubs(:load_taxonomy)
GenerateDocsCommand.any_instance.stubs(:load_taxonomy)
end
test "execute successfully adds a new base attribute with values" do
DumpAttributesCommand.any_instance.expects(:execute).once
DumpValuesCommand.any_instance.expects(:execute).once
SyncEnLocalizationsCommand.any_instance.expects(:execute).once
GenerateDocsCommand.any_instance.expects(:execute).once
AddAttributeCommand.new(
name: "Size",
description: "Product size information",
values: "Small, Medium, Large",
).execute
new_attribute = Attribute.find_by(friendly_id: "size")
assert_not_nil new_attribute
assert_equal 2, new_attribute.id # Since id 1 already exists
assert_equal "Size", new_attribute.name
assert_equal "Product size information", new_attribute.description
assert_equal "size", new_attribute.friendly_id
assert_equal "size", new_attribute.handle
assert_equal 3, new_attribute.values.size
value_names = new_attribute.values.map(&:name)
assert_includes value_names, "Small"
assert_includes value_names, "Medium"
assert_includes value_names, "Large"
value_friendly_ids = new_attribute.values.map(&:friendly_id)
assert_includes value_friendly_ids, "size__small"
assert_includes value_friendly_ids, "size__medium"
assert_includes value_friendly_ids, "size__large"
end
test "execute successfully adds an extended attribute" do
DumpAttributesCommand.any_instance.expects(:execute).once
DumpValuesCommand.any_instance.expects(:execute).once
SyncEnLocalizationsCommand.any_instance.expects(:execute).once
GenerateDocsCommand.any_instance.expects(:execute).once
AddAttributeCommand.new(
name: "Clothing Color",
description: "Color of clothing items",
base_attribute_friendly_id: "color",
).execute
new_attribute = Attribute.find_by(friendly_id: "clothing_color")
assert_not_nil new_attribute
assert_instance_of ExtendedAttribute, new_attribute
assert_equal "Clothing Color", new_attribute.name
assert_equal "Color of clothing items", new_attribute.description
assert_equal "clothing_color", new_attribute.friendly_id
assert_equal "clothing-color", new_attribute.handle
assert_equal @base_attribute, new_attribute.base_attribute
assert_equal @base_attribute.values.size, new_attribute.values.size
assert_equal @base_attribute.values.first.name, new_attribute.values.first.name
end
test "execute raises error when creating base attribute without values" do
stub_commands
assert_raises(RuntimeError) do
AddAttributeCommand.new(
name: "Material",
description: "Product material information",
values: "",
).execute
end
end
test "execute raises error when creating extended attribute with values" do
stub_commands
assert_raises(RuntimeError) do
AddAttributeCommand.new(
name: "Clothing Color",
description: "Color of clothing items",
base_attribute_friendly_id: "color",
values: "Red, Blue",
).execute
end
end
test "execute raises error when base attribute for extended attribute doesn't exist" do
stub_commands
assert_raises(ActiveModel::ValidationError) do
AddAttributeCommand.new(
name: "Clothing Material",
description: "Material of clothing items",
base_attribute_friendly_id: "nonexistent",
).execute
end
end
test "execute raises error when attribute with same friendly_id already exists" do
stub_commands
assert_raises(ActiveModel::ValidationError) do
AddAttributeCommand.new(
name: "Color", # This will generate the same friendly_id as @base_attribute
description: "Another color attribute",
values: "Red, Blue",
).execute
end
end
test "execute creates values with correct friendly_ids and handles" do
stub_commands
AddAttributeCommand.new(
name: "Material Type",
description: "Type of material used",
values: "Cotton, Polyester",
).execute
new_attribute = Attribute.find_by(friendly_id: "material_type")
assert_not_nil new_attribute
cotton_value = new_attribute.values.find { |v| v.name == "Cotton" }
assert_not_nil cotton_value
assert_equal "material_type__cotton", cotton_value.friendly_id
assert_equal "material-type__cotton", cotton_value.handle
polyester_value = new_attribute.values.find { |v| v.name == "Polyester" }
assert_not_nil polyester_value
assert_equal "material_type__polyester", polyester_value.friendly_id
assert_equal "material-type__polyester", polyester_value.handle
end
test "execute reuses existing values with same friendly_id" do
existing_value = Value.new(
id: 2,
name: "Existing Cotton",
friendly_id: "material_type__cotton",
handle: "material_type__cotton",
)
Value.add(existing_value)
stub_commands
AddAttributeCommand.new(
name: "Material Type",
description: "Type of material used",
values: "Cotton, Polyester",
).execute
new_attribute = Attribute.find_by(friendly_id: "material_type")
assert_not_nil new_attribute
cotton_value = new_attribute.values.find { |v| v.friendly_id == "material_type__cotton" }
assert_not_nil cotton_value
assert_equal existing_value, cotton_value
assert_equal "Existing Cotton", cotton_value.name # Name from existing value
polyester_value = new_attribute.values.find { |v| v.name == "Polyester" }
assert_not_nil polyester_value
assert_equal "material_type__polyester", polyester_value.friendly_id
end
test "execute updates data files after creating attribute" do
DumpAttributesCommand.any_instance.expects(:execute).once
DumpValuesCommand.any_instance.expects(:execute).once
SyncEnLocalizationsCommand.expects(:new).with(targets: "attributes,values").returns(stub(execute: true))
GenerateDocsCommand.any_instance.expects(:execute).once
AddAttributeCommand.new(
name: "Size",
description: "Product size information",
values: "Small, Medium, Large",
).execute
end
private
def stub_commands
DumpAttributesCommand.any_instance.stubs(:execute)
DumpValuesCommand.any_instance.stubs(:execute)
SyncEnLocalizationsCommand.any_instance.stubs(:execute)
GenerateDocsCommand.any_instance.stubs(:execute)
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/commands/dump_attributes_command_test.rb | dev/test/commands/dump_attributes_command_test.rb | # frozen_string_literal: true
require "test_helper"
require "tmpdir"
module ProductTaxonomy
class DumpAttributesCommandTest < TestCase
setup do
@tmp_base_path = Dir.mktmpdir
@real_base_path = File.expand_path("..", ProductTaxonomy.data_path)
FileUtils.mkdir_p(File.expand_path("data", @tmp_base_path))
ProductTaxonomy.stubs(:data_path).returns(File.expand_path("data", @tmp_base_path))
Command.any_instance.stubs(:load_taxonomy)
end
teardown do
FileUtils.remove_entry(@tmp_base_path)
end
test "execute dumps attributes to YAML file" do
mock_data = { "test" => "data" }
Serializers::Attribute::Data::DataSerializer.stubs(:serialize_all)
.returns(mock_data)
command = DumpAttributesCommand.new({})
command.execute
expected_path = File.expand_path("data/attributes.yml", @tmp_base_path)
assert File.exist?(expected_path)
assert_equal "---\ntest: data\n", File.read(expected_path)
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/commands/add_attributes_to_categories_command_test.rb | dev/test/commands/add_attributes_to_categories_command_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class AddAttributesToCategoriesCommandTest < TestCase
setup do
@color_attribute = Attribute.new(
id: 1,
name: "Color",
description: "Defines the primary color or pattern",
friendly_id: "color",
handle: "color",
values: [
Value.new(
id: 1,
name: "Black",
friendly_id: "color__black",
handle: "color__black",
),
],
)
@size_attribute = Attribute.new(
id: 2,
name: "Size",
description: "Defines the size of the product",
friendly_id: "size",
handle: "size",
values: [
Value.new(
id: 2,
name: "Small",
friendly_id: "size__small",
handle: "size__small",
),
],
)
Attribute.add(@color_attribute)
Attribute.add(@size_attribute)
Value.add(@color_attribute.values.first)
Value.add(@size_attribute.values.first)
@root = Category.new(id: "aa", name: "Apparel & Accessories")
@clothing = Category.new(id: "aa-1", name: "Clothing")
@shirts = Category.new(id: "aa-1-1", name: "Shirts")
@root.add_child(@clothing)
@clothing.add_child(@shirts)
Category.add(@root)
Category.add(@clothing)
Category.add(@shirts)
AddAttributesToCategoriesCommand.any_instance.stubs(:load_taxonomy)
DumpCategoriesCommand.any_instance.stubs(:load_taxonomy)
SyncEnLocalizationsCommand.any_instance.stubs(:load_taxonomy)
GenerateDocsCommand.any_instance.stubs(:load_taxonomy)
end
test "execute adds attributes to specified categories" do
DumpCategoriesCommand.any_instance.expects(:execute).once
SyncEnLocalizationsCommand.any_instance.expects(:execute).once
GenerateDocsCommand.any_instance.expects(:execute).once
AddAttributesToCategoriesCommand.new(
attribute_friendly_ids: "color,size",
category_ids: "aa-1",
include_descendants: false
).execute
assert_equal 2, @clothing.attributes.size
assert_includes @clothing.attributes, @color_attribute
assert_includes @clothing.attributes, @size_attribute
assert_empty @root.attributes
assert_empty @shirts.attributes
end
test "execute adds attributes to categories and their descendants when include_descendants is true" do
DumpCategoriesCommand.any_instance.expects(:execute).once
SyncEnLocalizationsCommand.any_instance.expects(:execute).once
GenerateDocsCommand.any_instance.expects(:execute).once
AddAttributesToCategoriesCommand.new(
attribute_friendly_ids: "color",
category_ids: "aa-1",
include_descendants: true
).execute
assert_equal 1, @clothing.attributes.size
assert_includes @clothing.attributes, @color_attribute
assert_equal 1, @shirts.attributes.size
assert_includes @shirts.attributes, @color_attribute
assert_empty @root.attributes
end
test "execute adds attributes to multiple categories" do
DumpCategoriesCommand.any_instance.expects(:execute).once
SyncEnLocalizationsCommand.any_instance.expects(:execute).once
GenerateDocsCommand.any_instance.expects(:execute).once
AddAttributesToCategoriesCommand.new(
attribute_friendly_ids: "color",
category_ids: "aa,aa-1",
include_descendants: false
).execute
assert_equal 1, @root.attributes.size
assert_includes @root.attributes, @color_attribute
assert_equal 1, @clothing.attributes.size
assert_includes @clothing.attributes, @color_attribute
assert_empty @shirts.attributes
end
test "execute skips adding attributes that are already present" do
@clothing.add_attribute(@color_attribute)
DumpCategoriesCommand.any_instance.expects(:execute).once
SyncEnLocalizationsCommand.any_instance.expects(:execute).once
GenerateDocsCommand.any_instance.expects(:execute).once
AddAttributesToCategoriesCommand.new(
attribute_friendly_ids: "color,size",
category_ids: "aa-1",
include_descendants: false
).execute
assert_equal 2, @clothing.attributes.size
assert_includes @clothing.attributes, @color_attribute
assert_includes @clothing.attributes, @size_attribute
assert_equal 1, @clothing.attributes.count { |attr| attr == @color_attribute }
end
test "execute raises error when attribute is not found" do
assert_raises(Indexed::NotFoundError) do
AddAttributesToCategoriesCommand.new(
attribute_friendly_ids: "nonexistent",
category_ids: "aa-1",
include_descendants: false
).execute
end
end
test "execute raises error when category is not found" do
assert_raises(Indexed::NotFoundError) do
AddAttributesToCategoriesCommand.new(
attribute_friendly_ids: "color",
category_ids: "nonexistent",
include_descendants: false
).execute
end
end
test "execute updates data files for all affected root categories" do
# When adding attributes to categories from different verticals,
# the command should update data files for all affected root categories
@second_root = Category.new(id: "bb", name: "Business & Industrial")
@equipment = Category.new(id: "bb-1", name: "Equipment")
@second_root.add_child(@equipment)
Category.add(@second_root)
Category.add(@equipment)
dump_command = mock
dump_command.expects(:execute).once
DumpCategoriesCommand.expects(:new).with(verticals: ["aa", "bb"]).returns(dump_command)
SyncEnLocalizationsCommand.any_instance.expects(:execute).once
GenerateDocsCommand.any_instance.expects(:execute).once
AddAttributesToCategoriesCommand.new(
attribute_friendly_ids: "color",
category_ids: "aa-1,bb-1",
include_descendants: false
).execute
assert_equal 1, @clothing.attributes.size
assert_includes @clothing.attributes, @color_attribute
assert_equal 1, @equipment.attributes.size
assert_includes @equipment.attributes, @color_attribute
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/commands/generate_release_command_test.rb | dev/test/commands/generate_release_command_test.rb | # frozen_string_literal: true
require "test_helper"
require "tmpdir"
module ProductTaxonomy
class GenerateReleaseCommandTest < TestCase
setup do
@tmp_base_path = Dir.mktmpdir
@version = "2024-01"
@next_version = "2024-02-unstable"
@version_file_path = File.expand_path("VERSION", @tmp_base_path)
@release_branch = "release-v#{@version}"
# Create test files and directories
FileUtils.mkdir_p(File.expand_path("dist", @tmp_base_path))
FileUtils.mkdir_p(File.expand_path("data/integrations/shopify/2023-12/mappings", @tmp_base_path))
FileUtils.mkdir_p(File.expand_path("data/integrations/shopify/2022-01/mappings", @tmp_base_path))
FileUtils.mkdir_p(File.expand_path("data/integrations/shopify/2022-10/mappings", @tmp_base_path))
FileUtils.mkdir_p(File.expand_path("data/integrations/google/2023-12/mappings", @tmp_base_path))
# Create VERSION file
File.write(@version_file_path, "2023-12")
# Create README files
File.write(
File.expand_path("README.md", @tmp_base_path),
'<img src="https://img.shields.io/badge/Version-2023--12-blue.svg" alt="Version">',
)
File.write(
File.expand_path("dist/README.md", @tmp_base_path),
'<img src="https://img.shields.io/badge/Version-2023--12-blue.svg" alt="Version">',
)
# Create test mapping files
File.write(
File.expand_path("data/integrations/shopify/2023-12/mappings/to_shopify.yml", @tmp_base_path),
"output_taxonomy: shopify/2023-12-unstable",
)
File.write(
File.expand_path("data/integrations/shopify/2022-01/mappings/to_shopify.yml", @tmp_base_path),
"input_taxonomy: shopify/2022-01-unstable",
)
File.write(
File.expand_path("data/integrations/shopify/2022-10/mappings/to_shopify.yml", @tmp_base_path),
"input_taxonomy: shopify/2022-07-unstable",
)
File.write(
File.expand_path("data/integrations/google/2023-12/mappings/from_shopify.yml", @tmp_base_path),
"input_taxonomy: shopify/2023-12-unstable",
)
# Stub dependencies
Command.any_instance.stubs(:version_file_path).returns(@version_file_path)
Command.any_instance.stubs(:load_taxonomy)
ProductTaxonomy.stubs(:data_path).returns("#{@tmp_base_path}/data")
# Stub git operations
command_stub = GenerateReleaseCommand.any_instance
command_stub.stubs(:run_git_command).returns(true)
command_stub.stubs(:get_commit_hash).returns("abc1234")
command_stub.stubs(:git_repo_root).returns(@tmp_base_path)
# Stub git branch and status check to pass by default
command_stub.stubs(:`).with("git rev-parse --abbrev-ref HEAD").returns("main\n")
command_stub.stubs(:`).with("git status --porcelain").returns("")
# Stub command executions
GenerateDistCommand.any_instance.stubs(:execute)
GenerateDocsCommand.any_instance.stubs(:execute)
DumpIntegrationFullNamesCommand.any_instance.stubs(:execute)
end
teardown do
FileUtils.remove_entry(@tmp_base_path)
end
test "initialize sets version from options if provided" do
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version)
assert_equal @version, command.instance_variable_get(:@version)
assert_equal @next_version, command.instance_variable_get(:@next_version)
end
test "initialize raises error if current_version ends with -unstable" do
assert_raises ArgumentError do
GenerateReleaseCommand.new(current_version: "2024-01-unstable", next_version: @next_version)
end
end
test "initialize raises error if next_version doesn't end with -unstable" do
assert_raises ArgumentError do
GenerateReleaseCommand.new(current_version: @version, next_version: "2024-02")
end
end
test "initialize sets all locales when 'all' is specified" do
Command.any_instance.stubs(:locales_defined_in_data_path).returns(["en", "fr", "es"])
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version, locales: ["all"])
assert_equal ["en", "fr", "es"], command.instance_variable_get(:@locales)
end
test "initialize sets specific locales when provided" do
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version, locales: ["en", "fr"])
assert_equal ["en", "fr"], command.instance_variable_get(:@locales)
end
test "execute performs release version steps and next version steps" do
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version, locales: ["en"])
command.expects(:run_git_command).with("pull")
command.expects(:run_git_command).with("checkout", "-b", @release_branch)
command.expects(:run_git_command).with("add", ".").times(2)
command.expects(:run_git_command).with("commit", "-m", "Release version #{@version}")
command.expects(:run_git_command).with("commit", "-m", "Bump version to #{@next_version}")
command.expects(:run_git_command).with("tag", "v#{@version}")
GenerateDistCommand.any_instance.expects(:execute).times(2)
GenerateDocsCommand.any_instance.expects(:execute).times(2)
DumpIntegrationFullNamesCommand.any_instance.expects(:execute)
command.execute
assert_equal @next_version, File.read(@version_file_path)
end
test "execute raises error when not on main branch" do
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version)
command.unstub(:`)
command.stubs(:`).with("git rev-parse --abbrev-ref HEAD").returns("feature/new-stuff\n")
command.stubs(:`).with("git status --porcelain").returns("")
assert_raises(RuntimeError) do
command.execute
end
end
test "execute raises error when working directory is not clean" do
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version)
command.unstub(:`)
command.stubs(:`).with("git rev-parse --abbrev-ref HEAD").returns("main\n")
command.stubs(:`).with("git status --porcelain").returns(" M dev/lib/product_taxonomy/commands/generate_release_command.rb\n")
assert_raises(RuntimeError) do
command.execute
end
end
test "execute updates integration mapping files" do
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version)
command.execute
to_shopify_content = File.read(File.expand_path("data/integrations/shopify/2023-12/mappings/to_shopify.yml", @tmp_base_path))
from_shopify_content = File.read(File.expand_path("data/integrations/google/2023-12/mappings/from_shopify.yml", @tmp_base_path))
assert_equal "output_taxonomy: shopify/#{@version}", to_shopify_content
assert_equal "input_taxonomy: shopify/#{@next_version}", from_shopify_content
end
test "execute updates taxonomy fields in mapping files" do
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version)
command.execute
# After execute, to_shopify should have the stable version
to_shopify_content = File.read(File.expand_path("data/integrations/shopify/2023-12/mappings/to_shopify.yml", @tmp_base_path))
assert_match "output_taxonomy: shopify/#{@version}", to_shopify_content
refute_match "output_taxonomy: shopify/2023-12-unstable", to_shopify_content
# After execute, from_shopify should have the next unstable version
from_shopify_content = File.read(File.expand_path("data/integrations/google/2023-12/mappings/from_shopify.yml", @tmp_base_path))
assert_match "input_taxonomy: shopify/#{@next_version}", from_shopify_content
refute_match "input_taxonomy: shopify/2023-12-unstable", from_shopify_content
end
test "execute updates input and output taxonomies for integrations in two stages" do
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version)
# Initial state (from setup) for reference:
# to_shopify.yml contains "output_taxonomy: shopify/2023-12-unstable"
# from_shopify.yml contains "input_taxonomy: shopify/2023-12-unstable"
# Basically the call sequence for execute is:
# 1. check_git_state!
# 2. generate_release_version!
# 3. move_to_next_version!
command.send(:check_git_state!)
command.send(:generate_release_version!)
to_shopify_content_stage1 = File.read(File.expand_path("data/integrations/shopify/2023-12/mappings/to_shopify.yml", @tmp_base_path))
from_shopify_content_stage1 = File.read(File.expand_path("data/integrations/google/2023-12/mappings/from_shopify.yml", @tmp_base_path))
assert_match "output_taxonomy: shopify/#{@version}",
to_shopify_content_stage1,
"After stage 1, to_shopify.yml output_taxonomy should be stable version (#{@version})"
assert_match "input_taxonomy: shopify/#{@version}",
from_shopify_content_stage1,
"After stage 1, from_shopify.yml input_taxonomy should be stable version (#{@version})"
refute_match "shopify/2023-12-unstable", to_shopify_content_stage1 unless "shopify/#{@version}" == "shopify/2023-12-unstable"
refute_match "shopify/2023-12-unstable", from_shopify_content_stage1 unless "shopify/#{@version}" == "shopify/2023-12-unstable"
command.send(:move_to_next_version!)
to_shopify_content_stage2 = File.read(File.expand_path("data/integrations/shopify/2023-12/mappings/to_shopify.yml", @tmp_base_path))
from_shopify_content_stage2 = File.read(File.expand_path("data/integrations/google/2023-12/mappings/from_shopify.yml", @tmp_base_path))
assert_match "output_taxonomy: shopify/#{@version}",
to_shopify_content_stage2,
"After stage 2, to_shopify.yml output_taxonomy should remain stable version (#{@version})"
refute_match "shopify/#{@next_version}",
to_shopify_content_stage2,
"After stage 2, to_shopify.yml output_taxonomy should NOT be next_version (#{@next_version})"
assert_match "input_taxonomy: shopify/#{@next_version}",
from_shopify_content_stage2,
"After stage 2, from_shopify.yml input_taxonomy should be next unstable version (#{@next_version})"
refute_match "input_taxonomy: shopify/#{@version}", from_shopify_content_stage2 unless @version == @next_version.gsub(/-unstable$/, "")
end
test "execute updates both README files version badges" do
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version)
command.execute
root_readme_content = File.read(File.expand_path("README.md", @tmp_base_path))
dist_readme_content = File.read(File.expand_path("dist/README.md", @tmp_base_path))
expected_badge = '<img src="https://img.shields.io/badge/Version-2024--01-blue.svg" alt="Version">'
assert_equal expected_badge, root_readme_content
assert_equal expected_badge, dist_readme_content
end
test "print_summary outputs expected format" do
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version)
expected_output = <<~OUTPUT
====== Release Summary ======
- Created commit (abc1234): Release version 2024-01
- Created commit (abc1234): Bump version to 2024-02-unstable
- Created tag: v2024-01
Inspect changes with:
git show abc1234
git show abc1234
git show v2024-01
Next steps:
1. If the changes look good, push the branch
* Run `git push origin release-v2024-01`
2. Open a PR and follow the usual process to get approval and merge
* https://github.com/Shopify/product-taxonomy/pull/new/release-v2024-01
3. Once the PR is merged, push the tag that was created
* Run `git push origin v2024-01`
4. Create a release on GitHub
* https://github.com/Shopify/product-taxonomy/releases/new?tag=v2024-01
OUTPUT
log_string = StringIO.new
logger = Logger.new(log_string)
logger.formatter = proc { |_, _, _, msg| "#{msg}\n" }
command.instance_variable_set(:@logger, logger)
command.send(:print_summary, "abc1234", "abc1234")
assert_equal expected_output, log_string.string
end
test "print_rollback_instructions outputs expected format when branch and tag exist" do
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version)
expected_output = <<~OUTPUT
====== Rollback Instructions ======
The release was aborted due to an error.
You can use the following commands to roll back to the original state:
git reset --hard main
git branch -D release-v2024-01
git tag -d v2024-01
OUTPUT
log_string = StringIO.new
logger = Logger.new(log_string)
logger.formatter = proc { |_, _, _, msg| "#{msg}\n" }
command.instance_variable_set(:@logger, logger)
# Stub system calls to simulate branch and tag existing
command.stubs(:system).with("git", "show-ref", "--verify", "--quiet", "refs/heads/release-v#{@version}").returns(true)
command.stubs(:system).with("git", "show-ref", "--verify", "--quiet", "refs/tags/v#{@version}").returns(true)
command.send(:print_rollback_instructions)
assert_equal expected_output, log_string.string
end
test "print_rollback_instructions outputs expected format when branch and tag don't exist" do
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version)
expected_output = <<~OUTPUT
====== Rollback Instructions ======
The release was aborted due to an error.
You can use the following commands to roll back to the original state:
git reset --hard main
OUTPUT
log_string = StringIO.new
logger = Logger.new(log_string)
logger.formatter = proc { |_, _, _, msg| "#{msg}\n" }
command.instance_variable_set(:@logger, logger)
# Stub system calls to simulate branch and tag not existing
command.stubs(:system).with("git", "show-ref", "--verify", "--quiet", "refs/heads/release-v#{@version}").returns(false)
command.stubs(:system).with("git", "show-ref", "--verify", "--quiet", "refs/tags/v#{@version}").returns(false)
command.send(:print_rollback_instructions)
assert_equal expected_output, log_string.string
end
test "execute handles errors and prints rollback instructions" do
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version)
# Simulate failure during execution
command.expects(:generate_release_version!).raises(StandardError.new("Test error"))
command.expects(:print_rollback_instructions)
assert_raises(StandardError) do
command.execute
end
end
test "run_git_command raises error when git command fails" do
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version)
GenerateReleaseCommand.any_instance.unstub(:run_git_command)
command.stubs(:git_repo_root).returns(@tmp_base_path)
command.expects(:system).with("git", "checkout", "main", chdir: @tmp_base_path).returns(false)
command.expects(:raise).with(regexp_matches(/Git command failed/))
command.send(:run_git_command, "checkout", "main")
end
test "git_repo_root memoizes git repository root path" do
GenerateReleaseCommand.any_instance.unstub(:git_repo_root)
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version)
command.expects(:`).with("git rev-parse --show-toplevel").returns("/repo/path\n").once
assert_equal "/repo/path", command.send(:git_repo_root)
assert_equal "/repo/path", command.send(:git_repo_root) # Should use memoized value
end
test "update_mapping_files handles to_shopify.yml files specially" do
older_shopify_version = "2022-10"
latest_shopify_version = "2023-12"
older_shopify_dir = File.expand_path("data/integrations/shopify/#{older_shopify_version}/mappings", @tmp_base_path)
latest_shopify_dir = File.expand_path("data/integrations/shopify/#{latest_shopify_version}/mappings", @tmp_base_path)
FileUtils.mkdir_p(older_shopify_dir)
FileUtils.mkdir_p(latest_shopify_dir)
older_shopify_file = File.join(older_shopify_dir, "to_shopify.yml")
latest_shopify_file = File.join(latest_shopify_dir, "to_shopify.yml")
File.write(older_shopify_file, "output_taxonomy: shopify/#{older_shopify_version}-unstable")
File.write(latest_shopify_file, "output_taxonomy: shopify/#{latest_shopify_version}-unstable")
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version)
command.send(:update_mapping_files, "to_shopify.yml", "output_taxonomy", "shopify/#{@version}")
assert_equal "output_taxonomy: shopify/#{older_shopify_version}-unstable", File.read(older_shopify_file)
assert_equal "output_taxonomy: shopify/#{@version}", File.read(latest_shopify_file)
end
test "update_mapping_files updates all from_shopify.yml files in non-shopify integrations" do
other_integration_dir = File.expand_path("data/integrations/other/mappings", @tmp_base_path)
FileUtils.mkdir_p(other_integration_dir)
other_integration_file = File.join(other_integration_dir, "from_shopify.yml")
File.write(other_integration_file, "input_taxonomy: shopify/2023-12-unstable")
command = GenerateReleaseCommand.new(current_version: @version, next_version: @next_version)
command.send(:update_mapping_files, "from_shopify.yml", "input_taxonomy", "shopify/#{@version}")
assert_equal "input_taxonomy: shopify/#{@version}", File.read(other_integration_file)
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/commands/generate_docs_command_test.rb | dev/test/commands/generate_docs_command_test.rb | # frozen_string_literal: true
require "test_helper"
require "tmpdir"
module ProductTaxonomy
class GenerateDocsCommandTest < TestCase
setup do
@tmp_base_path = Dir.mktmpdir
@real_base_path = File.expand_path("..", ProductTaxonomy.data_path)
# Create test files
FileUtils.mkdir_p(File.expand_path("data", @tmp_base_path))
FileUtils.mkdir_p(File.expand_path("dist/en/integrations", @tmp_base_path))
File.write(
File.expand_path("dist/en/integrations/all_mappings.json", @tmp_base_path),
JSON.fast_generate({
"mappings" => [{
"input_taxonomy" => ["shopify"],
"output_taxonomy" => ["external"],
"rules" => [{
"input" => { "category" => "test" },
"output" => { "category" => ["mapped"] },
}],
}],
}),
)
# Copy template files
FileUtils.mkdir_p(File.expand_path("docs/_releases", @tmp_base_path))
FileUtils.cp(
File.expand_path("docs/_releases/_index_template.html", @real_base_path),
File.expand_path("docs/_releases/_index_template.html", @tmp_base_path),
)
FileUtils.cp(
File.expand_path("docs/_releases/_attributes_template.html", @real_base_path),
File.expand_path("docs/_releases/_attributes_template.html", @tmp_base_path),
)
# Create a dummy latest.html for tests that update it
latest_html_dir = File.expand_path("docs/_releases", @tmp_base_path)
FileUtils.mkdir_p(latest_html_dir)
File.write(File.join(latest_html_dir, "latest.html"), <<~HTML)
---
title: latest
include_in_release_list: true
redirect_to: /releases/setup/
---
HTML
GenerateDocsCommand.stubs(:docs_path).returns(File.expand_path("docs", @tmp_base_path))
Command.any_instance.stubs(:load_taxonomy)
Serializers::Category::Docs::SiblingsSerializer.stubs(:serialize_all).returns({ "siblings" => "foo" })
Serializers::Category::Docs::SearchSerializer.stubs(:serialize_all).returns([{ "search" => "bar" }])
Serializers::Attribute::Docs::BaseAndExtendedSerializer.stubs(:serialize_all).returns({ "attributes" => "baz" })
Serializers::Attribute::Docs::ReversedSerializer.stubs(:serialize_all).returns({ "reversed" => "qux" })
Serializers::Attribute::Docs::SearchSerializer.stubs(:serialize_all).returns([{ "attribute_search" => "quux" }])
end
teardown do
FileUtils.remove_entry(@tmp_base_path)
end
test "initialize sets version to unstable by default" do
command = GenerateDocsCommand.new({})
assert_equal "unstable", command.instance_variable_get(:@version)
end
test "initialize accepts custom version" do
command = GenerateDocsCommand.new(version: "2024-01")
assert_equal "2024-01", command.instance_variable_get(:@version)
end
test "initialize raises error for invalid version format with special characters" do
assert_raises(ArgumentError) do
GenerateDocsCommand.new(version: "2024@01")
end
end
test "initialize raises error for version containing double dots" do
assert_raises(ArgumentError) do
GenerateDocsCommand.new(version: "2024..01")
end
end
test "run executes command and prints expected output for unstable version" do
expected_output = <<~OUTPUT
Version: unstable
Generating sibling groups...
Generating category search index...
Generating attributes...
Generating mappings...
Generating attributes with categories...
Generating attribute with categories search index...
Completed in 0.1 seconds
OUTPUT
assert_output(expected_output) do
Benchmark.stubs(:realtime).returns(0.1).yields
GenerateDocsCommand.new({}).run
end
end
test "run executes command and prints expected output for versioned release" do
expected_output = <<~OUTPUT
Version: 2024-01
Generating sibling groups...
Generating category search index...
Generating attributes...
Generating mappings...
Generating attributes with categories...
Generating attribute with categories search index...
Generating release folder...
Generating index.html...
Generating attributes.html...
Updating latest.html redirect...
Completed in 0.1 seconds
OUTPUT
assert_output(expected_output) do
Benchmark.stubs(:realtime).returns(0.1).yields
GenerateDocsCommand.new(version: "2024-01").run
end
end
test "run suppresses non-error output when quiet is true" do
assert_output("") do
Benchmark.stubs(:realtime).returns(0.1).yields
GenerateDocsCommand.new(quiet: true).run
end
end
test "execute generates data files for unstable version" do
command = GenerateDocsCommand.new({})
command.execute
data_path = File.expand_path("docs/_data/unstable", @tmp_base_path)
assert File.exist?("#{data_path}/sibling_groups.yml")
assert File.exist?("#{data_path}/search_index.json")
assert File.exist?("#{data_path}/attributes.yml")
assert File.exist?("#{data_path}/mappings.yml")
assert File.exist?("#{data_path}/reversed_attributes.yml")
assert File.exist?("#{data_path}/attribute_search_index.json")
assert_equal "---\nsiblings: foo\n", File.read("#{data_path}/sibling_groups.yml")
assert_equal "---\nattributes: baz\n", File.read("#{data_path}/attributes.yml")
assert_equal "---\nreversed: qux\n", File.read("#{data_path}/reversed_attributes.yml")
assert_equal '[{"search":"bar"}]' + "\n", File.read("#{data_path}/search_index.json")
assert_equal '[{"attribute_search":"quux"}]' + "\n", File.read("#{data_path}/attribute_search_index.json")
release_path = File.expand_path("docs/_releases/unstable", @tmp_base_path)
refute File.exist?(release_path)
end
test "execute generates data files and release folder for versioned release" do
command = GenerateDocsCommand.new(version: "2024-01")
command.execute
data_path = File.expand_path("docs/_data/2024-01", @tmp_base_path)
assert File.exist?("#{data_path}/sibling_groups.yml")
assert File.exist?("#{data_path}/search_index.json")
assert File.exist?("#{data_path}/attributes.yml")
assert File.exist?("#{data_path}/mappings.yml")
assert File.exist?("#{data_path}/reversed_attributes.yml")
assert File.exist?("#{data_path}/attribute_search_index.json")
assert_equal "---\nsiblings: foo\n", File.read("#{data_path}/sibling_groups.yml")
assert_equal "---\nattributes: baz\n", File.read("#{data_path}/attributes.yml")
assert_equal "---\nreversed: qux\n", File.read("#{data_path}/reversed_attributes.yml")
assert_equal '[{"search":"bar"}]' + "\n", File.read("#{data_path}/search_index.json")
assert_equal '[{"attribute_search":"quux"}]' + "\n", File.read("#{data_path}/attribute_search_index.json")
release_path = File.expand_path("docs/_releases/2024-01", @tmp_base_path)
assert File.exist?("#{release_path}/index.html")
assert File.exist?("#{release_path}/attributes.html")
expected_index_content = <<~CONTENT
---
layout: categories
title: 2024-01
target: 2024-01
permalink: /releases/2024-01/
github_url: https://github.com/Shopify/product-taxonomy/releases/tag/v2024-01
include_in_release_list: true
---
CONTENT
assert_equal expected_index_content, File.read("#{release_path}/index.html")
expected_attributes_content = <<~CONTENT
---
layout: attributes
title: 2024-01
target: 2024-01
permalink: /releases/2024-01/attributes/
github_url: https://github.com/Shopify/product-taxonomy
---
CONTENT
assert_equal expected_attributes_content, File.read("#{release_path}/attributes.html")
end
test "execute updates latest.html redirect for versioned release" do
latest_html_path = File.expand_path("docs/_releases/latest.html", @tmp_base_path)
command = GenerateDocsCommand.new(version: "2024-01")
command.execute
expected_content = <<~HTML
---
title: latest
include_in_release_list: true
redirect_to: /releases/2024-01/
---
HTML
assert_equal expected_content, File.read(latest_html_path)
end
test "execute does not update latest.html redirect for unstable version" do
latest_html_path = File.expand_path("docs/_releases/latest.html", @tmp_base_path)
initial_content = File.read(latest_html_path)
command = GenerateDocsCommand.new({})
command.execute
# Content should remain unchanged
assert_equal initial_content, File.read(latest_html_path)
end
test "reverse_shopify_mapping_rules correctly reverses mappings" do
command = GenerateDocsCommand.new({})
mappings = [{
"input_taxonomy" => ["external"],
"output_taxonomy" => ["shopify"],
"rules" => [{
"input" => { "category" => "test" },
"output" => { "category" => ["mapped1", "mapped2"] },
}],
}]
expected = [{
"input_taxonomy" => ["shopify"],
"output_taxonomy" => ["external"],
"rules" => [
{
"input" => { "category" => "mapped1" },
"output" => { "category" => ["test"] },
},
{
"input" => { "category" => "mapped2" },
"output" => { "category" => ["test"] },
},
],
}]
assert_equal expected, command.send(:reverse_shopify_mapping_rules, mappings)
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/commands/sync_en_localizations_command_test.rb | dev/test/commands/sync_en_localizations_command_test.rb | # frozen_string_literal: true
require "test_helper"
require "tmpdir"
module ProductTaxonomy
class SyncEnLocalizationsCommandTest < TestCase
setup do
@tmp_base_path = Dir.mktmpdir
@real_base_path = File.expand_path("..", ProductTaxonomy.data_path)
FileUtils.mkdir_p(File.expand_path("data/localizations/categories", @tmp_base_path))
FileUtils.mkdir_p(File.expand_path("data/localizations/attributes", @tmp_base_path))
FileUtils.mkdir_p(File.expand_path("data/localizations/values", @tmp_base_path))
ProductTaxonomy.stubs(:data_path).returns(File.expand_path("data", @tmp_base_path))
Command.any_instance.stubs(:load_taxonomy)
end
teardown do
FileUtils.remove_entry(@tmp_base_path)
end
test "initialize sets targets to all permitted targets when not specified" do
command = SyncEnLocalizationsCommand.new({})
assert_equal ["categories", "attributes", "values"], command.instance_variable_get(:@targets)
end
test "initialize accepts custom targets" do
command = SyncEnLocalizationsCommand.new(targets: "categories,attributes")
assert_equal ["categories", "attributes"], command.instance_variable_get(:@targets)
end
test "initialize raises error for invalid target" do
assert_raises(RuntimeError) do
SyncEnLocalizationsCommand.new(targets: "invalid,categories")
end
end
test "execute syncs categories localizations" do
mock_localizations = {
"en" => {
"categories" => {
"test-1" => { "name" => "Test Category", "context" => "Test > Category" },
},
},
}
Serializers::Category::Data::LocalizationsSerializer.stubs(:serialize_all)
.returns(mock_localizations)
command = SyncEnLocalizationsCommand.new(targets: "categories")
command.execute
expected_path = File.expand_path("data/localizations/categories/en.yml", @tmp_base_path)
assert File.exist?(expected_path)
expected_content = <<~YAML
# This file is auto-generated. Do not edit directly.
---
en:
categories:
test-1:
# Test > Category
name: Test Category
YAML
assert_equal expected_content, File.read(expected_path)
end
test "execute syncs attributes localizations" do
mock_localizations = {
"en" => {
"attributes" => {
"test-attr" => { "name" => "Test Attribute", "description" => "A test attribute" },
},
},
}
Serializers::Attribute::Data::LocalizationsSerializer.stubs(:serialize_all)
.returns(mock_localizations)
command = SyncEnLocalizationsCommand.new(targets: "attributes")
command.execute
expected_path = File.expand_path("data/localizations/attributes/en.yml", @tmp_base_path)
assert File.exist?(expected_path)
expected_content = <<~YAML
# This file is auto-generated. Do not edit directly.
---
en:
attributes:
test-attr:
name: Test Attribute
description: A test attribute
YAML
assert_equal expected_content, File.read(expected_path)
end
test "execute syncs values localizations" do
mock_localizations = {
"en" => {
"values" => {
"test-value" => { "name" => "Test Value", "context" => "Test Attribute" },
},
},
}
Serializers::Value::Data::LocalizationsSerializer.stubs(:serialize_all)
.returns(mock_localizations)
command = SyncEnLocalizationsCommand.new(targets: "values")
command.execute
expected_path = File.expand_path("data/localizations/values/en.yml", @tmp_base_path)
assert File.exist?(expected_path)
expected_content = <<~YAML
# This file is auto-generated. Do not edit directly.
---
en:
values:
test-value:
# Test Attribute
name: Test Value
YAML
assert_equal expected_content, File.read(expected_path)
end
test "execute syncs all targets when none specified" do
Serializers::Category::Data::LocalizationsSerializer.stubs(:serialize_all)
.returns({ "en" => { "categories" => { "cat-1" => { "name" => "Category", "context" => "Category" } } } })
Serializers::Attribute::Data::LocalizationsSerializer.stubs(:serialize_all)
.returns({ "en" => { "attributes" => { "attr-1" => { "name" => "Attribute", "description" => "Desc" } } } })
Serializers::Value::Data::LocalizationsSerializer.stubs(:serialize_all)
.returns({ "en" => { "values" => { "val-1" => { "name" => "Value", "context" => "Attribute" } } } })
command = SyncEnLocalizationsCommand.new({})
command.execute
categories_path = File.expand_path("data/localizations/categories/en.yml", @tmp_base_path)
attributes_path = File.expand_path("data/localizations/attributes/en.yml", @tmp_base_path)
values_path = File.expand_path("data/localizations/values/en.yml", @tmp_base_path)
assert File.exist?(categories_path)
assert File.exist?(attributes_path)
assert File.exist?(values_path)
expected_categories = <<~YAML
# This file is auto-generated. Do not edit directly.
---
en:
categories:
cat-1:
# Category
name: Category
YAML
expected_attributes = <<~YAML
# This file is auto-generated. Do not edit directly.
---
en:
attributes:
attr-1:
name: Attribute
description: Desc
YAML
expected_values = <<~YAML
# This file is auto-generated. Do not edit directly.
---
en:
values:
val-1:
# Attribute
name: Value
YAML
assert_equal expected_categories, File.read(categories_path)
assert_equal expected_attributes, File.read(attributes_path)
assert_equal expected_values, File.read(values_path)
end
test "serializers produce the expected structure for context extraction" do
# This test validates the structure assumptions in extract_contexts.
# If serializers change their output format, this test will fail.
# Temporarily use real data path to load taxonomy
ProductTaxonomy.unstub(:data_path)
# Load real taxonomy data
values_path = File.expand_path("values.yml", ProductTaxonomy.data_path)
attributes_path = File.expand_path("attributes.yml", ProductTaxonomy.data_path)
categories_glob = Dir.glob(File.expand_path("categories/*.yml", ProductTaxonomy.data_path))
ProductTaxonomy::Loader.load(values_path:, attributes_path:, categories_glob:)
begin
categories = Serializers::Category::Data::LocalizationsSerializer.serialize_all
attributes = Serializers::Attribute::Data::LocalizationsSerializer.serialize_all
values = Serializers::Value::Data::LocalizationsSerializer.serialize_all
[categories, attributes, values].each do |localizations|
# Should be a hash with one locale key
assert localizations.is_a?(Hash), "Expected localization to be a Hash"
assert_equal 1, localizations.keys.size, "Expected exactly one locale key"
locale, sections = localizations.first
assert_equal "en", locale, "Expected locale to be 'en'"
# Sections should be a hash with exactly ONE section
# This is important because extract_contexts assumes no ID collisions across sections
assert sections.is_a?(Hash), "Expected sections to be a Hash"
assert_equal 1, sections.keys.size,
"Expected exactly one section (to avoid entry ID collisions). Got: #{sections.keys.join(', ')}"
# Verify no duplicate entry IDs across all sections (even though we expect only one section)
# Redundant with single-section check above, but makes the extract_contexts assumption explicit.
all_entry_ids = []
sections.each do |_section_name, entries|
all_entry_ids.concat(entries.keys)
end
duplicate_ids = all_entry_ids.group_by { |id| id }.select { |_id, occurrences| occurrences.size > 1 }.keys
assert_empty duplicate_ids,
"Found duplicate entry IDs across sections: #{duplicate_ids.join(', ')}"
sections.each do |section_name, entries|
# Each section should contain a hash of entries
assert entries.is_a?(Hash), "Expected section '#{section_name}' to contain a Hash of entries"
entries.each do |entry_id, data|
# Each entry should be a hash with at least a 'name' field
assert data.is_a?(Hash), "Expected entry '#{entry_id}' to be a Hash"
assert data.key?("name"), "Expected entry '#{entry_id}' to have a 'name' field"
# If 'context' exists, it should be a string
if data.key?("context")
assert data["context"].is_a?(String), "Expected 'context' in entry '#{entry_id}' to be a String"
end
end
end
end
ensure
# Clean up taxonomy data so it doesn't interfere with other tests
Category.reset
Attribute.reset
Value.reset
# Re-stub data_path for other tests
ProductTaxonomy.stubs(:data_path).returns(File.expand_path("data", @tmp_base_path))
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/commands/dump_integration_full_names_command_test.rb | dev/test/commands/dump_integration_full_names_command_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class DumpIntegrationFullNamesCommandTest < TestCase
setup do
@tmp_base_path = Dir.mktmpdir
@integrations_path = File.expand_path("data/integrations", @tmp_base_path)
FileUtils.mkdir_p(@integrations_path)
File.write(File.expand_path("VERSION", @tmp_base_path), "2023-12")
DumpIntegrationFullNamesCommand.any_instance.stubs(:integration_data_path).returns(@integrations_path)
Command.any_instance.stubs(:load_taxonomy)
Command.any_instance.stubs(:version_file_path).returns(File.expand_path("VERSION", @tmp_base_path))
integrations_data = [
{
"name" => "shopify",
"available_versions" => ["shopify/2023-12"]
}
]
File.write(File.expand_path("integrations.yml", @integrations_path), YAML.dump(integrations_data))
end
teardown do
FileUtils.remove_entry(@tmp_base_path)
end
test "initialize sets version from options when provided" do
command = DumpIntegrationFullNamesCommand.new(version: "2024-01")
assert_equal "2024-01", command.instance_variable_get(:@version)
end
test "initialize sets version from version file when not provided in options" do
command = DumpIntegrationFullNamesCommand.new({})
assert_equal "2023-12", command.instance_variable_get(:@version)
end
test "execute creates directory structure when it doesn't exist" do
Serializers::Category::Data::FullNamesSerializer.stubs(:serialize_all).returns(["test_data"])
target_dir = File.expand_path("shopify/2023-12", @integrations_path)
refute File.exist?(target_dir)
command = DumpIntegrationFullNamesCommand.new({})
command.execute
assert File.exist?(target_dir)
end
test "execute dumps data to YAML file with correct path" do
Serializers::Category::Data::FullNamesSerializer.stubs(:serialize_all).returns(["test_data"])
command = DumpIntegrationFullNamesCommand.new({})
command.execute
expected_path = File.expand_path("shopify/2023-12/full_names.yml", @integrations_path)
assert File.exist?(expected_path)
assert_equal "---\n- test_data\n", File.read(expected_path)
end
test "execute adds new version to integrations.yml when using a new version" do
target_dir = File.expand_path("shopify/2024-02", @integrations_path)
refute File.exist?(target_dir)
command = DumpIntegrationFullNamesCommand.new(version: "2024-02")
Serializers::Category::Data::FullNamesSerializer.stubs(:serialize_all).returns(["test_data"])
command.execute
assert File.exist?(target_dir)
integrations_file = File.expand_path("integrations.yml", @integrations_path)
updated_integrations = YAML.load_file(integrations_file)
assert_includes updated_integrations[0]["available_versions"], "shopify/2024-02"
end
test "execute doesn't modify integrations.yml when using existing version" do
command = DumpIntegrationFullNamesCommand.new({})
Serializers::Category::Data::FullNamesSerializer.stubs(:serialize_all).returns(["test_data"])
command.execute
integrations_file = File.expand_path("integrations.yml", @integrations_path)
updated_integrations = YAML.load_file(integrations_file)
assert_equal ["shopify/2023-12"], updated_integrations[0]["available_versions"]
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/commands/add_value_command_test.rb | dev/test/commands/add_value_command_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class AddValueCommandTest < TestCase
setup do
@attribute = Attribute.new(
id: 1,
name: "Color",
description: "Defines the primary color or pattern",
friendly_id: "color",
handle: "color",
values: []
)
@extended_attribute = ExtendedAttribute.new(
name: "Clothing Color",
description: "Color of the clothing",
friendly_id: "clothing_color",
handle: "clothing_color",
values_from: @attribute
)
@existing_value = Value.new(
id: 1,
name: "Black",
friendly_id: "color__black",
handle: "color__black"
)
@attribute.add_value(@existing_value)
Attribute.add(@attribute)
Attribute.add(@extended_attribute)
Value.add(@existing_value)
AddValueCommand.any_instance.stubs(:load_taxonomy)
DumpAttributesCommand.any_instance.stubs(:load_taxonomy)
DumpValuesCommand.any_instance.stubs(:load_taxonomy)
SyncEnLocalizationsCommand.any_instance.stubs(:load_taxonomy)
GenerateDocsCommand.any_instance.stubs(:load_taxonomy)
end
test "execute successfully adds a new value to an attribute" do
DumpAttributesCommand.any_instance.expects(:execute).once
DumpValuesCommand.any_instance.expects(:execute).once
SyncEnLocalizationsCommand.any_instance.expects(:execute).once
GenerateDocsCommand.any_instance.expects(:execute).once
AddValueCommand.new(name: "Blue", attribute_friendly_id: "color").execute
new_value = @attribute.values.find { |v| v.name == "Blue" }
assert_not_nil new_value
assert_equal 2, new_value.id # Since id 1 already exists
assert_equal "Blue", new_value.name
assert_equal "color__blue", new_value.friendly_id
assert_equal "color__blue", new_value.handle
assert_not_nil Value.find_by(friendly_id: "color__blue")
end
test "execute raises error when attribute not found" do
stub_commands
assert_raises(Indexed::NotFoundError) do
AddValueCommand.new(name: "Blue", attribute_friendly_id: "nonexistent").execute
end
end
test "execute raises error when trying to add value to extended attribute" do
stub_commands
assert_raises(RuntimeError) do
AddValueCommand.new(name: "Blue", attribute_friendly_id: "clothing_color").execute
end
end
test "execute raises error when value already exists" do
stub_commands
assert_raises(ActiveModel::ValidationError) do
AddValueCommand.new(name: "Black", attribute_friendly_id: "color").execute
end
end
test "execute warns when attribute has custom sorting" do
@attribute.stubs(:manually_sorted?).returns(true)
stub_commands
logger = mock
logger.expects(:info).once
logger.expects(:warn).once.with(regexp_matches(/custom sorting/))
command = AddValueCommand.new(name: "Blue", attribute_friendly_id: "color")
command.stubs(:logger).returns(logger)
command.execute
new_value = @attribute.values.find { |v| v.name == "Blue" }
assert_not_nil new_value
end
test "execute generates correct friendly_id and handle" do
stub_commands
IdentifierFormatter.expects(:format_friendly_id).with("color__Multi Word").returns("color__multi_word")
IdentifierFormatter.expects(:format_handle).with("color__multi_word").returns("color__multi_word")
AddValueCommand.new(name: "Multi Word", attribute_friendly_id: "color").execute
new_value = @attribute.values.find { |v| v.name == "Multi Word" }
assert_not_nil new_value
assert_equal "color__multi_word", new_value.friendly_id
assert_equal "color__multi_word", new_value.handle
end
test "execute calls update_data_files! with correct options" do
options = { name: "Blue", attribute_friendly_id: "color" }
DumpAttributesCommand.expects(:new).with(options).returns(stub(execute: true))
DumpValuesCommand.expects(:new).with(options).returns(stub(execute: true))
SyncEnLocalizationsCommand.expects(:new).with(targets: "values").returns(stub(execute: true))
GenerateDocsCommand.expects(:new).with({}).returns(stub(execute: true))
AddValueCommand.new(options).execute
end
test "execute assigns sequential IDs correctly" do
stub_commands
AddValueCommand.new(name: "Blue", attribute_friendly_id: "color").execute
AddValueCommand.new(name: "Green", attribute_friendly_id: "color").execute
new_values = @attribute.values.select { |v| v.name != "Black" }.sort_by(&:id)
assert_equal 2, new_values.size
assert_equal 2, new_values[0].id
assert_equal 3, new_values[1].id
assert_equal "Blue", new_values[0].name
assert_equal "Green", new_values[1].name
assert_not_nil Value.find_by(friendly_id: "color__blue")
assert_not_nil Value.find_by(friendly_id: "color__green")
end
private
def stub_commands
DumpAttributesCommand.any_instance.stubs(:execute)
DumpValuesCommand.any_instance.stubs(:execute)
SyncEnLocalizationsCommand.any_instance.stubs(:execute)
GenerateDocsCommand.any_instance.stubs(:execute)
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/attribute_test.rb | dev/test/models/attribute_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class AttributeTest < TestCase
setup do
@value = Value.new(
id: 1,
name: "Black",
friendly_id: "color__black",
handle: "color__black",
)
@attribute = Attribute.new(
id: 1,
name: "Color",
description: "Defines the primary color or pattern, such as blue or striped",
friendly_id: "color",
handle: "color",
values: [@value],
)
@extended_attribute = ExtendedAttribute.new(
name: "Clothing Color",
description: "Color of the clothing",
friendly_id: "clothing_color",
handle: "clothing_color",
values_from: @attribute,
)
end
test "load_from_source loads attributes from deserialized YAML" do
attributes_yaml_content = <<~YAML
---
base_attributes:
- id: 1
name: Color
description: Defines the primary color or pattern, such as blue or striped
friendly_id: color
handle: color
values:
- color__black
- id: 3
name: Pattern
description: Describes the design or motif of a product, such as floral or striped
friendly_id: pattern
handle: pattern
values:
- pattern__abstract
extended_attributes:
- id: 4
name: Clothing Pattern
description: Describes the design or motif of a product, such as floral or striped
friendly_id: clothing_pattern
handle: clothing_pattern
values_from: pattern
YAML
values_yaml_content = <<~YAML
- id: 1
name: Black
friendly_id: color__black
handle: color__black
- id: 2
name: Abstract
friendly_id: pattern__abstract
handle: pattern__abstract
YAML
Value.load_from_source(YAML.safe_load(values_yaml_content))
Attribute.load_from_source(YAML.safe_load(attributes_yaml_content))
assert_equal 3, Attribute.size
color = Attribute.find_by(friendly_id: "color")
assert_instance_of Attribute, color
assert_equal "color", color.handle
refute color.manually_sorted?
assert_instance_of Array, color.values
assert_instance_of Value, color.values.first
assert_equal ["color__black"], color.values.map(&:friendly_id)
pattern = Attribute.find_by(friendly_id: "pattern")
assert_instance_of Attribute, pattern
assert_equal "pattern", pattern.handle
refute pattern.manually_sorted?
assert_instance_of Array, pattern.values
assert_instance_of Value, pattern.values.first
assert_equal ["pattern__abstract"], pattern.values.map(&:friendly_id)
clothing_pattern = Attribute.find_by(friendly_id: "clothing_pattern")
assert_instance_of ExtendedAttribute, clothing_pattern
assert_equal "clothing_pattern", clothing_pattern.handle
refute clothing_pattern.manually_sorted?
assert_instance_of Array, clothing_pattern.values
assert_instance_of Value, clothing_pattern.values.first
assert_equal ["pattern__abstract"], clothing_pattern.values.map(&:friendly_id)
end
test "load_from_source raises an error if the source YAML does not follow the expected schema" do
yaml_content = <<~YAML
---
foo=bar
YAML
assert_raises(ArgumentError) { Attribute.load_from_source(YAML.safe_load(yaml_content)) }
end
test "load_from_source raises an error if the source data contains incomplete attributes" do
yaml_content = <<~YAML
---
base_attributes:
- id: 1
name: Color
extended_attributes: []
YAML
error = assert_raises(ActiveModel::ValidationError) do
Attribute.load_from_source(YAML.safe_load(yaml_content))
end
expected_errors = {
friendly_id: [{ error: :blank }],
handle: [{ error: :blank }],
description: [{ error: :blank }],
values: [{ error: :blank }],
}
assert_equal expected_errors, error.model.errors.details
end
test "load_from_source raises an error if the source data contains attributes with empty values" do
yaml_content = <<~YAML
---
base_attributes:
- id: 1
name: Color
description: Defines the primary color or pattern, such as blue or striped
friendly_id: color
handle: color
values: []
extended_attributes: []
YAML
error = assert_raises(ActiveModel::ValidationError) do
Attribute.load_from_source(YAML.safe_load(yaml_content))
end
expected_errors = {
values: [{ error: :blank }],
}
assert_equal expected_errors, error.model.errors.details
end
test "load_from_source raises an error if the source data contains attributes with values that are not found" do
yaml_content = <<~YAML
---
base_attributes:
- id: 1
name: Color
description: Defines the primary color or pattern, such as blue or striped
friendly_id: color
handle: color
values:
- foo
extended_attributes: []
YAML
error = assert_raises(ActiveModel::ValidationError) do
Attribute.load_from_source(YAML.safe_load(yaml_content))
end
expected_errors = {
values: [{ error: :not_found }],
}
assert_equal expected_errors, error.model.errors.details
end
test "load_from_source raises an error if the source data contains incomplete extended attributes" do
yaml_content = <<~YAML
---
base_attributes: []
extended_attributes:
- id: 2
name: Clothing Color
description: Defines the primary color or pattern, such as blue or striped
YAML
error = assert_raises(ActiveModel::ValidationError) do
Attribute.load_from_source(YAML.safe_load(yaml_content))
end
expected_errors = {
friendly_id: [{ error: :blank }],
handle: [{ error: :blank }],
base_attribute: [{ error: :not_found }],
}
assert_equal expected_errors, error.model.errors.details
end
test "load_from_source raises an error if the source data contains extended attributes with values_from that is not found" do
yaml_content = <<~YAML
---
base_attributes: []
extended_attributes:
- id: 2
name: Clothing Color
description: Defines the primary color or pattern, such as blue or striped
handle: clothing_color
friendly_id: clothing_color
values_from: foo
YAML
error = assert_raises(ActiveModel::ValidationError) do
Attribute.load_from_source(YAML.safe_load(yaml_content))
end
expected_errors = {
base_attribute: [{ error: :not_found }],
}
assert_equal expected_errors, error.model.errors.details
end
test "load_from_source raises an error if the source data contains duplicate friendly IDs" do
attributes_yaml_content = <<~YAML
---
base_attributes:
- id: 1
name: Color
description: Defines the primary color or pattern, such as blue or striped
friendly_id: color
handle: color
values:
- color__black
- id: 2
name: Pattern
description: Describes the design or motif of a product, such as floral or striped
friendly_id: color
handle: pattern
values:
- pattern__abstract
extended_attributes: []
YAML
values_yaml_content = <<~YAML
- id: 1
name: Black
friendly_id: color__black
handle: color__black
- id: 2
name: Abstract
friendly_id: pattern__abstract
handle: pattern__abstract
YAML
Value.load_from_source(YAML.safe_load(values_yaml_content))
error = assert_raises(ActiveModel::ValidationError) do
Attribute.load_from_source(YAML.safe_load(attributes_yaml_content))
end
expected_errors = {
friendly_id: [{ error: :taken }],
}
assert_equal expected_errors, error.model.errors.details
end
test "load_from_source raises an error if the source data contains an invalid ID" do
attributes_yaml_content = <<~YAML
---
base_attributes:
- id: foo
name: Color
description: Defines the primary color or pattern, such as blue or striped
friendly_id: color
handle: color
values:
- color__black
extended_attributes: []
YAML
values_yaml_content = <<~YAML
- id: 1
name: Black
friendly_id: color__black
handle: color__black
YAML
Value.load_from_source(YAML.safe_load(values_yaml_content))
error = assert_raises(ActiveModel::ValidationError) do
Attribute.load_from_source(YAML.safe_load(attributes_yaml_content))
end
expected_errors = {
id: [{ error: :not_a_number, value: "foo" }],
}
assert_equal expected_errors, error.model.errors.details
end
test "load_from_source correctly loads attribute with manually sorted values" do
attributes_yaml_content = <<~YAML
---
base_attributes:
- id: 1
name: Color
description: Defines the primary color or pattern, such as blue or striped
friendly_id: color
handle: color
sorting: custom
values:
- color__black
extended_attributes: []
YAML
values_yaml_content = <<~YAML
- id: 1
name: Black
friendly_id: color__black
handle: color__black
YAML
Value.load_from_source(YAML.safe_load(values_yaml_content))
Attribute.load_from_source(YAML.safe_load(attributes_yaml_content))
assert Attribute.find_by(friendly_id: "color").manually_sorted?
end
test "localized attributes are returned correctly" do
stub_localizations
attribute = Attribute.new(
id: 1,
name: "Raw name",
description: "Raw description",
friendly_id: "color",
handle: "color",
values: [],
)
assert_equal "Raw name", attribute.name
assert_equal "Raw description", attribute.description
assert_equal "Raw name", attribute.name(locale: "en")
assert_equal "Raw description", attribute.description(locale: "en")
assert_equal "Nom en français", attribute.name(locale: "fr")
assert_equal "Description en français", attribute.description(locale: "fr")
assert_equal "Nombre en español", attribute.name(locale: "es")
assert_equal "Descripción en español", attribute.description(locale: "es")
assert_equal "Raw name", attribute.name(locale: "cs") # fall back to en
assert_equal "Raw description", attribute.description(locale: "cs") # fall back to en
end
test "extended attributes are added to the base attribute specified in values_from" do
assert_equal 1, @attribute.extended_attributes.size
assert_equal @extended_attribute, @attribute.extended_attributes.first
end
test "gid returns the global ID" do
assert_equal "gid://shopify/TaxonomyAttribute/1", @attribute.gid
end
test "extended? returns true if the attribute is extended" do
assert @extended_attribute.extended?
end
test "extended? returns false if the attribute is not extended" do
refute @attribute.extended?
end
test "next_id returns 1 when there are no attributes" do
Attribute.reset
assert_equal 1, Attribute.next_id
end
test "next_id returns max id + 1 when there are attributes" do
Attribute.reset
attribute1 = Attribute.new(
id: 5,
name: "Size",
description: "Defines the size of the product",
friendly_id: "size",
handle: "size",
values: [@value],
)
attribute2 = Attribute.new(
id: 10,
name: "Material",
description: "Defines the material of the product",
friendly_id: "material",
handle: "material",
values: [@value],
)
Attribute.add(attribute1)
Attribute.add(attribute2)
assert_equal 11, Attribute.next_id
end
private
def stub_localizations
fr_yaml = <<~YAML
fr:
attributes:
color:
name: "Nom en français"
description: "Description en français"
clothing_color:
name: "Nom en français (extended)"
description: "Description en français (extended)"
YAML
es_yaml = <<~YAML
es:
attributes:
color:
name: "Nombre en español"
description: "Descripción en español"
clothing_color:
name: "Nombre en español (extended)"
description: "Descripción en español (extended)"
YAML
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "attributes", "*.yml"))
.returns(["fake/path/fr.yml", "fake/path/es.yml"])
YAML.stubs(:safe_load_file).with("fake/path/fr.yml").returns(YAML.safe_load(fr_yaml))
YAML.stubs(:safe_load_file).with("fake/path/es.yml").returns(YAML.safe_load(es_yaml))
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "values", "*.yml"))
.returns([])
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/category_test.rb | dev/test/models/category_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class CategoryTest < TestCase
setup do
@root = Category.new(id: "aa", name: "Root")
@child = Category.new(id: "aa-1", name: "Child")
@root.add_child(@child)
@grandchild = Category.new(id: "aa-1-1", name: "Grandchild")
@child.add_child(@grandchild)
end
test "add_child sets parent-child relationship" do
root = Category.new(id: "aa", name: "Root")
child = Category.new(id: "aa-1", name: "Child")
root.add_child(child)
assert_includes root.children, child
assert_equal root, child.parent
end
test "add_secondary_child sets secondary relationships" do
root = Category.new(id: "aa", name: "Root")
root2 = Category.new(id: "bb", name: "Root2")
child = Category.new(id: "aa-1", name: "Child")
root.add_secondary_child(child)
root2.add_secondary_child(child)
assert_includes root.secondary_children, child
assert_includes root2.secondary_children, child
assert_equal [root, root2], child.secondary_parents
end
test "add_attribute adds multiple attributes to category's attributes" do
category = Category.new(id: "aa", name: "Root")
color_attribute = Attribute.new(
id: 1,
name: "Color",
friendly_id: "color",
handle: "color",
description: "Defines the primary color",
values: []
)
size_attribute = Attribute.new(
id: 2,
name: "Size",
friendly_id: "size",
handle: "size",
description: "Defines the size",
values: []
)
category.add_attribute(color_attribute)
category.add_attribute(size_attribute)
assert_includes category.attributes, color_attribute
assert_includes category.attributes, size_attribute
assert_equal 2, category.attributes.size
end
test "root? is true for root node" do
assert @root.root?
end
test "root? is false for child node" do
refute @child.root?
end
test "leaf? is true for node without children" do
assert @grandchild.leaf?
end
test "leaf? is true for node with only secondary children" do
@grandchild.add_secondary_child(@child)
assert @grandchild.leaf?
end
test "leaf? is false for node with children" do
refute @root.leaf?
end
test "level is 0 for root node" do
assert_equal 0, @root.level
end
test "level is 1 for child node" do
assert_equal 1, @child.level
end
test "level is 2 for grandchild node" do
assert_equal 2, @grandchild.level
end
test "ancestors is empty for root node" do
assert_empty @root.ancestors
end
test "ancestors contains [root] for child node" do
assert_equal [@root], @child.ancestors
end
test "ancestors contains [parent, root] for grandchild node" do
assert_equal [@child, @root], @grandchild.ancestors
end
test "root returns self for root node" do
assert_equal @root, @root.root
end
test "root returns root node for child node" do
assert_equal @root, @child.root
end
test "root returns root node for grandchild node" do
assert_equal @root, @grandchild.root
end
test "full_name returns name for root node" do
assert_equal "Root", @root.full_name
end
test "full_name returns parent > child for child node" do
assert_equal "Root > Child", @child.full_name
end
test "full_name returns full path for grandchild node" do
assert_equal "Root > Child > Grandchild", @grandchild.full_name
end
test "descendant_of? is true for child of root" do
assert @child.descendant_of?(@root)
end
test "descendant_of? is true for grandchild of root" do
assert @grandchild.descendant_of?(@root)
end
test "descendant_of? is true for child of parent" do
assert @grandchild.descendant_of?(@child)
end
test "descendant_of? is false for parent of child" do
refute @child.descendant_of?(@grandchild)
end
test "descendant_of? is false for root of child" do
refute @root.descendant_of?(@child)
end
test "raises validation error if id is invalid" do
category = Category.new(id: "foo", name: "Test")
error = assert_raises(ActiveModel::ValidationError) { category.validate!(:create) }
expected_errors = {
id: [{ error: :invalid, value: "foo" }],
}
assert_equal expected_errors, error.model.errors.details
end
test "raises validation error if name is blank" do
category = Category.new(id: "aa", name: "")
error = assert_raises(ActiveModel::ValidationError) { category.validate!(:create) }
expected_errors = {
name: [{ error: :blank }],
}
assert_equal expected_errors, error.model.errors.details
end
test "raises validation error if id depth doesn't match hierarchy level" do
# A root category should have format "aa"
parent = Category.new(id: "aa", name: "Root")
category = Category.new(id: "aa-1-1", name: "Test", parent:)
error = assert_raises(ActiveModel::ValidationError) { category.validate!(:category_tree_loaded) }
expected_errors = {
id: [{ error: :depth_mismatch }],
}
assert_equal expected_errors, error.model.errors.details
end
test "raises validation error if child id doesn't start with parent id" do
root = Category.new(id: "aa", name: "Root")
child = Category.new(id: "bb-1", name: "Child")
root.add_child(child)
error = assert_raises(ActiveModel::ValidationError) { child.validate!(:category_tree_loaded) }
expected_errors = {
id: [{ error: :prefix_mismatch }],
}
assert_equal expected_errors, error.model.errors.details
end
test "raises validation error for duplicate id" do
root = Category.new(id: "aa", name: "Root")
Category.add(root)
child = Category.new(id: "aa", name: "Child")
Category.add(child)
error = assert_raises(ActiveModel::ValidationError) { child.validate!(:create) }
expected_errors = {
id: [{ error: :taken }],
}
assert_equal expected_errors, error.model.errors.details
end
test "validates correct id format examples" do
assert_nothing_raised do
Category.new(id: "aa", name: "Root").validate!(:create)
root = Category.new(id: "bb", name: "Root")
child = Category.new(id: "bb-1", name: "Child")
root.add_child(child)
child.validate!(:create)
grandchild = Category.new(id: "bb-1-1", name: "Grandchild")
child.add_child(grandchild)
grandchild.validate!(:create)
end
end
test "load_from_source loads categories from deserialized YAML" do
value = Value.new(id: 1, name: "Black", friendly_id: "black", handle: "black")
Value.add(value)
attribute = Attribute.new(
id: 1,
name: "Color",
friendly_id: "color",
handle: "color",
description: "Defines the primary color or pattern, such as blue or striped",
values: [value],
)
Attribute.add(attribute)
yaml_content = <<~YAML
---
- id: aa
name: Apparel & Accessories
children:
- aa-1
attributes:
- color
- id: aa-1
name: Clothing
children: []
attributes:
- color
YAML
Category.load_from_source(YAML.safe_load(yaml_content))
aa_root = Category.verticals.first
aa_clothing = aa_root.children.first
assert_equal 2, Category.size
assert_equal "aa", aa_root.id
assert_equal "Apparel & Accessories", aa_root.name
assert_equal [attribute], aa_root.attributes
assert_equal 1, aa_root.children.size
assert_equal "aa-1", aa_clothing.id
assert_equal [attribute], aa_clothing.attributes
end
test "load_from_source raises validation error if attribute is not found" do
yaml_content = <<~YAML
---
- id: aa
name: Apparel & Accessories
children: []
attributes:
- foo
YAML
error = assert_raises(ActiveModel::ValidationError) do
Category.load_from_source(YAML.safe_load(yaml_content))
end
expected_errors = {
attributes: [{ error: :not_found }],
}
assert_equal expected_errors, error.model.errors.details
end
test "load_from_source raises validation error if child is not found" do
yaml_content = <<~YAML
---
- id: aa
name: Apparel & Accessories
children:
- aa-1
attributes: []
YAML
error = assert_raises(ActiveModel::ValidationError) do
Category.load_from_source(YAML.safe_load(yaml_content))
end
expected_errors = {
children: [{ error: :not_found }],
}
assert_equal expected_errors, error.model.errors.details
end
test "load_from_source raises validation error if secondary child is not found" do
yaml_content = <<~YAML
---
- id: aa
name: Apparel & Accessories
secondary_children:
- aa-1
attributes: []
YAML
error = assert_raises(ActiveModel::ValidationError) do
Category.load_from_source(YAML.safe_load(yaml_content))
end
expected_errors = {
secondary_children: [{ error: :not_found }],
}
assert_equal expected_errors, error.model.errors.details
end
test "load_from_source raises validation error if category is orphaned" do
yaml_content = <<~YAML
---
- id: aa
name: Apparel & Accessories
attributes: []
children: [] # aa-1 is missing
- id: aa-1
name: Clothing
attributes: []
YAML
error = assert_raises(ActiveModel::ValidationError) do
Category.load_from_source(YAML.safe_load(yaml_content))
end
expected_errors = {
base: [{ error: :orphan }],
}
assert_equal expected_errors, error.model.errors.details
end
test "load_from_source loads categories with multiple paths from deserialized YAML" do
value = Value.new(id: 1, name: "Black", friendly_id: "black", handle: "black")
Value.add(value)
attribute = Attribute.new(
id: 1,
name: "Color",
friendly_id: "color",
handle: "color",
description: "Defines the primary color or pattern, such as blue or striped",
values: [value],
)
Attribute.add(attribute)
yaml_content = <<~YAML
---
- id: aa
name: Apparel & Accessories
children:
- aa-1
attributes:
- color
- id: aa-1
name: Clothing
children: []
secondary_children:
- bi-19-10
- id: bi
name: Business & Industrial
children:
- bi-19
attributes:
- color
- id: bi-19
name: Medical
children:
- bi-19-10
attributes:
- color
- id: bi-19-10
name: Scrubs
children: []
attributes:
- color
YAML
Category.load_from_source(YAML.safe_load(yaml_content))
aa_root = Category.verticals.first
aa_clothing = aa_root.children.first
bi_root = Category.verticals.second
bi_medical = bi_root.children.first
bi_scrubs = bi_medical.children.first
assert_equal "aa", aa_root.id
assert_equal "aa-1", aa_clothing.id
assert_equal "bi", bi_root.id
assert_equal "bi-19", bi_medical.id
assert_equal "bi-19-10", bi_scrubs.id
assert_equal bi_scrubs, aa_clothing.secondary_children.first
assert_equal bi_medical, bi_scrubs.parent
assert_equal aa_clothing, bi_scrubs.secondary_parents.first
end
test "localized attributes are returned correctly" do
stub_localizations
category = Category.new(id: "aa", name: "Raw name")
assert_equal "Raw name", category.name
assert_equal "Raw name", category.name(locale: "en")
assert_equal "Root en français", category.name(locale: "fr")
assert_equal "Root en español", category.name(locale: "es")
assert_equal "Raw name", category.name(locale: "cs") # fall back to en
end
test "full_name returns the localized full name of the category" do
stub_localizations
assert_equal "Root en français", @root.full_name(locale: "fr")
assert_equal "Root en français > Child en français", @child.full_name(locale: "fr")
assert_equal "Root en français > Child en français > Grandchild en français", @grandchild.full_name(locale: "fr")
end
test "gid returns the GID of the category" do
assert_equal "gid://shopify/TaxonomyCategory/aa", @root.gid
end
test "descendants returns the descendants of the category" do
assert_equal [@child, @grandchild], @root.descendants
end
test "descendants_and_self returns the descendants and self of the category" do
assert_equal [@root, @child, @grandchild], @root.descendants_and_self
end
test "id_parts returns the parts of the ID" do
assert_equal ["aa"], @root.id_parts
assert_equal ["aa", 1], @child.id_parts
assert_equal ["aa", 1, 1], @grandchild.id_parts
end
test "next_child_id returns id-1 for category with no children" do
category = Category.new(id: "aa", name: "Root")
assert_equal "aa-1", category.next_child_id
end
test "next_child_id returns next sequential id based on largest child id" do
root = Category.new(id: "aa", name: "Root")
child1 = Category.new(id: "aa-1", name: "Child 1")
child2 = Category.new(id: "aa-2", name: "Child 2")
child3 = Category.new(id: "aa-5", name: "Child 3") # Note gap in sequence
root.add_child(child1)
root.add_child(child2)
root.add_child(child3)
assert_equal "aa-6", root.next_child_id
end
test "next_child_id ignores secondary children when determining next id" do
root = Category.new(id: "aa", name: "Root")
child = Category.new(id: "aa-1", name: "Child")
secondary = Category.new(id: "bb-5", name: "Secondary")
root.add_child(child)
root.add_secondary_child(secondary)
assert_equal "aa-2", root.next_child_id
end
private
def stub_localizations
fr_yaml = <<~YAML
fr:
categories:
aa:
name: "Root en français"
aa-1:
name: "Child en français"
aa-1-1:
name: "Grandchild en français"
YAML
es_yaml = <<~YAML
es:
categories:
aa:
name: "Root en español"
aa-1:
name: "Child en español"
aa-1-1:
name: "Grandchild en español"
YAML
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "categories", "*.yml"))
.returns(["fake/path/fr.yml", "fake/path/es.yml"])
YAML.stubs(:safe_load_file).with("fake/path/fr.yml").returns(YAML.safe_load(fr_yaml))
YAML.stubs(:safe_load_file).with("fake/path/es.yml").returns(YAML.safe_load(es_yaml))
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "attributes", "*.yml"))
.returns([])
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "values", "*.yml"))
.returns([])
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/integration_version_test.rb | dev/test/models/integration_version_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class IntegrationVersionTest < TestCase
DATA_PATH = File.expand_path("../fixtures/data", __dir__)
setup do
aa = Category.new(id: "aa", name: "Apparel & Accessories")
aa_1 = Category.new(id: "aa-1", name: "Clothing")
aa_2 = Category.new(id: "aa-2", name: "Clothing Accessories")
aa_3 = Category.new(id: "aa-3", name: "Costumes & Accessories")
aa.add_child(aa_1)
aa.add_child(aa_2)
aa.add_child(aa_3)
Category.add(aa)
Category.add(aa_1)
Category.add(aa_2)
Category.add(aa_3)
@current_shopify_version = "2025-01-unstable"
@shopify_integration = IntegrationVersion.load_from_source(
integration_path: File.expand_path("integrations/shopify/2020-01", DATA_PATH),
current_shopify_version: @current_shopify_version,
)
@shopify_integration.resolve_to_shopify_mappings([]) # Resolve against current version
@external_integration = IntegrationVersion.load_from_source(
integration_path: File.expand_path("integrations/foocommerce/1.0.0", DATA_PATH),
current_shopify_version: @current_shopify_version,
)
end
test "IntegrationVersion.load_from_source loads the integration version with the correct version and name" do
assert_equal "2020-01", @shopify_integration.version
assert_equal "shopify", @shopify_integration.name
end
test "IntegrationVersion.load_all_from_source loads all integration versions" do
integrations_path = File.expand_path("integrations", DATA_PATH)
integration_versions = IntegrationVersion.load_all_from_source(
base_path: integrations_path,
current_shopify_version: @current_shopify_version,
)
assert_equal 5, integration_versions.size
assert_equal "foocommerce", integration_versions.first.name
assert_equal "1.0.0", integration_versions.first.version
assert_equal "shopify", integration_versions.second.name
assert_equal "2020-01", integration_versions.second.version
assert_equal "shopify", integration_versions.third.name
assert_equal "2021-01", integration_versions.third.version
assert_equal "shopify", integration_versions.fourth.name
assert_equal "2022-01", integration_versions.fourth.version
assert_equal "shopify", integration_versions.fifth.name
assert_equal "2023-01", integration_versions.fifth.version
end
test "IntegrationVersion.load_all_from_source resolves chain of to_shopify mappings against latest version" do
integrations_path = File.expand_path("integrations", DATA_PATH)
integration_versions = IntegrationVersion.load_all_from_source(
base_path: integrations_path,
current_shopify_version: @current_shopify_version,
)
output_mappings = integration_versions
.index_by { "#{_1.name}/#{_1.version}" }
.transform_values(&:to_shopify_mappings)
# 2022: mapped to aa-3, latest
assert_equal "gid://shopify/TaxonomyCategory/aa-3", output_mappings["shopify/2022-01"].first.output_category.gid
# 2021: mapped to aa-2, continues to resolve to aa-3
assert_equal "gid://shopify/TaxonomyCategory/aa-3", output_mappings["shopify/2021-01"].first.output_category.gid
# 2020: mapped to aa-1, continues to resolve to aa-3
assert_equal "gid://shopify/TaxonomyCategory/aa", output_mappings["shopify/2020-01"].first.output_category.gid
assert_equal "gid://shopify/TaxonomyCategory/aa-3", output_mappings["shopify/2020-01"].second.output_category.gid
end
test "to_json returns the JSON representation of a mapping to Shopify" do
expected_json = {
input_taxonomy: "shopify/2020-01",
output_taxonomy: "shopify/2025-01-unstable",
rules: [
{
input: { category: { id: "1", full_name: "Apparel & Accessories (2020-01)" } },
output: {
category: [{
id: "gid://shopify/TaxonomyCategory/aa",
full_name: "Apparel & Accessories",
}],
},
},
{
input: { category: { id: "2", full_name: "Apparel & Accessories > Clothing (2020-01)" } },
output: {
category: [{
id: "gid://shopify/TaxonomyCategory/aa-1",
full_name: "Apparel & Accessories > Clothing",
}],
},
},
],
}
assert_equal expected_json, @shopify_integration.to_json(direction: :to_shopify)
end
test "to_json returns the JSON representation of a mapping from Shopify" do
expected_json = {
input_taxonomy: "shopify/2025-01-unstable",
output_taxonomy: "foocommerce/1.0.0",
rules: [
{
input: { category: { id: "gid://shopify/TaxonomyCategory/aa", full_name: "Apparel & Accessories" } },
output: {
category: [{
id: "1",
full_name: "Apparel & Accessories (foocommerce)",
}],
},
},
{
input: {
category: {
id: "gid://shopify/TaxonomyCategory/aa-1",
full_name: "Apparel & Accessories > Clothing",
},
},
output: { category: [{ id: "2", full_name: "Apparel & Accessories > Clothing (foocommerce)" }] },
},
],
}
assert_equal expected_json, @external_integration.to_json(direction: :from_shopify)
end
test "to_txt returns the TXT representation of a mapping to Shopify" do
expected_txt = <<~TXT
# Shopify Product Taxonomy - Mapping shopify/2020-01 to shopify/2025-01-unstable
# Format:
# → {base taxonomy category name}
# ⇒ {mapped taxonomy category name}
→ Apparel & Accessories (2020-01)
⇒ Apparel & Accessories
→ Apparel & Accessories > Clothing (2020-01)
⇒ Apparel & Accessories > Clothing
TXT
assert_equal expected_txt.chomp, @shopify_integration.to_txt(direction: :to_shopify)
end
test "to_txt returns the TXT representation of a mapping from Shopify" do
expected_txt = <<~TXT
# Shopify Product Taxonomy - Mapping shopify/2025-01-unstable to foocommerce/1.0.0
# Format:
# → {base taxonomy category name}
# ⇒ {mapped taxonomy category name}
→ Apparel & Accessories
⇒ Apparel & Accessories (foocommerce)
→ Apparel & Accessories > Clothing
⇒ Apparel & Accessories > Clothing (foocommerce)
TXT
assert_equal expected_txt.chomp, @external_integration.to_txt(direction: :from_shopify)
end
test "generate_distribution generates the distribution files for a mapping to Shopify" do
FileUtils.expects(:mkdir_p).with("/tmp/fake/en/integrations/shopify")
expected_shopify_json = {
version: "2025-01-unstable",
mappings: [@shopify_integration.to_json(direction: :to_shopify)],
}
File.expects(:write).with(
"/tmp/fake/en/integrations/shopify/shopify_2020-01_to_shopify_2025-01.json",
JSON.pretty_generate(expected_shopify_json) + "\n",
)
File.expects(:write).with(
"/tmp/fake/en/integrations/shopify/shopify_2020-01_to_shopify_2025-01.txt",
@shopify_integration.to_txt(direction: :to_shopify) + "\n",
)
assert_nothing_raised do
@shopify_integration.generate_distribution(
output_path: "/tmp/fake",
direction: :to_shopify,
)
end
end
test "generate_distribution generates the distribution files for a mapping from Shopify" do
FileUtils.expects(:mkdir_p).with("/tmp/fake/en/integrations/foocommerce")
expected_external_json = {
version: "2025-01-unstable",
mappings: [@external_integration.to_json(direction: :from_shopify)],
}
File.expects(:write).with(
"/tmp/fake/en/integrations/foocommerce/shopify_2025-01_to_foocommerce_1.0.0.json",
JSON.pretty_generate(expected_external_json) + "\n",
)
File.expects(:write).with(
"/tmp/fake/en/integrations/foocommerce/shopify_2025-01_to_foocommerce_1.0.0.txt",
@external_integration.to_txt(direction: :from_shopify) + "\n",
)
assert_nothing_raised do
@external_integration.generate_distribution(
output_path: "/tmp/fake",
direction: :from_shopify,
)
end
end
test "generate_distributions only calls generate_distribution with to_shopify for Shopify integration version" do
@shopify_integration.expects(:generate_distribution).with(output_path: "/tmp/fake", direction: :to_shopify)
@shopify_integration.generate_distributions(output_path: "/tmp/fake")
end
test "generate_distributions only calls generate_distribution with from_shopify for external integration version" do
@external_integration.expects(:generate_distribution).with(output_path: "/tmp/fake", direction: :from_shopify)
@external_integration.generate_distributions(output_path: "/tmp/fake")
end
test "IntegrationVersion.to_json returns the JSON representation of a list of mappings" do
mappings = [
{
input_taxonomy: "shopify/2020-01",
output_taxonomy: "shopify/2025-01-unstable",
rules: [
{
input: { category: { id: "1", full_name: "Animals & Pet Supplies (old shopify)" } },
},
],
},
]
expected_json = {
version: "2025-01-unstable",
mappings:,
}
assert_equal expected_json, IntegrationVersion.to_json(mappings:, current_shopify_version: "2025-01-unstable")
end
test "unmapped_external_category_ids returns IDs of external categories not mapped from the Shopify taxonomy" do
external_category1 = category_hash("1")
from_shopify_mappings = [
MappingRule.new(
input_category: Category.new(id: "aa", name: "aa"),
output_category: external_category1,
),
]
full_names_by_id = {
"1" => external_category1,
"2" => { "id" => "2", "full_name" => "External category 2" },
"3" => { "id" => "3", "full_name" => "External category 3" },
}
integration_version = IntegrationVersion.new(
name: "test",
version: "1.0.0",
from_shopify_mappings:,
full_names_by_id:,
)
assert_equal ["2", "3"], integration_version.unmapped_external_category_ids
end
test "resolve_to_shopify_mappings resolves mappings to the latest version of the Shopify taxonomy" do
mapping = MappingRule.new(input_category: category_hash("aa-1"), output_category: "aa-2")
integration_version = IntegrationVersion.new(
name: "shopify",
version: "2020-01",
to_shopify_mappings: [mapping],
full_names_by_id: {},
)
integration_version.resolve_to_shopify_mappings([])
assert_equal "gid://shopify/TaxonomyCategory/aa-2", mapping.output_category.gid
end
test "resolve_to_shopify_mappings raises an error if a mapping cannot be resolved" do
mapping = MappingRule.new(input_category: category_hash("aa-1"), output_category: "invalid")
integration_version = IntegrationVersion.new(
name: "shopify",
version: "2020-01",
to_shopify_mappings: [mapping],
full_names_by_id: {},
)
assert_raises(ArgumentError) { integration_version.resolve_to_shopify_mappings([]) }
end
test "IntegrationVersion.resolve_to_shopify_mappings_chain resolves mappings to the current version of the Shopify taxonomy" do
version = IntegrationVersion.new(
name: "shopify",
version: "2020-01",
to_shopify_mappings: [MappingRule.new(input_category: category_hash("aa-1"), output_category: "aa-2")],
full_names_by_id: {},
)
IntegrationVersion.resolve_to_shopify_mappings_chain([version])
assert_equal "gid://shopify/TaxonomyCategory/aa-2", version.to_shopify_mappings[0].output_category.gid
end
test "IntegrationVersion.resolve_to_shopify_mappings_chain resolves mappings through two versions without chained mappings" do
versions = [
IntegrationVersion.new(
name: "shopify",
version: "2020-01",
to_shopify_mappings: [MappingRule.new(input_category: category_hash("aa-1"), output_category: "aa-2")],
full_names_by_id: {},
),
IntegrationVersion.new(
name: "shopify",
version: "2021-01",
to_shopify_mappings: [MappingRule.new(input_category: category_hash("bb-1"), output_category: "aa-1")],
full_names_by_id: {},
),
]
IntegrationVersion.resolve_to_shopify_mappings_chain(versions)
assert_equal "gid://shopify/TaxonomyCategory/aa-2", versions[0].to_shopify_mappings[0].output_category.gid
assert_equal "gid://shopify/TaxonomyCategory/aa-1", versions[1].to_shopify_mappings[0].output_category.gid
end
test "IntegrationVersion.resolve_to_shopify_mappings_chain resolves mappings through two versions with chained mappings" do
versions = [
IntegrationVersion.new(
name: "shopify",
version: "2020-01",
to_shopify_mappings: [MappingRule.new(input_category: category_hash("aa-1"), output_category: "aa-2")],
full_names_by_id: {},
),
IntegrationVersion.new(
name: "shopify",
version: "2021-01",
to_shopify_mappings: [MappingRule.new(input_category: category_hash("aa-2"), output_category: "aa-3")],
full_names_by_id: {},
),
]
IntegrationVersion.resolve_to_shopify_mappings_chain(versions)
assert_equal "gid://shopify/TaxonomyCategory/aa-3", versions[0].to_shopify_mappings[0].output_category.gid
assert_equal "gid://shopify/TaxonomyCategory/aa-3", versions[1].to_shopify_mappings[0].output_category.gid
end
test "IntegrationVersion.resolve_to_shopify_mappings_chain resolves mappings through four versions with non-consecutive chained mappings" do
versions = [
IntegrationVersion.new(
name: "shopify",
version: "2020-01",
to_shopify_mappings: [MappingRule.new(input_category: category_hash("aa-1"), output_category: "aa-2")],
full_names_by_id: {},
),
IntegrationVersion.new(
name: "shopify",
version: "2021-01",
to_shopify_mappings: [],
full_names_by_id: {},
),
IntegrationVersion.new(
name: "shopify",
version: "2022-01",
to_shopify_mappings: [MappingRule.new(input_category: category_hash("aa-2"), output_category: "aa-3")],
full_names_by_id: {},
),
IntegrationVersion.new(
name: "shopify",
version: "2023-01",
to_shopify_mappings: [],
full_names_by_id: {},
),
]
IntegrationVersion.resolve_to_shopify_mappings_chain(versions)
assert_equal "gid://shopify/TaxonomyCategory/aa-3", versions[0].to_shopify_mappings[0].output_category.gid
assert_equal "gid://shopify/TaxonomyCategory/aa-3", versions[2].to_shopify_mappings[0].output_category.gid
end
test "IntegrationVersion.resolve_to_shopify_mappings_chain resolves mappings through four versions with a mix of chained and non-chained mappings" do
versions = [
IntegrationVersion.new(
name: "shopify",
version: "2020-01",
to_shopify_mappings: [
MappingRule.new(input_category: category_hash("aa-1"), output_category: "aa-2"),
MappingRule.new(input_category: category_hash("bb-1"), output_category: "aa-1"),
],
full_names_by_id: {},
),
IntegrationVersion.new(
name: "shopify",
version: "2021-01",
to_shopify_mappings: [MappingRule.new(input_category: category_hash("cc-1"), output_category: "aa-1")],
full_names_by_id: {},
),
IntegrationVersion.new(
name: "shopify",
version: "2022-01",
to_shopify_mappings: [MappingRule.new(input_category: category_hash("aa-2"), output_category: "aa-3")],
full_names_by_id: {},
),
IntegrationVersion.new(
name: "shopify",
version: "2023-01",
to_shopify_mappings: [MappingRule.new(input_category: category_hash("dd-1"), output_category: "aa-2")],
full_names_by_id: {},
),
]
IntegrationVersion.resolve_to_shopify_mappings_chain(versions)
assert_equal "gid://shopify/TaxonomyCategory/aa-3", versions[0].to_shopify_mappings[0].output_category.gid
assert_equal "gid://shopify/TaxonomyCategory/aa-1", versions[0].to_shopify_mappings[1].output_category.gid
assert_equal "gid://shopify/TaxonomyCategory/aa-1", versions[1].to_shopify_mappings[0].output_category.gid
assert_equal "gid://shopify/TaxonomyCategory/aa-3", versions[2].to_shopify_mappings[0].output_category.gid
assert_equal "gid://shopify/TaxonomyCategory/aa-2", versions[3].to_shopify_mappings[0].output_category.gid
end
test "IntegrationVersion.clear_shopify_integrations_directory removes existing directory and recreates it" do
output_path = "/tmp/fake"
shopify_integrations_path = "/tmp/fake/en/integrations/shopify"
Dir.expects(:exist?).with(shopify_integrations_path).returns(true)
FileUtils.expects(:rm_rf).with(shopify_integrations_path)
FileUtils.expects(:mkdir_p).with(shopify_integrations_path)
IntegrationVersion.clear_shopify_integrations_directory(output_path: output_path, logger: mock)
end
test "IntegrationVersion.clear_shopify_integrations_directory does nothing if directory doesn't exist" do
output_path = "/tmp/fake"
shopify_integrations_path = "/tmp/fake/en/integrations/shopify"
Dir.expects(:exist?).with(shopify_integrations_path).returns(false)
FileUtils.expects(:rm_rf).never
FileUtils.expects(:mkdir_p).never
IntegrationVersion.clear_shopify_integrations_directory(output_path: output_path, logger: mock)
end
def category_hash(id)
{ "id" => id, "full_name" => "Category #{id}" }
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/value_test.rb | dev/test/models/value_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class ValueTest < TestCase
setup do
@value = Value.new(id: 1, name: "Black", friendly_id: "color__black", handle: "color__black")
@attribute = Attribute.new(
id: 1,
name: "Color",
friendly_id: "color",
handle: "color",
description: "Color",
values: [@value],
)
Attribute.add(@attribute)
end
test "load_from_source loads values from deserialized YAML" do
yaml_content = <<~YAML
- id: 1
name: Black
friendly_id: color__black
handle: color__black
- id: 2
name: Blue
friendly_id: color__blue
handle: color__blue
YAML
Value.load_from_source(YAML.safe_load(yaml_content))
assert_equal 2, Value.size
black = Value.find_by(friendly_id: "color__black")
assert_instance_of Value, black
assert_equal 1, black.id
assert_equal "Black", black.name
assert_equal "color__black", black.friendly_id
assert_equal "color__black", black.handle
blue = Value.find_by(friendly_id: "color__blue")
assert_instance_of Value, blue
assert_equal 2, blue.id
assert_equal "Blue", blue.name
assert_equal "color__blue", blue.friendly_id
assert_equal "color__blue", blue.handle
end
test "load_from_source raises an error if the source YAML does not follow the expected schema" do
yaml_content = <<~YAML
---
foo=bar
YAML
assert_raises(ArgumentError) { Value.load_from_source(YAML.safe_load(yaml_content)) }
end
test "load_from_source raises an error if the source data contains incomplete values" do
yaml_content = <<~YAML
- id: 1
name: Black
YAML
assert_raises(ActiveModel::ValidationError) { Value.load_from_source(YAML.safe_load(yaml_content)) }
end
test "load_from_source raises an error if the source data contains duplicate friendly IDs" do
yaml_content = <<~YAML
- id: 1
name: Black
friendly_id: color__black
handle: color__black
- id: 2
name: Blue
friendly_id: color__black
handle: color__blue
YAML
error = assert_raises(ActiveModel::ValidationError) do
Value.load_from_source(YAML.safe_load(yaml_content))
end
expected_errors = {
friendly_id: [{ error: :taken }],
}
assert_equal expected_errors, error.model.errors.details
end
test "load_from_source raises an error if the source data contains an invalid ID" do
yaml_content = <<~YAML
- id: foo
name: Black
friendly_id: color__black
handle: color__black
YAML
error = assert_raises(ActiveModel::ValidationError) do
Value.load_from_source(YAML.safe_load(yaml_content))
end
expected_errors = {
id: [{ error: :not_a_number, value: "foo" }],
}
assert_equal expected_errors, error.model.errors.details
end
test "load_from_source raises an error if the source data contains duplicate handles" do
yaml_content = <<~YAML
- id: 1
name: Black
friendly_id: color__black
handle: color__black
- id: 2
name: Blue
friendly_id: color__blue
handle: color__black
YAML
error = assert_raises(ActiveModel::ValidationError) do
Value.load_from_source(YAML.safe_load(yaml_content))
end
expected_errors = {
handle: [{ error: :taken }],
}
assert_equal expected_errors, error.model.errors.details
end
test "load_from_source raises an error if the source data contains duplicate IDs" do
yaml_content = <<~YAML
- id: 1
name: Black
friendly_id: color__black
handle: color__black
- id: 1
name: Blue
friendly_id: color__blue
handle: color__blue
YAML
error = assert_raises(ActiveModel::ValidationError) do
Value.load_from_source(YAML.safe_load(yaml_content))
end
expected_errors = {
id: [{ error: :taken }],
}
assert_equal expected_errors, error.model.errors.details
end
test "localized attributes are returned correctly" do
stub_localizations
value = Value.new(id: 1, name: "Raw name", friendly_id: "color__black", handle: "color__black")
assert_equal "Raw name", value.name
assert_equal "Raw name", value.name(locale: "en")
assert_equal "Nom en français", value.name(locale: "fr")
assert_equal "Nombre en español", value.name(locale: "es")
assert_equal "Raw name", value.name(locale: "cs") # fall back to en
end
test "primary_attribute returns the attribute for the value" do
Attribute.reset
value = Value.new(id: 1, name: "Black", friendly_id: "color__black", handle: "color__black")
assert_nil value.primary_attribute
attribute = Attribute.new(
id: 1,
name: "Color",
friendly_id: "color",
handle: "color",
description: "Color",
values: [value],
)
Attribute.add(attribute)
assert_equal attribute, value.primary_attribute
end
test "primary_attribute returns nil if the attribute is not found" do
Attribute.reset
assert_nil @value.primary_attribute
end
test "full_name returns the name of the value and its primary attribute" do
assert_equal "Black [Color]", @value.full_name
end
test "Value.sort_by_localized_name sorts values alphanumerically" do
values = stub_color_values
assert_equal ["Blue", "Green", "Red"], Value.sort_by_localized_name(values).map(&:name)
end
test "Value.sort_by_localized_name sorts non-English values alphanumerically" do
values = stub_color_values
sorted_values = Value.sort_by_localized_name(values, locale: "fr")
assert_equal ["Bleu", "Rouge", "Vert"], sorted_values.map { _1.name(locale: "fr") }
end
test "Value.sort_by_localized_name sorts values with 'Other' at the end" do
values = stub_pattern_values
assert_equal ["Animal", "Striped", "Other"], Value.sort_by_localized_name(values).map(&:name)
end
test "Value.sort_by_localized_name sorts non-English values with 'Other' at the end" do
values = stub_pattern_values
sorted_values = Value.sort_by_localized_name(values, locale: "fr")
assert_equal ["Animal", "Rayé", "Autre"], sorted_values.map { _1.name(locale: "fr") }
end
test "next_id returns 1 when there are no values" do
Value.reset
assert_equal 1, Value.next_id
end
test "next_id returns max id + 1 when there are existing values" do
Value.reset
Value.add(Value.new(id: 5, name: "Red", friendly_id: "color__red", handle: "color__red"))
Value.add(Value.new(id: 10, name: "Blue", friendly_id: "color__blue", handle: "color__blue"))
Value.add(Value.new(id: 3, name: "Green", friendly_id: "color__green", handle: "color__green"))
assert_equal 11, Value.next_id
end
test "next_id returns correct value after values have been reset" do
Value.reset
Value.add(Value.new(id: 5, name: "Red", friendly_id: "color__red", handle: "color__red"))
assert_equal 6, Value.next_id
Value.reset
assert_equal 1, Value.next_id
Value.add(Value.new(id: 3, name: "Blue", friendly_id: "color__blue", handle: "color__blue"))
assert_equal 4, Value.next_id
end
test "validates friendly_id prefix does not resolve to attribute on taxonomy_loaded" do
Attribute.reset
value = Value.new(id: 1, name: "Black", friendly_id: "color__black", handle: "color__black")
expected_errors = {
friendly_id: [{ error: :invalid_prefix }],
}
refute value.valid?(:taxonomy_loaded)
assert_equal expected_errors, value.errors.details
end
test "validates handle prefix does not match attribute on taxonomy_loaded" do
value = Value.new(id: 1, name: "Black", friendly_id: "color__black", handle: "size__black")
expected_errors = {
handle: [{ error: :invalid_prefix }],
}
refute value.valid?(:taxonomy_loaded)
assert_equal expected_errors, value.errors.details
end
test "validates handle and friendly_id prefix on taxonomy_loaded when primary_attribute is nil" do
Attribute.reset
value = Value.new(id: 1, name: "Black", friendly_id: "color__black", handle: "color__black")
expected_errors = {
friendly_id: [{ error: :invalid_prefix }],
}
refute value.valid?(:taxonomy_loaded)
assert_equal expected_errors, value.errors.details
end
private
def stub_localizations
fr_yaml = <<~YAML
fr:
values:
color__black:
name: "Nom en français"
YAML
es_yaml = <<~YAML
es:
values:
color__black:
name: "Nombre en español"
YAML
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "values", "*.yml"))
.returns(["fake/path/fr.yml", "fake/path/es.yml"])
YAML.stubs(:safe_load_file).with("fake/path/fr.yml").returns(YAML.safe_load(fr_yaml))
YAML.stubs(:safe_load_file).with("fake/path/es.yml").returns(YAML.safe_load(es_yaml))
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "attributes", "*.yml"))
.returns([])
end
def stub_color_values
fr_yaml = <<~YAML
fr:
values:
color__red:
name: "Rouge"
color__blue:
name: "Bleu"
color__green:
name: "Vert"
YAML
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "values", "*.yml"))
.returns(["fake/path/fr.yml"])
YAML.stubs(:safe_load_file).with("fake/path/fr.yml").returns(YAML.safe_load(fr_yaml))
[
Value.new(id: 1, name: "Red", handle: "color__red", friendly_id: "color__red"),
Value.new(id: 2, name: "Blue", handle: "color__blue", friendly_id: "color__blue"),
Value.new(id: 3, name: "Green", handle: "color__green", friendly_id: "color__green"),
]
end
def stub_pattern_values
fr_yaml = <<~YAML
fr:
values:
pattern__animal:
name: "Animal"
pattern__striped:
name: "Rayé"
pattern__other:
name: "Autre"
YAML
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "values", "*.yml"))
.returns(["fake/path/fr.yml"])
YAML.stubs(:safe_load_file).with("fake/path/fr.yml").returns(YAML.safe_load(fr_yaml))
[
Value.new(id: 1, name: "Animal", handle: "pattern__animal", friendly_id: "pattern__animal"),
Value.new(id: 2, name: "Striped", handle: "pattern__striped", friendly_id: "pattern__striped"),
Value.new(id: 3, name: "Other", handle: "pattern__other", friendly_id: "pattern__other"),
]
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/mapping_rule_test.rb | dev/test/models/mapping_rule_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class MappingRuleTest < TestCase
setup do
@shopify_category = Category.new(id: "aa", name: "Shopify category")
@integration_category = {
"id" => "166",
"full_name" => "Integration category",
}
Category.add(@shopify_category)
end
test "load_rules_from_source loads rules from source for from_shopify direction without errors" do
full_names_by_id = {
"166" => { "id" => "166", "full_name" => "Integration category" },
}
File.expects(:exist?).with("/fake/data/integrations/google/2021-09-21/mappings/from_shopify.yml").returns(true)
YAML.expects(:safe_load_file).with("/fake/data/integrations/google/2021-09-21/mappings/from_shopify.yml").returns(
"rules" => [
{ "input" => { "product_category_id" => "aa" }, "output" => { "product_category_id" => ["166"] } },
],
)
rules = MappingRule.load_rules_from_source(
integration_path: "/fake/data/integrations/google/2021-09-21",
direction: :from_shopify,
full_names_by_id:,
)
assert_equal 1, rules.size
end
test "load_rules_from_source loads rules from source for to_shopify direction without errors" do
full_names_by_id = {
"166" => { "id" => "166", "full_name" => "Integration category" },
}
File.expects(:exist?).with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml").returns(true)
YAML.expects(:safe_load_file).with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml").returns(
"rules" => [
{ "input" => { "product_category_id" => "166" }, "output" => { "product_category_id" => ["aa"] } },
],
)
rules = MappingRule.load_rules_from_source(
integration_path: "/fake/data/integrations/google/2021-09-21",
direction: :to_shopify,
full_names_by_id:,
)
assert_equal 1, rules.size
end
test "load_rules_from_source returns nil if the file does not exist" do
full_names_by_id = {
"166" => { "id" => "166", "full_name" => "Integration category" },
}
File.expects(:exist?).with("/fake/data/integrations/google/2021-09-21/mappings/from_shopify.yml").returns(false)
rules = MappingRule.load_rules_from_source(
integration_path: "/fake/data/integrations/google/2021-09-21",
direction: :from_shopify,
full_names_by_id:,
)
assert_nil rules
end
test "load_rules_from_source raises an error if the file does not contain a hash" do
File.expects(:exist?).with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml").returns(true)
YAML.expects(:safe_load_file)
.with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml")
.returns("foo")
assert_raises(ArgumentError) do
MappingRule.load_rules_from_source(
integration_path: "/fake/data/integrations/google/2021-09-21",
direction: :to_shopify,
full_names_by_id: {},
)
end
end
test "load_rules_from_source raises an error if the file does not contain a rules key" do
File.expects(:exist?).with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml").returns(true)
YAML.expects(:safe_load_file)
.with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml")
.returns({ foo: "bar" })
assert_raises(ArgumentError) do
MappingRule.load_rules_from_source(
integration_path: "/fake/data/integrations/google/2021-09-21",
direction: :to_shopify,
full_names_by_id: {},
)
end
end
test "load_rules_from_source raises an error if the input category is not found" do
File.expects(:exist?).with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml").returns(true)
YAML.expects(:safe_load_file)
.with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml")
.returns("rules" => [
{ "input" => { "product_category_id" => "166" }, "output" => { "product_category_id" => ["aa"] } },
])
assert_raises(ArgumentError) do
MappingRule.load_rules_from_source(
integration_path: "/fake/data/integrations/google/2021-09-21",
direction: :to_shopify,
full_names_by_id: {},
)
end
end
test "load_rules_from_source raises an error if the output category is missing" do
File.expects(:exist?).with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml").returns(true)
YAML.expects(:safe_load_file)
.with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml")
.returns("rules" => [
{ "input" => { "product_category_id" => "166" }, "output" => { "product_category_id" => [] } },
])
assert_raises(ArgumentError) do
MappingRule.load_rules_from_source(
integration_path: "/fake/data/integrations/google/2021-09-21",
direction: :to_shopify,
full_names_by_id: { "166" => { "id" => "166", "full_name" => "Integration category" } },
)
end
end
test "load_rules_from_source raises an error if the mapping definition is invalid" do
File.expects(:exist?).with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml").returns(true)
YAML.expects(:safe_load_file)
.with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml")
.returns("rules" => [
{ "foo" => "bar" },
])
assert_raises(ArgumentError) do
MappingRule.load_rules_from_source(
integration_path: "/fake/data/integrations/google/2021-09-21",
direction: :to_shopify,
full_names_by_id: {},
)
end
end
test "load_rules_from_source raises an error if the mapping input is not a hash" do
File.expects(:exist?).with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml").returns(true)
YAML.expects(:safe_load_file)
.with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml")
.returns("rules" => [
{ "input" => "foo", "output" => { "product_category_id" => ["aa"] } },
])
assert_raises(ArgumentError) do
MappingRule.load_rules_from_source(
integration_path: "/fake/data/integrations/google/2021-09-21",
direction: :to_shopify,
full_names_by_id: {},
)
end
end
test "load_rules_from_source raises an error if the mapping input hash key is invalid" do
File.expects(:exist?).with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml").returns(true)
YAML.expects(:safe_load_file)
.with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml")
.returns("rules" => [
{ "input" => { "id" => "foo" }, "output" => { "product_category_id" => ["aa"] } },
])
assert_raises(ArgumentError) do
MappingRule.load_rules_from_source(
integration_path: "/fake/data/integrations/google/2021-09-21",
direction: :to_shopify,
full_names_by_id: {},
)
end
end
test "load_rules_from_source raises an error if the mapping output ID value is not an array" do
File.expects(:exist?).with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml").returns(true)
YAML.expects(:safe_load_file)
.with("/fake/data/integrations/google/2021-09-21/mappings/to_shopify.yml")
.returns("rules" => [
{ "input" => { "product_category_id" => "166" }, "output" => { "product_category_id" => 1 } },
])
assert_raises(ArgumentError) do
MappingRule.load_rules_from_source(
integration_path: "/fake/data/integrations/google/2021-09-21",
direction: :to_shopify,
full_names_by_id: {},
)
end
end
test "to_json returns correct JSON with Shopify input and integration output" do
rule = MappingRule.new(
input_category: @shopify_category,
output_category: @integration_category,
)
expected_json = {
input: { category: { id: "gid://shopify/TaxonomyCategory/aa", full_name: "Shopify category" } },
output: { category: [{ id: "166", full_name: "Integration category" }] },
}
assert_equal expected_json, rule.to_json.deep_symbolize_keys
end
test "to_json returns correct JSON with integration input and Shopify output" do
rule = MappingRule.new(
input_category: @integration_category,
output_category: @shopify_category,
)
expected_json = {
input: { category: { id: "166", full_name: "Integration category" } },
output: { category: [{ id: "gid://shopify/TaxonomyCategory/aa", full_name: "Shopify category" }] },
}
assert_equal expected_json, rule.to_json.deep_symbolize_keys
end
test "to_txt returns correct TXT with Shopify input and integration output" do
rule = MappingRule.new(
input_category: @shopify_category,
output_category: @integration_category,
)
expected_txt = <<~TXT
→ Shopify category
⇒ Integration category
TXT
assert_equal expected_txt, rule.to_txt
end
test "to_txt returns correct TXT with integration input and Shopify output" do
rule = MappingRule.new(
input_category: @integration_category,
output_category: @shopify_category,
)
expected_txt = <<~TXT
→ Integration category
⇒ Shopify category
TXT
assert_equal expected_txt, rule.to_txt
end
test "input_txt_equals_output_txt? returns true if the input and output categories have the same full name" do
rule = MappingRule.new(
input_category: @shopify_category,
output_category: {
"id" => "166",
"full_name" => "Shopify category",
},
)
assert rule.input_txt_equals_output_txt?
end
test "input_txt_equals_output_txt? returns false if the input and output categories have different full names" do
rule = MappingRule.new(
input_category: @shopify_category,
output_category: @integration_category,
)
refute rule.input_txt_equals_output_txt?
end
test "to_txt raises an error if the output category is not resolved" do
rule = MappingRule.new(
input_category: @shopify_category,
output_category: "aa",
)
assert_raises(ArgumentError) do
rule.to_txt
end
end
test "to_json raises an error if the output category is not resolved" do
rule = MappingRule.new(
input_category: @shopify_category,
output_category: "aa",
)
assert_raises(ArgumentError) do
rule.to_json
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/extended_attribute_test.rb | dev/test/models/extended_attribute_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class ExtendedAttributeTest < TestCase
test "validates values_from is an attribute" do
extended_attribute = ExtendedAttribute.new(
name: "Clothing Color",
description: "Color of the clothing",
friendly_id: "clothing_color",
handle: "clothing_color",
values_from: "not an attribute",
)
error = assert_raises(ActiveModel::ValidationError) do
extended_attribute.validate!(:create)
end
expected_errors = {
base_attribute: [{ error: :not_found }],
}
assert_equal expected_errors, error.model.errors.details
end
test "localized attributes are returned correctly" do
attribute = Attribute.new(
id: 1,
name: "Color",
description: "Defines the primary color or pattern, such as blue or striped",
friendly_id: "color",
handle: "color",
values: [],
)
extended_attribute = ExtendedAttribute.new(
name: "Clothing Color",
description: "Color of the clothing",
friendly_id: "clothing_color",
handle: "clothing_color",
values_from: attribute,
)
fr_yaml = <<~YAML
fr:
attributes:
clothing_color:
name: "Nom en français"
description: "Description en français"
YAML
es_yaml = <<~YAML
es:
attributes:
clothing_color:
name: "Nombre en español"
description: "Descripción en español"
YAML
Dir.expects(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "attributes", "*.yml"))
.returns(["fake/path/fr.yml", "fake/path/es.yml"])
YAML.expects(:safe_load_file).with("fake/path/fr.yml").returns(YAML.safe_load(fr_yaml))
YAML.expects(:safe_load_file).with("fake/path/es.yml").returns(YAML.safe_load(es_yaml))
assert_equal "Clothing Color", extended_attribute.name
assert_equal "Color of the clothing", extended_attribute.description
assert_equal "Clothing Color", extended_attribute.name(locale: "en")
assert_equal "Color of the clothing", extended_attribute.description(locale: "en")
assert_equal "Nom en français", extended_attribute.name(locale: "fr")
assert_equal "Description en français", extended_attribute.description(locale: "fr")
assert_equal "Nombre en español", extended_attribute.name(locale: "es")
assert_equal "Descripción en español", extended_attribute.description(locale: "es")
assert_equal "Clothing Color", extended_attribute.name(locale: "cs") # fall back to en
assert_equal "Color of the clothing", extended_attribute.description(locale: "cs") # fall back to en
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/category/docs/siblings_serializer_test.rb | dev/test/models/serializers/category/docs/siblings_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Category
module Docs
class SiblingsSerializerTest < TestCase
setup do
@parent = ProductTaxonomy::Category.new(
id: 1,
name: "Parent Category",
)
@category = ProductTaxonomy::Category.new(
id: 2,
name: "Test Category",
parent: @parent,
)
@value = ProductTaxonomy::Value.new(
id: 1,
name: "Test Value",
friendly_id: "test_value",
handle: "test_value",
)
@attribute = ProductTaxonomy::Attribute.new(
id: 1,
name: "Test Attribute",
description: "Test Description",
friendly_id: "test_attribute",
handle: "test_handle",
values: [@value],
)
@category.attributes << @attribute
end
test "serialize returns the expected structure" do
expected = {
"id" => "gid://shopify/TaxonomyCategory/2",
"name" => "Test Category",
"fully_qualified_type" => "Parent Category > Test Category",
"depth" => 1,
"parent_id" => "gid://shopify/TaxonomyCategory/1",
"node_type" => "leaf",
"ancestor_ids" => "gid://shopify/TaxonomyCategory/1",
"attribute_handles" => "test_handle",
}
assert_equal expected, SiblingsSerializer.serialize(@category)
end
test "serialize root category returns the expected structure" do
root_category = ProductTaxonomy::Category.new(
id: 3,
name: "Root Category",
)
expected = {
"id" => "gid://shopify/TaxonomyCategory/3",
"name" => "Root Category",
"fully_qualified_type" => "Root Category",
"depth" => 0,
"parent_id" => "root",
"node_type" => "root",
"ancestor_ids" => "",
"attribute_handles" => "",
}
assert_equal expected, SiblingsSerializer.serialize(root_category)
end
test "serialize_all returns categories grouped by level and parent" do
ProductTaxonomy::Category.stubs(:all_depth_first).returns([@parent, @category])
expected = {
0 => {
"root" => [
{
"id" => "gid://shopify/TaxonomyCategory/1",
"name" => "Parent Category",
"fully_qualified_type" => "Parent Category",
"depth" => 0,
"parent_id" => "root",
"node_type" => "root",
"ancestor_ids" => "",
"attribute_handles" => "",
},
],
},
1 => {
"gid://shopify/TaxonomyCategory/1" => [
{
"id" => "gid://shopify/TaxonomyCategory/2",
"name" => "Test Category",
"fully_qualified_type" => "Parent Category > Test Category",
"depth" => 1,
"parent_id" => "gid://shopify/TaxonomyCategory/1",
"node_type" => "leaf",
"ancestor_ids" => "gid://shopify/TaxonomyCategory/1",
"attribute_handles" => "test_handle",
},
],
},
}
assert_equal expected, SiblingsSerializer.serialize_all
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/category/docs/search_serializer_test.rb | dev/test/models/serializers/category/docs/search_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Category
module Docs
class SearchSerializerTest < TestCase
setup do
@category = ProductTaxonomy::Category.new(
id: 1,
name: "Test Category",
)
end
test "serialize returns the expected search structure" do
expected = {
"searchIdentifier" => "gid://shopify/TaxonomyCategory/1",
"title" => "Test Category",
"url" => "?categoryId=gid%3A%2F%2Fshopify%2FTaxonomyCategory%2F1",
"category" => {
"id" => "gid://shopify/TaxonomyCategory/1",
"name" => "Test Category",
"fully_qualified_type" => "Test Category",
"depth" => 0,
},
}
assert_equal expected, SearchSerializer.serialize(@category)
end
test "serialize_all returns all categories in search format" do
ProductTaxonomy::Category.stubs(:all_depth_first).returns([@category])
expected = [
{
"searchIdentifier" => "gid://shopify/TaxonomyCategory/1",
"title" => "Test Category",
"url" => "?categoryId=gid%3A%2F%2Fshopify%2FTaxonomyCategory%2F1",
"category" => {
"id" => "gid://shopify/TaxonomyCategory/1",
"name" => "Test Category",
"fully_qualified_type" => "Test Category",
"depth" => 0,
},
},
]
assert_equal expected, SearchSerializer.serialize_all
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/category/dist/json_serializer_test.rb | dev/test/models/serializers/category/dist/json_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Category
module Dist
class JsonSerializerTest < TestCase
setup do
@root = ProductTaxonomy::Category.new(id: "aa", name: "Root")
@child = ProductTaxonomy::Category.new(id: "aa-1", name: "Child")
@root.add_child(@child)
@grandchild = ProductTaxonomy::Category.new(id: "aa-1-1", name: "Grandchild")
@child.add_child(@grandchild)
end
test "serialize returns the JSON representation of the category for root node" do
expected_json = {
"id" => "gid://shopify/TaxonomyCategory/aa",
"level" => 0,
"name" => "Root",
"full_name" => "Root",
"parent_id" => nil,
"attributes" => [],
"children" => [{
"id" => "gid://shopify/TaxonomyCategory/aa-1",
"name" => "Child",
}],
"ancestors" => [],
}
assert_equal expected_json, JsonSerializer.serialize(@root)
end
test "serialize returns the JSON representation of the category for child node" do
expected_json = {
"id" => "gid://shopify/TaxonomyCategory/aa-1",
"level" => 1,
"name" => "Child",
"full_name" => "Root > Child",
"parent_id" => "gid://shopify/TaxonomyCategory/aa",
"attributes" => [],
"children" => [{
"id" => "gid://shopify/TaxonomyCategory/aa-1-1",
"name" => "Grandchild",
}],
"ancestors" => [{
"id" => "gid://shopify/TaxonomyCategory/aa",
"name" => "Root",
}],
}
assert_equal expected_json, JsonSerializer.serialize(@child)
end
test "serialize returns the JSON representation of the category for grandchild node" do
expected_json = {
"id" => "gid://shopify/TaxonomyCategory/aa-1-1",
"level" => 2,
"name" => "Grandchild",
"full_name" => "Root > Child > Grandchild",
"parent_id" => "gid://shopify/TaxonomyCategory/aa-1",
"attributes" => [],
"children" => [],
"ancestors" => [
{
"id" => "gid://shopify/TaxonomyCategory/aa-1",
"name" => "Child",
},
{
"id" => "gid://shopify/TaxonomyCategory/aa",
"name" => "Root",
},
],
}
assert_equal expected_json, JsonSerializer.serialize(@grandchild)
end
test "serialize returns the localized JSON representation of the category for root node" do
stub_localizations
expected_json = {
"id" => "gid://shopify/TaxonomyCategory/aa",
"level" => 0,
"name" => "Root en français",
"full_name" => "Root en français",
"parent_id" => nil,
"attributes" => [],
"children" => [{
"id" => "gid://shopify/TaxonomyCategory/aa-1",
"name" => "Child en français",
}],
"ancestors" => [],
}
assert_equal expected_json, JsonSerializer.serialize(@root, locale: "fr")
end
test "serialize returns the JSON representation of the category with children sorted by name" do
yaml_content = <<~YAML
---
- id: aa
name: Root
children:
- aa-1
- aa-2
- aa-3
attributes: []
- id: aa-1
name: Cccc
children: []
attributes: []
- id: aa-2
name: Bbbb
children: []
attributes: []
- id: aa-3
name: Aaaa
children: []
attributes: []
YAML
ProductTaxonomy::Category.load_from_source(YAML.safe_load(yaml_content))
actual_json = JsonSerializer
.serialize(ProductTaxonomy::Category.verticals.first)["children"]
.map { _1["name"] }
assert_equal ["Aaaa", "Bbbb", "Cccc"], actual_json
end
test "serialize returns the JSON representation of the category with attributes sorted by name" do
value = ProductTaxonomy::Value.new(id: 1, name: "Black", friendly_id: "black", handle: "black")
ProductTaxonomy::Value.add(value)
attribute1 = ProductTaxonomy::Attribute.new(
id: 1,
name: "Aaaa",
friendly_id: "aaaa",
handle: "aaaa",
description: "Aaaa",
values: [value],
)
attribute2 = ProductTaxonomy::Attribute.new(
id: 2,
name: "Bbbb",
friendly_id: "bbbb",
handle: "bbbb",
description: "Bbbb",
values: [value],
)
attribute3 = ProductTaxonomy::Attribute.new(
id: 3,
name: "Cccc",
friendly_id: "cccc",
handle: "cccc",
description: "Cccc",
values: [value],
)
ProductTaxonomy::Attribute.add(attribute1)
ProductTaxonomy::Attribute.add(attribute2)
ProductTaxonomy::Attribute.add(attribute3)
yaml_content = <<~YAML
---
- id: aa
name: Root
attributes:
- cccc
- bbbb
- aaaa
children: []
YAML
ProductTaxonomy::Category.load_from_source(YAML.safe_load(yaml_content))
actual_json = JsonSerializer
.serialize(ProductTaxonomy::Category.verticals.first)["attributes"]
.map { _1["name"] }
assert_equal ["Aaaa", "Bbbb", "Cccc"], actual_json
end
test "serialize_all returns the JSON representation of all categories" do
stub_localizations
ProductTaxonomy::Category.stubs(:verticals).returns([@root])
expected_json = {
"version" => "1.0",
"verticals" => [{
"name" => "Root",
"prefix" => "aa",
"categories" => [
{
"id" => "gid://shopify/TaxonomyCategory/aa",
"level" => 0,
"name" => "Root",
"full_name" => "Root",
"parent_id" => nil,
"attributes" => [],
"children" => [{ "id" => "gid://shopify/TaxonomyCategory/aa-1", "name" => "Child" }],
"ancestors" => [],
},
{
"id" => "gid://shopify/TaxonomyCategory/aa-1",
"level" => 1,
"name" => "Child",
"full_name" => "Root > Child",
"parent_id" => "gid://shopify/TaxonomyCategory/aa",
"attributes" => [],
"children" => [{ "id" => "gid://shopify/TaxonomyCategory/aa-1-1", "name" => "Grandchild" }],
"ancestors" => [{ "id" => "gid://shopify/TaxonomyCategory/aa", "name" => "Root" }],
},
{
"id" => "gid://shopify/TaxonomyCategory/aa-1-1",
"level" => 2,
"name" => "Grandchild",
"full_name" => "Root > Child > Grandchild",
"parent_id" => "gid://shopify/TaxonomyCategory/aa-1",
"attributes" => [],
"children" => [],
"ancestors" => [
{ "id" => "gid://shopify/TaxonomyCategory/aa-1", "name" => "Child" },
{ "id" => "gid://shopify/TaxonomyCategory/aa", "name" => "Root" },
],
},
],
}],
}
assert_equal expected_json, JsonSerializer.serialize_all(version: "1.0")
end
private
def stub_localizations
fr_yaml = <<~YAML
fr:
categories:
aa:
name: "Root en français"
aa-1:
name: "Child en français"
aa-1-1:
name: "Grandchild en français"
YAML
es_yaml = <<~YAML
es:
categories:
aa:
name: "Root en español"
aa-1:
name: "Child en español"
aa-1-1:
name: "Grandchild en español"
YAML
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "categories", "*.yml"))
.returns(["fake/path/fr.yml", "fake/path/es.yml"])
YAML.stubs(:safe_load_file).with("fake/path/fr.yml").returns(YAML.safe_load(fr_yaml))
YAML.stubs(:safe_load_file).with("fake/path/es.yml").returns(YAML.safe_load(es_yaml))
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "attributes", "*.yml"))
.returns([])
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "values", "*.yml"))
.returns([])
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/category/dist/txt_serializer_test.rb | dev/test/models/serializers/category/dist/txt_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Category
module Dist
class TxtSerializerTest < TestCase
setup do
@root = ProductTaxonomy::Category.new(id: "aa", name: "Root")
@child = ProductTaxonomy::Category.new(id: "aa-1", name: "Child")
@root.add_child(@child)
@grandchild = ProductTaxonomy::Category.new(id: "aa-1-1", name: "Grandchild")
@child.add_child(@grandchild)
end
test "serialize returns the TXT representation of the category" do
assert_equal "gid://shopify/TaxonomyCategory/aa : Root", TxtSerializer.serialize(@root, padding: 0)
end
test "serialize returns the localized TXT representation of the category" do
stub_localizations
actual_txt = TxtSerializer.serialize(@root, padding: 0, locale: "fr")
assert_equal "gid://shopify/TaxonomyCategory/aa : Root en français", actual_txt
end
test "serialize_all returns the TXT representation of all categories with correct padding" do
stub_localizations
ProductTaxonomy::Category.stubs(:verticals).returns([@root])
ProductTaxonomy::Category.add(@root)
ProductTaxonomy::Category.add(@child)
ProductTaxonomy::Category.add(@grandchild)
expected_txt = <<~TXT
# Shopify Product Taxonomy - Categories: 1.0
# Format: {GID} : {Ancestor name} > ... > {Category name}
gid://shopify/TaxonomyCategory/aa : Root
gid://shopify/TaxonomyCategory/aa-1 : Root > Child
gid://shopify/TaxonomyCategory/aa-1-1 : Root > Child > Grandchild
TXT
assert_equal expected_txt.strip, TxtSerializer.serialize_all(version: "1.0")
end
private
def stub_localizations
fr_yaml = <<~YAML
fr:
categories:
aa:
name: "Root en français"
aa-1:
name: "Child en français"
aa-1-1:
name: "Grandchild en français"
YAML
es_yaml = <<~YAML
es:
categories:
aa:
name: "Root en español"
aa-1:
name: "Child en español"
aa-1-1:
name: "Grandchild en español"
YAML
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "categories", "*.yml"))
.returns(["fake/path/fr.yml", "fake/path/es.yml"])
YAML.stubs(:safe_load_file).with("fake/path/fr.yml").returns(YAML.safe_load(fr_yaml))
YAML.stubs(:safe_load_file).with("fake/path/es.yml").returns(YAML.safe_load(es_yaml))
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "attributes", "*.yml"))
.returns([])
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "values", "*.yml"))
.returns([])
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/category/data/data_serializer_test.rb | dev/test/models/serializers/category/data/data_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Category
module Data
class DataSerializerTest < TestCase
setup do
@root = ProductTaxonomy::Category.new(id: "aa", name: "Root")
@child = ProductTaxonomy::Category.new(id: "aa-1", name: "Child")
@root.add_child(@child)
@value = ProductTaxonomy::Value.new(
id: 1,
name: "Black",
friendly_id: "black",
handle: "black",
)
@attribute = ProductTaxonomy::Attribute.new(
id: 1,
name: "Color",
friendly_id: "color",
handle: "color",
description: "Test attribute",
values: [@value],
)
@child.attributes << @attribute
ProductTaxonomy::Category.add(@root)
ProductTaxonomy::Category.add(@child)
ProductTaxonomy::Category.stubs(:verticals).returns([@root])
end
teardown do
ProductTaxonomy::Category.reset
end
test "serialize returns the expected data structure" do
expected = {
"id" => "aa",
"name" => "Root",
"children" => ["aa-1"],
"attributes" => [],
}
assert_equal expected, DataSerializer.serialize(@root)
end
test "serialize_all returns all categories in data format" do
expected = [
{
"id" => "aa",
"name" => "Root",
"children" => ["aa-1"],
"attributes" => [],
},
{
"id" => "aa-1",
"name" => "Child",
"children" => [],
"attributes" => ["color"],
},
]
assert_equal expected, DataSerializer.serialize_all
end
test "serialize_all with root returns descendants and self in data format" do
expected = [
{
"id" => "aa",
"name" => "Root",
"children" => ["aa-1"],
"attributes" => [],
},
{
"id" => "aa-1",
"name" => "Child",
"children" => [],
"attributes" => ["color"],
},
]
assert_equal expected, DataSerializer.serialize_all(@root)
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/category/data/localizations_serializer_test.rb | dev/test/models/serializers/category/data/localizations_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Category
module Data
class LocalizationsSerializerTest < TestCase
setup do
@root = ProductTaxonomy::Category.new(id: "aa", name: "Root")
@child = ProductTaxonomy::Category.new(id: "aa-1", name: "Child")
@root.add_child(@child)
ProductTaxonomy::Category.add(@root)
ProductTaxonomy::Category.add(@child)
ProductTaxonomy::Category.stubs(:verticals).returns([@root])
end
teardown do
ProductTaxonomy::Category.reset
end
test "serialize returns the expected data structure for a category" do
expected = {
"aa" => {
"name" => "Root",
"context" => "Root",
}
}
assert_equal expected, LocalizationsSerializer.serialize(@root)
end
test "serialize_all returns all categories in localization format" do
expected = {
"en" => {
"categories" => {
"aa" => {
"name" => "Root",
"context" => "Root",
},
"aa-1" => {
"name" => "Child",
"context" => "Root > Child",
}
}
}
}
assert_equal expected, LocalizationsSerializer.serialize_all
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/category/data/full_names_serializer_test.rb | dev/test/models/serializers/category/data/full_names_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Category
module Data
class FullNamesSerializerTest < TestCase
setup do
@root = ProductTaxonomy::Category.new(id: "aa", name: "Root")
@child = ProductTaxonomy::Category.new(id: "aa-1", name: "Child")
@grandchild = ProductTaxonomy::Category.new(id: "aa-1-1", name: "Grandchild")
@root.add_child(@child)
@child.add_child(@grandchild)
end
test "serialize returns the expected data structure" do
expected = {
"id" => "aa",
"full_name" => "Root",
}
assert_equal expected, FullNamesSerializer.serialize(@root)
end
test "serialize generates proper full_name for child category" do
expected = {
"id" => "aa-1",
"full_name" => "Root > Child",
}
assert_equal expected, FullNamesSerializer.serialize(@child)
end
test "serialize generates proper full_name for grandchild category" do
expected = {
"id" => "aa-1-1",
"full_name" => "Root > Child > Grandchild",
}
assert_equal expected, FullNamesSerializer.serialize(@grandchild)
end
test "serialize_all returns all categories with correct full_names" do
ProductTaxonomy::Category.add(@root)
ProductTaxonomy::Category.add(@child)
ProductTaxonomy::Category.add(@grandchild)
expected = [
{
"id" => "aa",
"full_name" => "Root",
},
{
"id" => "aa-1",
"full_name" => "Root > Child",
},
{
"id" => "aa-1-1",
"full_name" => "Root > Child > Grandchild",
},
]
assert_equal expected, FullNamesSerializer.serialize_all
end
test "serialize_all sorts categories by full_name" do
cat_a = ProductTaxonomy::Category.new(id: "zz", name: "Apples")
cat_b = ProductTaxonomy::Category.new(id: "yy", name: "Bananas")
cat_c = ProductTaxonomy::Category.new(id: "xx", name: "Cherries")
ProductTaxonomy::Category.add(cat_c)
ProductTaxonomy::Category.add(cat_a)
ProductTaxonomy::Category.add(cat_b)
expected = [
{
"id" => "zz",
"full_name" => "Apples",
},
{
"id" => "yy",
"full_name" => "Bananas",
},
{
"id" => "xx",
"full_name" => "Cherries",
},
]
assert_equal expected, FullNamesSerializer.serialize_all
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/value/dist/json_serializer_test.rb | dev/test/models/serializers/value/dist/json_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Value
module Dist
class JsonSerializerTest < TestCase
setup do
@value = ProductTaxonomy::Value.new(
id: 1,
name: "Black",
friendly_id: "color__black",
handle: "color__black"
)
@attribute = ProductTaxonomy::Attribute.new(
id: 1,
name: "Color",
friendly_id: "color",
handle: "color",
description: "Color",
values: [@value]
)
ProductTaxonomy::Attribute.add(@attribute)
end
test "serialize returns the JSON representation of the value" do
expected_json = {
"id" => "gid://shopify/TaxonomyValue/1",
"name" => "Black",
"handle" => "color__black"
}
assert_equal expected_json, JsonSerializer.serialize(@value)
end
test "serialize returns the localized JSON representation of the value" do
stub_localizations
expected_json = {
"id" => "gid://shopify/TaxonomyValue/1",
"name" => "Nom en français",
"handle" => "color__black"
}
assert_equal expected_json, JsonSerializer.serialize(@value, locale: "fr")
end
test "serialize_all returns the JSON representation of all values" do
ProductTaxonomy::Value.add(@value)
expected_json = {
"version" => "1.0",
"values" => [
{
"id" => "gid://shopify/TaxonomyValue/1",
"name" => "Black",
"handle" => "color__black"
}
]
}
assert_equal expected_json, JsonSerializer.serialize_all(version: "1.0")
end
test "serialize_all returns the JSON representation of all values sorted by name with 'Other' at the end" do
add_values_for_sorting
expected_json = {
"version" => "1.0",
"values" => [
{
"id" => "gid://shopify/TaxonomyValue/4",
"name" => "Aaaa",
"handle" => "color__aaa"
},
{
"id" => "gid://shopify/TaxonomyValue/2",
"name" => "Bbbb",
"handle" => "color__bbb"
},
{
"id" => "gid://shopify/TaxonomyValue/1",
"name" => "Cccc",
"handle" => "color__ccc"
},
{
"id" => "gid://shopify/TaxonomyValue/3",
"name" => "Other",
"handle" => "color__other"
}
]
}
assert_equal expected_json, JsonSerializer.serialize_all(version: "1.0")
end
test "serialize_all sorts localized values according to their sort order in English" do
add_values_for_sorting
stub_localizations_for_sorting
expected_json = {
"version" => "1.0",
"values" => [
{
"id" => "gid://shopify/TaxonomyValue/4",
"name" => "Zzzz",
"handle" => "color__aaa"
},
{
"id" => "gid://shopify/TaxonomyValue/2",
"name" => "Xxxx",
"handle" => "color__bbb"
},
{
"id" => "gid://shopify/TaxonomyValue/1",
"name" => "Yyyy",
"handle" => "color__ccc"
},
{
"id" => "gid://shopify/TaxonomyValue/3",
"name" => "Autre",
"handle" => "color__other"
}
]
}
assert_equal expected_json, JsonSerializer.serialize_all(version: "1.0", locale: "fr")
end
private
def stub_localizations
fr_yaml = <<~YAML
fr:
values:
color__black:
name: "Nom en français"
YAML
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "values", "*.yml"))
.returns(["fake/path/fr.yml"])
YAML.stubs(:safe_load_file).with("fake/path/fr.yml").returns(YAML.safe_load(fr_yaml))
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "attributes", "*.yml"))
.returns([])
end
def add_values_for_sorting
[
ProductTaxonomy::Value.new(id: 1, name: "Cccc", friendly_id: "color__ccc", handle: "color__ccc"),
ProductTaxonomy::Value.new(id: 2, name: "Bbbb", friendly_id: "color__bbb", handle: "color__bbb"),
ProductTaxonomy::Value.new(id: 3, name: "Other", friendly_id: "color__other", handle: "color__other"),
ProductTaxonomy::Value.new(id: 4, name: "Aaaa", friendly_id: "color__aaa", handle: "color__aaa")
].each { ProductTaxonomy::Value.add(_1) }
end
def stub_localizations_for_sorting
fr_yaml = <<~YAML
fr:
values:
color__aaa:
name: "Zzzz"
color__bbb:
name: "Xxxx"
color__ccc:
name: "Yyyy"
color__other:
name: "Autre"
YAML
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "values", "*.yml"))
.returns(["fake/path/fr.yml"])
YAML.stubs(:safe_load_file).with("fake/path/fr.yml").returns(YAML.safe_load(fr_yaml))
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "attributes", "*.yml"))
.returns([])
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/value/dist/txt_serializer_test.rb | dev/test/models/serializers/value/dist/txt_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Value
module Dist
class TxtSerializerTest < TestCase
setup do
@value = ProductTaxonomy::Value.new(
id: 1,
name: "Black",
friendly_id: "color__black",
handle: "color__black"
)
@attribute = ProductTaxonomy::Attribute.new(
id: 1,
name: "Color",
friendly_id: "color",
handle: "color",
description: "Color",
values: [@value]
)
ProductTaxonomy::Attribute.add(@attribute)
end
test "serialize returns the text representation of the value" do
expected_txt = "gid://shopify/TaxonomyValue/1 : Black [Color]"
assert_equal expected_txt, TxtSerializer.serialize(@value)
end
test "serialize returns the localized text representation of the value" do
stub_localizations
expected_txt = "gid://shopify/TaxonomyValue/1 : Nom en français [Color]"
assert_equal expected_txt, TxtSerializer.serialize(@value, locale: "fr")
end
test "serialize_all returns the text representation of all values with correct padding" do
value2 = ProductTaxonomy::Value.new(
id: 123456,
name: "Blue",
friendly_id: "color__blue",
handle: "color__blue"
)
ProductTaxonomy::Value.add(@value)
ProductTaxonomy::Value.add(value2)
expected_txt = <<~TXT
# Shopify Product Taxonomy - Attribute Values: 1.0
# Format: {GID} : {Value name} [{Attribute name}]
gid://shopify/TaxonomyValue/1 : Black [Color]
gid://shopify/TaxonomyValue/123456 : Blue [Color]
TXT
assert_equal expected_txt.strip, TxtSerializer.serialize_all(version: "1.0")
end
test "serialize_all returns the text representation of all values sorted by name with 'Other' at the end" do
add_values_for_sorting
expected_txt = <<~TXT
# Shopify Product Taxonomy - Attribute Values: 1.0
# Format: {GID} : {Value name} [{Attribute name}]
gid://shopify/TaxonomyValue/4 : Aaaa [Color]
gid://shopify/TaxonomyValue/2 : Bbbb [Color]
gid://shopify/TaxonomyValue/1 : Cccc [Color]
gid://shopify/TaxonomyValue/3 : Other [Color]
TXT
assert_equal expected_txt.strip, TxtSerializer.serialize_all(version: "1.0")
end
test "serialize_all sorts localized values according to their sort order in English" do
add_values_for_sorting
stub_localizations_for_sorting
expected_txt = <<~TXT
# Shopify Product Taxonomy - Attribute Values: 1.0
# Format: {GID} : {Value name} [{Attribute name}]
gid://shopify/TaxonomyValue/4 : Zzzz [Color]
gid://shopify/TaxonomyValue/2 : Xxxx [Color]
gid://shopify/TaxonomyValue/1 : Yyyy [Color]
gid://shopify/TaxonomyValue/3 : Autre [Color]
TXT
assert_equal expected_txt.strip, TxtSerializer.serialize_all(version: "1.0", locale: "fr")
end
private
def stub_localizations
fr_yaml = <<~YAML
fr:
values:
color__black:
name: "Nom en français"
YAML
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "values", "*.yml"))
.returns(["fake/path/fr.yml"])
YAML.stubs(:safe_load_file).with("fake/path/fr.yml").returns(YAML.safe_load(fr_yaml))
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "attributes", "*.yml"))
.returns([])
end
def add_values_for_sorting
[
ProductTaxonomy::Value.new(id: 1, name: "Cccc", friendly_id: "color__ccc", handle: "color__ccc"),
ProductTaxonomy::Value.new(id: 2, name: "Bbbb", friendly_id: "color__bbb", handle: "color__bbb"),
ProductTaxonomy::Value.new(id: 3, name: "Other", friendly_id: "color__other", handle: "color__other"),
ProductTaxonomy::Value.new(id: 4, name: "Aaaa", friendly_id: "color__aaa", handle: "color__aaa")
].each { ProductTaxonomy::Value.add(_1) }
end
def stub_localizations_for_sorting
fr_yaml = <<~YAML
fr:
values:
color__aaa:
name: "Zzzz"
color__bbb:
name: "Xxxx"
color__ccc:
name: "Yyyy"
color__other:
name: "Autre"
YAML
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "values", "*.yml"))
.returns(["fake/path/fr.yml"])
YAML.stubs(:safe_load_file).with("fake/path/fr.yml").returns(YAML.safe_load(fr_yaml))
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "attributes", "*.yml"))
.returns([])
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/value/data/data_serializer_test.rb | dev/test/models/serializers/value/data/data_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Value
module Data
class DataSerializerTest < TestCase
setup do
@value1 = ProductTaxonomy::Value.new(
id: 1,
name: "Black",
friendly_id: "color__black",
handle: "color__black"
)
@value2 = ProductTaxonomy::Value.new(
id: 2,
name: "Red",
friendly_id: "color__red",
handle: "color__red"
)
@value3 = ProductTaxonomy::Value.new(
id: 3,
name: "Blue",
friendly_id: "color__blue",
handle: "color__blue"
)
ProductTaxonomy::Value.add(@value1)
ProductTaxonomy::Value.add(@value2)
ProductTaxonomy::Value.add(@value3)
end
test "serialize returns the expected data structure for a value" do
expected = {
"id" => 1,
"name" => "Black",
"friendly_id" => "color__black",
"handle" => "color__black"
}
assert_equal expected, DataSerializer.serialize(@value1)
end
test "serialize_all returns all values in data format" do
expected = [
{
"id" => 1,
"name" => "Black",
"friendly_id" => "color__black",
"handle" => "color__black"
},
{
"id" => 2,
"name" => "Red",
"friendly_id" => "color__red",
"handle" => "color__red"
},
{
"id" => 3,
"name" => "Blue",
"friendly_id" => "color__blue",
"handle" => "color__blue"
}
]
assert_equal expected, DataSerializer.serialize_all
end
test "serialize_all sorts values by ID" do
# Add values in random order to ensure sorting is by ID
ProductTaxonomy::Value.reset
ProductTaxonomy::Value.add(@value3)
ProductTaxonomy::Value.add(@value1)
ProductTaxonomy::Value.add(@value2)
result = DataSerializer.serialize_all
assert_equal 3, result.length
assert_equal "color__black", result[0]["friendly_id"]
assert_equal "color__red", result[1]["friendly_id"]
assert_equal "color__blue", result[2]["friendly_id"]
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/value/data/localizations_serializer_test.rb | dev/test/models/serializers/value/data/localizations_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Value
module Data
class LocalizationsSerializerTest < TestCase
setup do
@value = ProductTaxonomy::Value.new(
id: 1,
name: "Black",
friendly_id: "black",
handle: "black"
)
@attribute = ProductTaxonomy::Attribute.new(
id: 1,
name: "Color",
friendly_id: "color",
handle: "color",
description: "Test attribute",
values: [@value]
)
@value.stubs(:primary_attribute).returns(@attribute)
end
test "serialize returns the expected data structure for a value" do
expected = {
"black" => {
"name" => "Black",
"context" => "Color"
}
}
assert_equal expected, LocalizationsSerializer.serialize(@value)
end
test "serialize_all returns all values in localization format" do
ProductTaxonomy::Value.stubs(:all).returns([@value])
expected = {
"en" => {
"values" => {
"black" => {
"name" => "Black",
"context" => "Color"
}
}
}
}
assert_equal expected, LocalizationsSerializer.serialize_all
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/attribute/docs/base_and_extended_serializer_test.rb | dev/test/models/serializers/attribute/docs/base_and_extended_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Attribute
module Docs
class BaseAndExtendedSerializerTest < TestCase
setup do
@value = ProductTaxonomy::Value.new(
id: 1,
name: "Test Value",
friendly_id: "test_value",
handle: "test_value",
)
@base_attribute = ProductTaxonomy::Attribute.new(
id: 1,
name: "Base Attribute",
description: "Base Description",
friendly_id: "base_attribute",
handle: "base_handle",
values: [@value],
)
@extended_attribute = ProductTaxonomy::ExtendedAttribute.new(
name: "Extended Attribute",
description: "Extended Description",
friendly_id: "extended_attribute",
handle: "extended_handle",
values_from: @base_attribute,
)
end
test "serialize base attribute returns the expected structure" do
expected = {
"id" => "gid://shopify/TaxonomyAttribute/1",
"name" => "Base Attribute",
"handle" => "base_handle",
"values" => [
{
"id" => "gid://shopify/TaxonomyValue/1",
"name" => "Test Value",
},
],
}
assert_equal expected, BaseAndExtendedSerializer.serialize(@base_attribute)
end
test "serialize extended attribute returns the expected structure" do
expected = {
"id" => "gid://shopify/TaxonomyAttribute/1",
"name" => "Base Attribute",
"handle" => "extended_handle",
"extended_name" => "Extended Attribute",
"values" => [
{
"id" => "gid://shopify/TaxonomyValue/1",
"name" => "Test Value",
},
],
}
assert_equal expected, BaseAndExtendedSerializer.serialize(@extended_attribute)
end
test "serialize_all returns base and extended attributes in correct order" do
ProductTaxonomy::Attribute.stubs(:sorted_base_attributes).returns([@base_attribute])
@base_attribute.stubs(:extended_attributes).returns([@extended_attribute])
expected = [
{
"id" => "gid://shopify/TaxonomyAttribute/1",
"name" => "Base Attribute",
"handle" => "extended_handle",
"extended_name" => "Extended Attribute",
"values" => [
{
"id" => "gid://shopify/TaxonomyValue/1",
"name" => "Test Value",
},
],
},
{
"id" => "gid://shopify/TaxonomyAttribute/1",
"name" => "Base Attribute",
"handle" => "base_handle",
"values" => [
{
"id" => "gid://shopify/TaxonomyValue/1",
"name" => "Test Value",
},
],
},
]
assert_equal expected, BaseAndExtendedSerializer.serialize_all
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/attribute/docs/reversed_serializer_test.rb | dev/test/models/serializers/attribute/docs/reversed_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Attribute
module Docs
class ReversedSerializerTest < TestCase
setup do
@value = ProductTaxonomy::Value.new(
id: 1,
name: "Test Value",
friendly_id: "test_value",
handle: "test_value",
)
@attribute = ProductTaxonomy::Attribute.new(
id: 1,
name: "Test Attribute",
description: "Test Description",
friendly_id: "test_attribute",
handle: "test_handle",
values: [@value],
)
@category = ProductTaxonomy::Category.new(
id: 1,
name: "Test Category",
)
@category.attributes << @attribute
end
test "serialize returns the expected JSON structure" do
expected = {
"id" => "gid://shopify/TaxonomyAttribute/1",
"handle" => "test_handle",
"name" => "Test Attribute",
"base_name" => nil,
"categories" => [
{
"id" => "gid://shopify/TaxonomyCategory/1",
"full_name" => "Test Category",
},
],
"values" => [
{
"id" => "gid://shopify/TaxonomyValue/1",
"name" => "Test Value",
},
],
}
assert_equal expected, ReversedSerializer.serialize(@attribute, [@category])
end
test "serialize with extended attribute returns the expected JSON structure" do
base_attribute = ProductTaxonomy::Attribute.new(
id: 2,
name: "Base Attribute",
description: "Base Description",
friendly_id: "base_attribute",
handle: "base_handle",
values: [@value],
)
extended_attribute = ProductTaxonomy::ExtendedAttribute.new(
name: "Extended Attribute",
description: "Extended Description",
friendly_id: "extended_attribute",
handle: "extended_handle",
values_from: base_attribute,
)
expected = {
"id" => "gid://shopify/TaxonomyAttribute/2",
"handle" => "extended_handle",
"name" => "Extended Attribute",
"base_name" => "Base Attribute",
"categories" => [],
"values" => [
{
"id" => "gid://shopify/TaxonomyValue/1",
"name" => "Test Value",
},
],
}
assert_equal expected, ReversedSerializer.serialize(extended_attribute, [])
end
test "serialize_all returns all attributes with their categories" do
ProductTaxonomy::Attribute.stubs(:all).returns([@attribute])
ProductTaxonomy::Category.stubs(:all).returns([@category])
expected = {
"attributes" => [
{
"id" => "gid://shopify/TaxonomyAttribute/1",
"handle" => "test_handle",
"name" => "Test Attribute",
"base_name" => nil,
"categories" => [
{
"id" => "gid://shopify/TaxonomyCategory/1",
"full_name" => "Test Category",
},
],
"values" => [
{
"id" => "gid://shopify/TaxonomyValue/1",
"name" => "Test Value",
},
],
},
],
}
assert_equal expected, ReversedSerializer.serialize_all
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/attribute/docs/search_serializer_test.rb | dev/test/models/serializers/attribute/docs/search_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Attribute
module Docs
class SearchSerializerTest < TestCase
setup do
@value = ProductTaxonomy::Value.new(
id: 1,
name: "Test Value",
friendly_id: "test_value",
handle: "test_value",
)
@attribute = ProductTaxonomy::Attribute.new(
id: 1,
name: "Test Attribute",
description: "Test Description",
friendly_id: "test_attribute",
handle: "test_handle",
values: [@value],
)
end
test "serialize returns the expected search structure" do
expected = {
"searchIdentifier" => "test_handle",
"title" => "Test Attribute",
"url" => "?attributeHandle=test_handle",
"attribute" => {
"handle" => "test_handle",
},
}
assert_equal expected, SearchSerializer.serialize(@attribute)
end
test "serialize_all returns all attributes in search format" do
ProductTaxonomy::Attribute.stubs(:all).returns([@attribute])
expected = [
{
"searchIdentifier" => "test_handle",
"title" => "Test Attribute",
"url" => "?attributeHandle=test_handle",
"attribute" => {
"handle" => "test_handle",
},
},
]
assert_equal expected, SearchSerializer.serialize_all
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/attribute/dist/json_serializer_test.rb | dev/test/models/serializers/attribute/dist/json_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Attribute
module Dist
class JsonSerializerTest < TestCase
setup do
@value = ProductTaxonomy::Value.new(
id: 1,
name: "Black",
friendly_id: "color__black",
handle: "color__black",
)
@attribute = ProductTaxonomy::Attribute.new(
id: 1,
name: "Color",
description: "Defines the primary color or pattern, such as blue or striped",
friendly_id: "color",
handle: "color",
values: [@value],
)
@extended_attribute = ProductTaxonomy::ExtendedAttribute.new(
name: "Clothing Color",
description: "Color of the clothing",
friendly_id: "clothing_color",
handle: "clothing_color",
values_from: @attribute,
)
end
test "serialize returns the JSON representation of the attribute" do
expected_json = {
"id" => "gid://shopify/TaxonomyAttribute/1",
"name" => "Color",
"handle" => "color",
"description" => "Defines the primary color or pattern, such as blue or striped",
"extended_attributes" => [
{
"name" => "Clothing Color",
"handle" => "clothing_color",
},
],
"values" => [
{
"id" => "gid://shopify/TaxonomyValue/1",
"name" => "Black",
"handle" => "color__black",
},
],
}
assert_equal expected_json, JsonSerializer.serialize(@attribute)
end
test "serialize returns the localized JSON representation of the attribute" do
stub_localizations
expected_json = {
"id" => "gid://shopify/TaxonomyAttribute/1",
"name" => "Nom en français",
"handle" => "color",
"description" => "Description en français",
"extended_attributes" => [
{
"name" => "Nom en français (extended)",
"handle" => "clothing_color",
},
],
"values" => [
{
"id" => "gid://shopify/TaxonomyValue/1",
"name" => "Black",
"handle" => "color__black",
},
],
}
assert_equal expected_json, JsonSerializer.serialize(@attribute, locale: "fr")
end
test "serialize_all returns the JSON representation of all attributes" do
ProductTaxonomy::Attribute.add(@attribute)
expected_json = {
"version" => "1.0",
"attributes" => [{
"id" => "gid://shopify/TaxonomyAttribute/1",
"name" => "Color",
"handle" => "color",
"description" => "Defines the primary color or pattern, such as blue or striped",
"extended_attributes" => [
{
"name" => "Clothing Color",
"handle" => "clothing_color",
},
],
"values" => [
{
"id" => "gid://shopify/TaxonomyValue/1",
"name" => "Black",
"handle" => "color__black",
},
],
}],
}
assert_equal expected_json, JsonSerializer.serialize_all(version: "1.0")
end
test "serialize_all returns the JSON representation of all attributes sorted by name" do
add_attributes_for_sorting
expected_json = {
"version" => "1.0",
"attributes" => [
{
"id" => "gid://shopify/TaxonomyAttribute/3",
"name" => "Aaaa",
"handle" => "aaaa",
"description" => "Aaaa",
"extended_attributes" => [],
"values" => [],
},
{
"id" => "gid://shopify/TaxonomyAttribute/2",
"name" => "Bbbb",
"handle" => "bbbb",
"description" => "Bbbb",
"extended_attributes" => [],
"values" => [],
},
{
"id" => "gid://shopify/TaxonomyAttribute/1",
"name" => "Cccc",
"handle" => "cccc",
"description" => "Cccc",
"extended_attributes" => [],
"values" => [],
},
],
}
assert_equal expected_json, JsonSerializer.serialize_all(version: "1.0")
end
test "serialize calls Value.sort_by_localized_name when sorting is not custom" do
attribute = ProductTaxonomy::Attribute.new(
id: 1,
name: "Color",
description: "Defines the primary color or pattern, such as blue or striped",
friendly_id: "color",
handle: "color",
values: [@value],
is_manually_sorted: false,
)
ProductTaxonomy::Value.expects(:sort_by_localized_name)
.with(attribute.values, locale: "en")
.returns([@value])
JsonSerializer.serialize(attribute)
end
test "serialize does not call Value.sort_by_localized_name when sorting is custom" do
attribute = ProductTaxonomy::Attribute.new(
id: 1,
name: "Color",
description: "Defines the primary color or pattern, such as blue or striped",
friendly_id: "color",
handle: "color",
values: [@value],
is_manually_sorted: true,
)
Value.expects(:sort_by_localized_name).with(attribute.values, locale: "en").never
JsonSerializer.serialize(attribute)
end
test "serialize returns extended attributes sorted by name" do
attr = ProductTaxonomy::Attribute.new(
id: 1,
name: "Color",
description: "Defines the primary color or pattern, such as blue or striped",
friendly_id: "color",
handle: "color",
values: [@value],
)
ProductTaxonomy::ExtendedAttribute.new(
name: "Cccc",
handle: "cccc",
description: "Cccc",
friendly_id: "cccc",
values_from: attr,
)
ProductTaxonomy::ExtendedAttribute.new(
name: "Bbbb",
handle: "bbbb",
description: "Bbbb",
friendly_id: "bbbb",
values_from: attr,
)
ProductTaxonomy::ExtendedAttribute.new(
name: "Aaaa",
handle: "aaaa",
description: "Aaaa",
friendly_id: "aaaa",
values_from: attr,
)
expected_json = {
"id" => "gid://shopify/TaxonomyAttribute/1",
"name" => "Color",
"handle" => "color",
"description" => "Defines the primary color or pattern, such as blue or striped",
"extended_attributes" => [
{
"name" => "Aaaa",
"handle" => "aaaa",
},
{
"name" => "Bbbb",
"handle" => "bbbb",
},
{
"name" => "Cccc",
"handle" => "cccc",
},
],
"values" => [
{
"id" => "gid://shopify/TaxonomyValue/1",
"name" => "Black",
"handle" => "color__black",
},
],
}
assert_equal expected_json, JsonSerializer.serialize(attr)
end
private
def stub_localizations
fr_yaml = <<~YAML
fr:
attributes:
color:
name: "Nom en français"
description: "Description en français"
clothing_color:
name: "Nom en français (extended)"
description: "Description en français (extended)"
YAML
es_yaml = <<~YAML
es:
attributes:
color:
name: "Nombre en español"
description: "Descripción en español"
clothing_color:
name: "Nombre en español (extended)"
description: "Descripción en español (extended)"
YAML
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "attributes", "*.yml"))
.returns(["fake/path/fr.yml", "fake/path/es.yml"])
YAML.stubs(:safe_load_file).with("fake/path/fr.yml").returns(YAML.safe_load(fr_yaml))
YAML.stubs(:safe_load_file).with("fake/path/es.yml").returns(YAML.safe_load(es_yaml))
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "values", "*.yml"))
.returns([])
end
def add_attributes_for_sorting
[
ProductTaxonomy::Attribute.new(id: 1,
name: "Cccc",
description: "Cccc",
friendly_id: "cccc",
handle: "cccc",
values: [],
),
ProductTaxonomy::Attribute.new(id: 2,
name: "Bbbb",
description: "Bbbb",
friendly_id: "bbbb",
handle: "bbbb",
values: [],
),
ProductTaxonomy::Attribute.new(
id: 3,
name: "Aaaa",
description: "Aaaa",
friendly_id: "aaaa",
handle: "aaaa",
values: [],
),
].each { ProductTaxonomy::Attribute.add(_1) }
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/attribute/dist/txt_serializer_test.rb | dev/test/models/serializers/attribute/dist/txt_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Attribute
module Dist
class TxtSerializerTest < TestCase
setup do
@value = ProductTaxonomy::Value.new(
id: 1,
name: "Black",
friendly_id: "color__black",
handle: "color__black",
)
@attribute = ProductTaxonomy::Attribute.new(
id: 1,
name: "Color",
description: "Defines the primary color or pattern, such as blue or striped",
friendly_id: "color",
handle: "color",
values: [@value],
)
end
test "serialize returns the TXT representation of the attribute" do
assert_equal "gid://shopify/TaxonomyAttribute/1 : Color", TxtSerializer.serialize(@attribute)
end
test "serialize returns the localized TXT representation of the attribute" do
stub_localizations
actual_txt = TxtSerializer.serialize(@attribute, locale: "fr")
assert_equal "gid://shopify/TaxonomyAttribute/1 : Nom en français", actual_txt
end
test "serialize_all returns the TXT representation of all attributes with correct padding" do
attribute2 = ProductTaxonomy::Attribute.new(
id: 123456,
name: "Pattern",
description: "Describes the design or motif of a product, such as floral or striped",
friendly_id: "pattern",
handle: "pattern",
values: [],
)
ProductTaxonomy::Attribute.add(@attribute)
ProductTaxonomy::Attribute.add(attribute2)
expected_txt = <<~TXT
# Shopify Product Taxonomy - Attributes: 1.0
# Format: {GID} : {Attribute name}
gid://shopify/TaxonomyAttribute/1 : Color
gid://shopify/TaxonomyAttribute/123456 : Pattern
TXT
assert_equal expected_txt.strip, TxtSerializer.serialize_all(version: "1.0")
end
test "serialize_all returns the TXT representation of all attributes sorted by name" do
add_attributes_for_sorting
expected_txt = <<~TXT
# Shopify Product Taxonomy - Attributes: 1.0
# Format: {GID} : {Attribute name}
gid://shopify/TaxonomyAttribute/3 : Aaaa
gid://shopify/TaxonomyAttribute/2 : Bbbb
gid://shopify/TaxonomyAttribute/1 : Cccc
TXT
assert_equal expected_txt.strip, TxtSerializer.serialize_all(version: "1.0")
end
private
def stub_localizations
fr_yaml = <<~YAML
fr:
attributes:
color:
name: "Nom en français"
description: "Description en français"
clothing_color:
name: "Nom en français (extended)"
description: "Description en français (extended)"
YAML
es_yaml = <<~YAML
es:
attributes:
color:
name: "Nombre en español"
description: "Descripción en español"
clothing_color:
name: "Nombre en español (extended)"
description: "Descripción en español (extended)"
YAML
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "attributes", "*.yml"))
.returns(["fake/path/fr.yml", "fake/path/es.yml"])
YAML.stubs(:safe_load_file).with("fake/path/fr.yml").returns(YAML.safe_load(fr_yaml))
YAML.stubs(:safe_load_file).with("fake/path/es.yml").returns(YAML.safe_load(es_yaml))
Dir.stubs(:glob)
.with(File.join(ProductTaxonomy.data_path, "localizations", "values", "*.yml"))
.returns([])
end
def add_attributes_for_sorting
[
ProductTaxonomy::Attribute.new(id: 1,
name: "Cccc",
description: "Cccc",
friendly_id: "cccc",
handle: "cccc",
values: [],
),
ProductTaxonomy::Attribute.new(id: 2,
name: "Bbbb",
description: "Bbbb",
friendly_id: "bbbb",
handle: "bbbb",
values: [],
),
ProductTaxonomy::Attribute.new(
id: 3,
name: "Aaaa",
description: "Aaaa",
friendly_id: "aaaa",
handle: "aaaa",
values: [],
),
].each { ProductTaxonomy::Attribute.add(_1) }
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/attribute/data/data_serializer_test.rb | dev/test/models/serializers/attribute/data/data_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Attribute
module Data
class DataSerializerTest < TestCase
setup do
@value = ProductTaxonomy::Value.new(
id: 1,
name: "Black",
friendly_id: "color__black",
handle: "color__black",
)
@base_attribute = ProductTaxonomy::Attribute.new(
id: 1,
name: "Color",
description: "Defines the primary color or pattern, such as blue or striped",
friendly_id: "color",
handle: "color",
values: [@value],
)
@extended_attribute = ProductTaxonomy::ExtendedAttribute.new(
name: "Clothing Color",
description: "Color of the clothing",
friendly_id: "clothing_color",
handle: "clothing_color",
values_from: @base_attribute
)
ProductTaxonomy::Value.add(@value)
ProductTaxonomy::Attribute.add(@base_attribute)
ProductTaxonomy::Attribute.add(@extended_attribute)
end
test "serialize returns the expected data structure for base attribute" do
expected = {
"id" => 1,
"name" => "Color",
"description" => "Defines the primary color or pattern, such as blue or striped",
"friendly_id" => "color",
"handle" => "color",
"values" => ["color__black"]
}
assert_equal expected, DataSerializer.serialize(@base_attribute)
end
test "serialize returns the expected data structure for extended attribute" do
expected = {
"name" => "Clothing Color",
"handle" => "clothing_color",
"description" => "Color of the clothing",
"friendly_id" => "clothing_color",
"values_from" => "color"
}
assert_equal expected, DataSerializer.serialize(@extended_attribute)
end
test "serialize_all returns all attributes in data format" do
expected = {
"base_attributes" => [{
"id" => 1,
"name" => "Color",
"description" => "Defines the primary color or pattern, such as blue or striped",
"friendly_id" => "color",
"handle" => "color",
"values" => ["color__black"]
}],
"extended_attributes" => [{
"name" => "Clothing Color",
"handle" => "clothing_color",
"description" => "Color of the clothing",
"friendly_id" => "clothing_color",
"values_from" => "color"
}]
}
assert_equal expected, DataSerializer.serialize_all
end
test "serialize includes sorting field when attribute is manually sorted" do
@base_attribute = ProductTaxonomy::Attribute.new(
id: 2,
name: "Size",
description: "Defines the size of the product",
friendly_id: "size",
handle: "size",
values: [@value],
is_manually_sorted: true
)
ProductTaxonomy::Attribute.add(@base_attribute)
expected = {
"id" => 2,
"name" => "Size",
"description" => "Defines the size of the product",
"friendly_id" => "size",
"handle" => "size",
"sorting" => "custom",
"values" => ["color__black"]
}
assert_equal expected, DataSerializer.serialize(@base_attribute)
end
test "serialize_all sorts base attributes by ID" do
second_base_attribute = ProductTaxonomy::Attribute.new(
id: 2,
name: "Size",
description: "Defines the size of the product",
friendly_id: "size",
handle: "size",
values: []
)
third_base_attribute = ProductTaxonomy::Attribute.new(
id: 3,
name: "Material",
description: "Defines the material of the product",
friendly_id: "material",
handle: "material",
values: []
)
# Add attributes in random order to ensure sorting is by ID
ProductTaxonomy::Attribute.add(third_base_attribute)
ProductTaxonomy::Attribute.add(second_base_attribute)
result = DataSerializer.serialize_all
base_attributes = result["base_attributes"]
assert_equal 3, base_attributes.length
assert_equal "color", base_attributes[0]["friendly_id"]
assert_equal "size", base_attributes[1]["friendly_id"]
assert_equal "material", base_attributes[2]["friendly_id"]
end
test "serialize_all preserves extended attributes order" do
second_extended_attribute = ProductTaxonomy::ExtendedAttribute.new(
name: "Shoe Color",
description: "Color of the shoe",
friendly_id: "shoe_color",
handle: "shoe_color",
values_from: @base_attribute
)
third_extended_attribute = ProductTaxonomy::ExtendedAttribute.new(
name: "Accessory Color",
description: "Color of the accessory",
friendly_id: "accessory_color",
handle: "accessory_color",
values_from: @base_attribute
)
# Add extended attributes in specific order
ProductTaxonomy::Attribute.add(second_extended_attribute)
ProductTaxonomy::Attribute.add(third_extended_attribute)
result = DataSerializer.serialize_all
extended_attributes = result["extended_attributes"]
assert_equal 3, extended_attributes.length
assert_equal "clothing_color", extended_attributes[0]["friendly_id"]
assert_equal "shoe_color", extended_attributes[1]["friendly_id"]
assert_equal "accessory_color", extended_attributes[2]["friendly_id"]
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/serializers/attribute/data/localizations_serializer_test.rb | dev/test/models/serializers/attribute/data/localizations_serializer_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
module Serializers
module Attribute
module Data
class LocalizationsSerializerTest < TestCase
setup do
@value = ProductTaxonomy::Value.new(
id: 1,
name: "Black",
friendly_id: "black",
handle: "black"
)
@attribute = ProductTaxonomy::Attribute.new(
id: 1,
name: "Color",
friendly_id: "color",
handle: "color",
description: "The color of the item",
values: [@value]
)
end
test "serialize returns the expected data structure for an attribute" do
expected = {
"color" => {
"name" => "Color",
"description" => "The color of the item"
}
}
assert_equal expected, LocalizationsSerializer.serialize(@attribute)
end
test "serialize_all returns all attributes in localization format" do
ProductTaxonomy::Attribute.stubs(:all).returns([@attribute])
expected = {
"en" => {
"attributes" => {
"color" => {
"name" => "Color",
"description" => "The color of the item"
}
}
}
}
assert_equal expected, LocalizationsSerializer.serialize_all
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/mixins/formatted_validation_errors_test.rb | dev/test/models/mixins/formatted_validation_errors_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class FormattedValidationErrorsTest < TestCase
class CategoryModel
include ActiveModel::Validations
include FormattedValidationErrors
attr_reader :id, :name
validates :id, presence: true, format: { with: /\A[a-z]{2}(-\d+)*\z/ }
validates :name, presence: true, length: { minimum: 2 }
def initialize(id: nil, name: nil)
@id = id
@name = name
end
def is_a?(klass)
klass == Category || super
end
end
class AttributeModel
include ActiveModel::Validations
include FormattedValidationErrors
attr_reader :friendly_id, :name, :handle
validates :friendly_id, presence: true, format: { with: /\A[a-z_]+\z/ }
validates :name, presence: true
validates :handle, presence: true
validate :validate_custom_base_error
def initialize(friendly_id: nil, name: nil, handle: nil, has_base_error: false)
@friendly_id = friendly_id
@name = name
@handle = handle
@has_base_error = has_base_error
end
def validate_custom_base_error
errors.add(:base, "Custom base error") if @has_base_error
end
end
test "validate! passes through arguments to super" do
model = CategoryModel.new(id: "aa", name: "Test")
assert_nothing_raised { model.validate! }
assert_nothing_raised { model.validate!(:create) }
assert_nothing_raised { model.validate!(:update) }
end
test "validate! formats single attribute error for category-like model" do
model = CategoryModel.new(id: "invalid-id", name: "Test")
error = assert_raises(ActiveModel::ValidationError) { model.validate! }
expected_message = <<~MESSAGE.chomp
Validation failed for categorymodel with id=`invalid-id`:
• id is invalid
MESSAGE
assert_equal expected_message, error.message
assert_equal model, error.model
end
test "validate! formats single attribute error for non-category model" do
model = AttributeModel.new(friendly_id: "invalid-friendly-id", name: "Test", handle: "test")
error = assert_raises(ActiveModel::ValidationError) { model.validate! }
expected_message = <<~MESSAGE.chomp
Validation failed for attributemodel with friendly_id=`invalid-friendly-id`:
• friendly_id is invalid
MESSAGE
assert_equal expected_message, error.message
assert_equal model, error.model
end
test "validate! formats multiple attribute errors for category-like model" do
model = CategoryModel.new(id: "", name: "")
error = assert_raises(ActiveModel::ValidationError) { model.validate! }
expected_message = <<~MESSAGE.chomp
Validation failed for categorymodel with id=``:
• id can't be blank
• id is invalid
• name can't be blank
• name is too short (minimum is 2 characters)
MESSAGE
assert_equal expected_message, error.message
assert_equal model, error.model
end
test "validate! formats multiple attribute errors for non-category model" do
model = AttributeModel.new(friendly_id: "", name: "", handle: "")
error = assert_raises(ActiveModel::ValidationError) { model.validate! }
expected_message = <<~MESSAGE.chomp
Validation failed for attributemodel with friendly_id=``:
• friendly_id can't be blank
• friendly_id is invalid
• name can't be blank
• handle can't be blank
MESSAGE
assert_equal expected_message, error.message
assert_equal model, error.model
end
test "validate! handles base errors without attribute prefix" do
model = AttributeModel.new(friendly_id: "aa", name: "Test", handle: "test", has_base_error: true)
error = assert_raises(ActiveModel::ValidationError) { model.validate! }
expected_message = "Validation failed for attributemodel with friendly_id=`aa`:\n • Custom base error"
assert_equal expected_message, error.message
assert_equal model, error.model
end
test "validate! handles mixed attribute and base errors" do
model = AttributeModel.new(friendly_id: "", name: "Test", handle: "test", has_base_error: true)
error = assert_raises(ActiveModel::ValidationError) { model.validate! }
expected_message = <<~MESSAGE.chomp
Validation failed for attributemodel with friendly_id=``:
• friendly_id can't be blank
• friendly_id is invalid
• Custom base error
MESSAGE
assert_equal expected_message, error.message
assert_equal model, error.model
end
test "validate! handles nil identifier values" do
model = CategoryModel.new(id: nil, name: "Test")
error = assert_raises(ActiveModel::ValidationError) { model.validate! }
expected_message = <<~MESSAGE.chomp
Validation failed for categorymodel with id=``:
• id can't be blank
• id is invalid
MESSAGE
assert_equal expected_message, error.message
assert_equal model, error.model
end
test "validate! preserves original error model" do
model = CategoryModel.new(id: "", name: "")
error = assert_raises(ActiveModel::ValidationError) { model.validate! }
assert_same model, error.model
assert_instance_of CategoryModel, error.model
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/mixins/indexed_test.rb | dev/test/models/mixins/indexed_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class IndexedTest < TestCase
class Model
include ActiveModel::Validations
extend Indexed
class << self
def reset
@hashed_models = nil
end
end
validates_with ProductTaxonomy::Indexed::UniquenessValidator, attributes: [:id]
attr_reader :id
def initialize(id:)
@id = id
end
end
# Subclass of Model to test inheritance behavior with hashed_models
class SubModel < Model
end
setup do
@model = Model.new(id: 1)
Model.add(@model)
end
teardown do
Model.reset
end
test "add adds a model to the index" do
assert_equal 1, Model.size
end
test "add stores models in arrays" do
second_model = Model.new(id: 2)
Model.add(second_model)
assert_instance_of Array, Model.hashed_models[:id][1]
assert_instance_of Array, Model.hashed_models[:id][2]
assert_equal [@model], Model.hashed_models[:id][1]
assert_equal [second_model], Model.hashed_models[:id][2]
end
test "duplicate? returns true if the value exists and refers to a different model" do
different_model = Model.new(id: 1)
assert Model.duplicate?(model: different_model, field: :id)
end
test "duplicate? returns false if the value does not exist" do
model = Model.new(id: 2)
refute Model.duplicate?(model:, field: :id)
end
test "duplicate? returns false if the value exists but refers to the same model" do
refute Model.duplicate?(model: @model, field: :id)
end
test "errors are added to a record with a uniqueness violation when the record is not in the index yet" do
new_model = Model.new(id: 1)
refute new_model.valid?
expected_errors = {
id: [{ error: :taken }],
}
assert_equal expected_errors, new_model.errors.details
end
test "errors are added to a record with a uniqueness violation when the record is already in the index" do
new_model = Model.new(id: 1)
Model.add(new_model)
refute new_model.valid?
expected_errors = {
id: [{ error: :taken }],
}
assert_equal expected_errors, new_model.errors.details
end
test "find_by returns the first model with the specified field value" do
assert_equal @model, Model.find_by(id: 1)
end
test "find_by returns nil if the model with the specified field value is not in the index" do
assert_nil Model.find_by(id: 2)
end
test "find_by raises an error if the field is not hashed" do
assert_raises(ArgumentError) { Model.find_by(name: "test") }
end
test "find_by! returns the first model with the specified field value" do
assert_equal @model, Model.find_by!(id: 1)
end
test "find_by! raises NotFoundError if the model with the specified field value is not in the index" do
assert_raises(ProductTaxonomy::Indexed::NotFoundError) do
Model.find_by!(id: 2)
end
end
test "all returns all models in the index" do
assert_equal [@model], Model.all
end
test "all returns flattened array when multiple models exist" do
second_model = Model.new(id: 2)
Model.add(second_model)
all_models = Model.all
assert_equal 2, all_models.size
assert_includes all_models, @model
assert_includes all_models, second_model
end
test "self.extended sets @is_indexed to true on the extended class" do
assert_equal true, Model.instance_variable_get(:@is_indexed)
end
test "create_validate_and_add! creates, validates, and adds a model to the index" do
Model.reset
model = Model.create_validate_and_add!(id: 2)
assert_equal 2, model.id
assert_equal 1, Model.size
assert_equal model, Model.find_by(id: 2)
end
test "create_validate_and_add! validates with :create context" do
Model.reset
model_instance = Model.new(id: 2)
Model.stubs(:new).returns(model_instance)
model_instance.expects(:validate!).with(:create)
Model.create_validate_and_add!(id: 2)
end
test "create_validate_and_add! raises an error if the model is not valid" do
assert_raises(ActiveModel::ValidationError) do
Model.create_validate_and_add!(id: 1)
end
end
test "subclass shares hashed_models with parent class" do
parent_model = Model.new(id: 2)
Model.add(parent_model)
sub_model = SubModel.new(id: 3)
SubModel.add(sub_model)
assert_equal 3, Model.size
assert_equal 3, SubModel.size
assert_equal parent_model, Model.find_by(id: 2)
assert_equal sub_model, Model.find_by(id: 3)
assert_equal parent_model, SubModel.find_by(id: 2)
assert_equal sub_model, SubModel.find_by(id: 3)
assert_same Model.hashed_models, SubModel.hashed_models
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/test/models/mixins/localized_test.rb | dev/test/models/mixins/localized_test.rb | # frozen_string_literal: true
require "test_helper"
module ProductTaxonomy
class LocalizedTest < TestCase
class TestClass
extend Localized
localized_attr_reader :name, keyed_by: :id
attr_reader :id, :non_localized_attr
def initialize(id:, name:, non_localized_attr:)
@id = id
@name = name
@non_localized_attr = non_localized_attr
end
end
setup do
@test_instance = TestClass.new(id: 1, name: "Raw name", non_localized_attr: "Non-localized attr")
@fr_yaml = <<~YAML
fr:
testclasses:
"1":
name: "Nom en français"
YAML
@es_yaml = <<~YAML
es:
testclasses:
"1":
name: "Nombre en español"
YAML
Dir.stubs(:glob).returns(["fake/path/fr.yml", "fake/path/es.yml"])
YAML.stubs(:safe_load_file).with("fake/path/fr.yml").returns(YAML.safe_load(@fr_yaml))
YAML.stubs(:safe_load_file).with("fake/path/es.yml").returns(YAML.safe_load(@es_yaml))
end
teardown do
TestClass.instance_variable_set(:@localizations, nil)
end
test "localized_attr_reader defines methods that return localized attributes, using raw value if locale is en" do
assert_equal "Raw name", @test_instance.name
assert_equal "Raw name", @test_instance.name(locale: "en")
end
test "localized_attr_reader returns translated value for non-English locales" do
assert_equal "Nom en français", @test_instance.name(locale: "fr")
assert_equal "Nombre en español", @test_instance.name(locale: "es")
end
test "localized_attr_reader falls back to en value if locale is not found" do
assert_equal "Raw name", @test_instance.name(locale: "cs")
assert_equal "Raw name", @test_instance.name(locale: "da")
end
test "localized_attr_reader does not change non-localized attributes" do
assert_equal "Non-localized attr", @test_instance.non_localized_attr
end
test "validate_localizations! passes when all required localizations are present" do
TestClass.stubs(:all).returns([@test_instance])
assert_nothing_raised do
TestClass.validate_localizations!
TestClass.validate_localizations!(["fr"])
TestClass.validate_localizations!(["es"])
TestClass.validate_localizations!(["fr", "es"])
end
end
test "validate_localizations! raises error when localizations are missing" do
test_instance2 = TestClass.new(id: 2, name: "Second", non_localized_attr: "Non-localized attr")
TestClass.stubs(:all).returns([@test_instance, test_instance2])
assert_raises(ArgumentError) do
TestClass.validate_localizations!(["fr"])
end
end
test "validate_localizations! raises error when localizations are incomplete" do
fr_yaml = <<~YAML
fr:
testclasses:
"1":
name: # Missing name
YAML
Dir.unstub(:glob)
Dir.stubs(:glob).returns(["fake/path/fr.yml"])
YAML.unstub(:safe_load_file)
YAML.stubs(:safe_load_file).with("fake/path/fr.yml").returns(YAML.safe_load(fr_yaml))
TestClass.stubs(:all).returns([@test_instance])
assert_raises(ArgumentError) do
TestClass.validate_localizations!(["fr"])
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy.rb | dev/lib/product_taxonomy.rb | # frozen_string_literal: true
require "active_support/all"
require "active_model"
module ProductTaxonomy
DEFAULT_DATA_PATH = File.expand_path("../../data", __dir__)
class << self
attr_writer :data_path
def data_path
@data_path ||= DEFAULT_DATA_PATH
end
end
end
require_relative "product_taxonomy/version"
require_relative "product_taxonomy/loader"
require_relative "product_taxonomy/alphanumeric_sorter"
require_relative "product_taxonomy/identifier_formatter"
require_relative "product_taxonomy/localizations_validator"
require_relative "product_taxonomy/models/mixins/localized"
require_relative "product_taxonomy/models/mixins/indexed"
require_relative "product_taxonomy/models/mixins/formatted_validation_errors"
require_relative "product_taxonomy/models/attribute"
require_relative "product_taxonomy/models/extended_attribute"
require_relative "product_taxonomy/models/value"
require_relative "product_taxonomy/models/category"
require_relative "product_taxonomy/models/taxonomy"
require_relative "product_taxonomy/models/mapping_rule"
require_relative "product_taxonomy/models/integration_version"
require_relative "product_taxonomy/models/serializers/category/data/data_serializer"
require_relative "product_taxonomy/models/serializers/category/data/localizations_serializer"
require_relative "product_taxonomy/models/serializers/category/data/full_names_serializer"
require_relative "product_taxonomy/models/serializers/category/docs/siblings_serializer"
require_relative "product_taxonomy/models/serializers/category/docs/search_serializer"
require_relative "product_taxonomy/models/serializers/category/dist/json_serializer"
require_relative "product_taxonomy/models/serializers/category/dist/txt_serializer"
require_relative "product_taxonomy/models/serializers/attribute/data/data_serializer"
require_relative "product_taxonomy/models/serializers/attribute/data/localizations_serializer"
require_relative "product_taxonomy/models/serializers/attribute/docs/base_and_extended_serializer"
require_relative "product_taxonomy/models/serializers/attribute/docs/reversed_serializer"
require_relative "product_taxonomy/models/serializers/attribute/docs/search_serializer"
require_relative "product_taxonomy/models/serializers/attribute/dist/json_serializer"
require_relative "product_taxonomy/models/serializers/attribute/dist/txt_serializer"
require_relative "product_taxonomy/models/serializers/value/data/data_serializer"
require_relative "product_taxonomy/models/serializers/value/data/localizations_serializer"
require_relative "product_taxonomy/models/serializers/value/dist/json_serializer"
require_relative "product_taxonomy/models/serializers/value/dist/txt_serializer"
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/version.rb | dev/lib/product_taxonomy/version.rb | # frozen_string_literal: true
module ProductTaxonomy
VERSION = "1.0.0"
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/loader.rb | dev/lib/product_taxonomy/loader.rb | # frozen_string_literal: true
require "yaml"
module ProductTaxonomy
class Loader
class << self
def load(values_path:, attributes_path:, categories_glob:)
return if ProductTaxonomy::Category.all.any?
begin
ProductTaxonomy::Value.load_from_source(YAML.load_file(values_path))
ProductTaxonomy::Attribute.load_from_source(YAML.load_file(attributes_path))
categories_source_data = categories_glob.each_with_object([]) do |file, array|
array.concat(YAML.safe_load_file(file))
end
ProductTaxonomy::Category.load_from_source(categories_source_data)
rescue Errno::ENOENT => e
raise ArgumentError, "File not found: #{e.message}"
rescue Psych::SyntaxError => e
raise ArgumentError, "Invalid YAML: #{e.message}"
end
# Run validations that can only be run after the taxonomy has been loaded.
ProductTaxonomy::Value.all.each { |model| model.validate!(:taxonomy_loaded) }
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/alphanumeric_sorter.rb | dev/lib/product_taxonomy/alphanumeric_sorter.rb | # frozen_string_literal: true
module ProductTaxonomy
module AlphanumericSorter
class << self
def sort(values, other_last: false)
values.sort_by.with_index do |value, idx|
[
other_last && value.to_s.downcase == "other" ? 1 : 0,
*normalize_value(value),
idx,
]
end
end
def normalize_value(value)
@normalized_values ||= {}
@normalized_values[value] ||= if (numerical = value.match(RegexPattern::NUMERIC_PATTERN))
[0, *normalize_numerical(numerical)]
elsif (sequential = value.match(RegexPattern::SEQUENTIAL_TEXT_PATTERN))
[1, *normalize_sequential(sequential)]
else
[1, normalize_text(value)]
end
end
private
def normalize_numerical(match)
[
normalize_text(match[:primary_unit] || match[:secondary_unit]) || "",
normalize_text(match[:seperator]) || "-",
normalize_single_number(match[:primary_number]),
normalize_single_number(match[:secondary_number]),
]
end
def normalize_sequential(match)
[
normalize_text(match[:primary_text]),
normalize_single_number(match[:primary_step]),
normalize_text(match[:primary_unit] || match[:secondary_unit]) || "",
normalize_text(match[:seperator]) || "-",
normalize_text(match[:secondary_text]),
normalize_single_number(match[:secondary_step]),
normalize_text(match[:trailing_text]),
]
end
def normalize_single_number(value)
value = value.split.sum(&:to_r) if value&.include?("/")
value.to_f
end
def normalize_text(value)
return if value.nil?
ActiveSupport::Inflector.transliterate(value.strip.downcase)
end
end
module RegexPattern
# matches numbers like -1, 5, 10.5, 3/4, 2 5/8
SINGLE_NUMBER = %r{
-? # Optional negative sign
(?:
\d+\.?\d* # Easy numbers like 5, 10.5
|
(?:\d+\s)?\d+/[1-9]+\d* # Fractions like 3/4, 2 5/8
)
}x
# matches units like sq.ft, km/h
UNITS_OF_MEASURE = %r{
[^\d\./\-] # Matches any character not a digit, dot, slash or dash
[^\-\d]* # Matches any character not a dash or digit
}x
# String capturing is simple
BASIC_TEXT = /\D+/
SEPERATOR = /[\p{Pd}x~]/
# NUMERIC_PATTERN matches a primary number with optional units, and an optional range or dimension
# with a secondary number and its optional units.
NUMERIC_PATTERN = %r{
^\s*(?<primary_number>#{SINGLE_NUMBER}) # 1. Primary number
\s*(?<primary_unit>#{UNITS_OF_MEASURE})? # 2. Optional units for primary number
(?: # Optional range or dimension
\s*(?<seperator>#{SEPERATOR}) # 3. Separator
\s*(?<secondary_number>#{SINGLE_NUMBER}) # 4. Secondary number
\s*(?<secondary_unit>#{UNITS_OF_MEASURE})? # 5. Optional units for secondary number
)?
\s*$
}x
# SEQUENTIAL_TEXT_PATTERN matches a primary non-number string, an optional step, and optional units,
# followed by an optional range or dimension with a secondary non-number string, an optional step,
# and optional units, and finally an optional trailing text.
SEQUENTIAL_TEXT_PATTERN = %r{
^\s*(?<primary_text>#{BASIC_TEXT}) # 1. Primary non-number string
\s*(?<primary_step>#{SINGLE_NUMBER})? # 2. Optional step
\s*(?<primary_unit>#{UNITS_OF_MEASURE})? # 3. Optional units for primary number
(?: # Optional range or dimension
\s*(?<seperator>#{SEPERATOR}) # 4. Separator -- capturing allows us to group ranges and dimensions
\s*(?<secondary_text>#{BASIC_TEXT})? # 5. Optional secondary non-number string
\s*(?<secondary_step>#{SINGLE_NUMBER}) # 6. Secondary step
\s*(?<secondary_unit>#{UNITS_OF_MEASURE})? # 7. Optional units for secondary number
)?
\s*(?<trailing_text>.*)?$ # 8. Optional trailing text
}x
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/identifier_formatter.rb | dev/lib/product_taxonomy/identifier_formatter.rb | # frozen_string_literal: true
module ProductTaxonomy
module IdentifierFormatter
class << self
def format_friendly_id(text)
I18n.transliterate(text)
.downcase
.gsub(%r{[^a-z0-9\s\-_/\.\+#]}, "")
.gsub(/[\s\-\.]+/, "_")
end
def format_handle(text)
I18n.transliterate(text)
.downcase
.gsub(%r{[^a-z0-9\s\-_/\+#]}, "")
.gsub("+", "-plus-")
.gsub("#", "-hashtag-")
.gsub("/", "-")
.gsub(/[\s\.]+/, "-")
.gsub("_-_", "-")
.gsub(/(?<!_)_(?!_)/, "-")
.gsub(/--+/, "-")
.gsub(/\A-+|-+\z/, "")
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/cli.rb | dev/lib/product_taxonomy/cli.rb | # frozen_string_literal: true
require "thor"
require_relative "commands/command"
require_relative "commands/generate_dist_command"
require_relative "commands/find_unmapped_external_categories_command"
require_relative "commands/generate_docs_command"
require_relative "commands/generate_release_command"
require_relative "commands/dump_categories_command"
require_relative "commands/dump_attributes_command"
require_relative "commands/dump_values_command"
require_relative "commands/dump_integration_full_names_command"
require_relative "commands/sync_en_localizations_command"
require_relative "commands/add_category_command"
require_relative "commands/add_attribute_command"
require_relative "commands/add_attributes_to_categories_command"
require_relative "commands/add_value_command"
module ProductTaxonomy
class Cli < Thor
class << self
def exit_on_failure? = true
end
class_option :quiet,
type: :boolean,
default: false,
aliases: ["q"],
desc: "Suppress informational messages, only output errors"
class_option :verbose,
type: :boolean,
default: false,
aliases: ["v"],
desc: "Enable verbose output"
desc "dist", "Generate the taxonomy distribution"
option :version, type: :string, desc: "The version of the taxonomy to generate"
option :locales, type: :array, default: ["en"], desc: "The locales to generate"
def dist
GenerateDistCommand.new(options).run
end
desc "unmapped_external_categories",
"Find categories in an external taxonomy that are not mapped from the Shopify taxonomy"
option :external_taxonomy, type: :string, desc: "The external taxonomy to find unmapped categories in"
def unmapped_external_categories(name_and_version)
FindUnmappedExternalCategoriesCommand.new(options).run(name_and_version)
end
desc "docs", "Generate documentation files"
option :version, type: :string, desc: "The version of the documentation to generate"
def docs
GenerateDocsCommand.new(options).run
end
desc "release CURRENT_VERSION NEXT_VERSION", "Generate a release for CURRENT_VERSION and move to NEXT_VERSION (must end with '-unstable')"
option :locales, type: :array, default: ["all"], desc: "The locales to generate"
def release(current_version, next_version)
GenerateReleaseCommand.new(options.merge(current_version:, next_version:)).run
end
desc "dump_categories", "Dump category verticals to YAML files"
option :verticals, type: :array, desc: "List of vertical IDs to dump (defaults to all verticals)"
def dump_categories
DumpCategoriesCommand.new(options).run
end
desc "dump_attributes", "Dump attributes to YAML file"
def dump_attributes
DumpAttributesCommand.new(options).run
end
desc "dump_values", "Dump values to YAML file"
def dump_values
DumpValuesCommand.new(options).run
end
desc "dump_integration_full_names", "Dump `full_names.yml` from current taxonomy for integrations"
option :version, type: :string, desc: "Version with which to label the dumped data"
def dump_integration_full_names
DumpIntegrationFullNamesCommand.new(options).run
end
desc "sync_en_localizations", "Sync English localizations for categories, attributes, and values"
option :targets, type: :string, desc: "List of targets to sync. Valid targets are: categories, attributes, values"
def sync_en_localizations
SyncEnLocalizationsCommand.new(options).run
end
desc "add_category NAME PARENT_ID", "Add a new category to the taxonomy with NAME, as a child of PARENT_ID"
option :id, type: :string, desc: "Override the created category's ID"
def add_category(name, parent_id)
AddCategoryCommand.new(options.merge(name:, parent_id:)).run
end
desc "add_attribute NAME DESCRIPTION", "Add a new attribute to the taxonomy with NAME and DESCRIPTION"
option :values, type: :string, desc: "A comma separated list of values to add to the attribute"
option :base_attribute_friendly_id, type: :string, desc: "Create an extended attribute by extending the attribute with this friendly ID"
def add_attribute(name, description)
AddAttributeCommand.new(options.merge(name:, description:)).run
end
desc "add_attributes_to_categories ATTRIBUTE_FRIENDLY_IDS CATEGORY_IDS",
"Add one or more attributes to one or more categories. ATTRIBUTE_FRIENDLY_IDS is a comma-separated list of attribute friendly IDs."
option :include_descendants, type: :boolean, desc: "When set, the attributes will be added to all descendants of the specified categories"
def add_attributes_to_categories(attribute_friendly_ids, category_ids)
AddAttributesToCategoriesCommand.new(options.merge(attribute_friendly_ids:, category_ids:)).run
end
desc "add_value NAME ATTRIBUTE_FRIENDLY_ID", "Add a new value with NAME to the primary attribute with ATTRIBUTE_FRIENDLY_ID"
def add_value(name, attribute_friendly_id)
AddValueCommand.new(options.merge(name:, attribute_friendly_id:)).run
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/localizations_validator.rb | dev/lib/product_taxonomy/localizations_validator.rb | # frozen_string_literal: true
module ProductTaxonomy
module LocalizationsValidator
class << self
# Validate that all localizations are present for the given locales. If no locales are provided, all locales
# will be validated and the consistency of locales across models will be checked.
#
# @param locales [Array<String>, nil] The locales to validate. If nil, all locales will be validated.
def validate!(locales = nil)
Category.validate_localizations!(locales)
Attribute.validate_localizations!(locales)
Value.validate_localizations!(locales)
validate_locales_are_consistent! if locales.nil?
end
private
def validate_locales_are_consistent!
categories_locales = Category.localizations.keys
attributes_locales = Attribute.localizations.keys
values_locales = Value.localizations.keys
error_message = "Not all model localizations have the same set of locales"
raise ArgumentError,
error_message unless categories_locales == attributes_locales && attributes_locales == values_locales
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/commands/add_attributes_to_categories_command.rb | dev/lib/product_taxonomy/commands/add_attributes_to_categories_command.rb | # frozen_string_literal: true
module ProductTaxonomy
class AddAttributesToCategoriesCommand < Command
def initialize(options)
super
load_taxonomy
@attribute_friendly_ids = options[:attribute_friendly_ids]
@category_ids = options[:category_ids]
@include_descendants = options[:include_descendants]
end
def execute
add_attributes_to_categories!
update_data_files!
end
private
def add_attributes_to_categories!
@attributes = attribute_friendly_ids.map { |friendly_id| Attribute.find_by!(friendly_id:) }
@categories = category_ids.map { |id| Category.find_by!(id:) }
@categories = @categories.flat_map(&:descendants_and_self) if @include_descendants
@categories.each do |category|
@attributes.each do |attribute|
if category.attributes.include?(attribute)
logger.info("Category `#{category.name}` already has attribute `#{attribute.friendly_id}` - skipping")
else
category.add_attribute(attribute)
end
end
end
logger.info("Added #{@attributes.size} attribute(s) to #{@categories.size} categories")
end
def update_data_files!
roots = @categories.map(&:root).uniq.map(&:id)
DumpCategoriesCommand.new(verticals: roots).execute
SyncEnLocalizationsCommand.new(targets: "categories").execute
GenerateDocsCommand.new({}).execute
end
def attribute_friendly_ids
@attribute_friendly_ids.split(",").map(&:strip)
end
def category_ids
@category_ids.split(",").map(&:strip)
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/commands/command.rb | dev/lib/product_taxonomy/commands/command.rb | # frozen_string_literal: true
require "logger"
require "benchmark"
module ProductTaxonomy
class Command
attr_reader :logger, :options
def initialize(options)
@options = options
@logger = Logger.new($stdout, level: :info)
@logger.formatter = proc { |_, _, _, msg| "#{msg}\n" }
@logger.level = :debug if options[:verbose]
@logger.level = :error if options[:quiet]
end
def run(...)
elapsed = Benchmark.realtime do
execute(...)
end
logger.info("Completed in #{elapsed.round(2)} seconds")
end
def execute(...)
raise NotImplementedError, "#{self.class}#execute must be implemented"
end
def load_taxonomy
values_path = File.expand_path("values.yml", ProductTaxonomy.data_path)
attributes_path = File.expand_path("attributes.yml", ProductTaxonomy.data_path)
categories_glob = Dir.glob(File.expand_path("categories/*.yml", ProductTaxonomy.data_path))
ProductTaxonomy::Loader.load(values_path:, attributes_path:, categories_glob:)
end
def validate_and_sanitize_version!(version)
return version if version.nil?
sanitized_version = version.to_s.strip
unless sanitized_version.match?(/\A[a-zA-Z0-9.-]+\z/) && !sanitized_version.include?("..")
raise ArgumentError,
"Invalid version format. Version can only contain alphanumeric characters, dots, and dashes."
end
sanitized_version
end
def version_file_path
File.expand_path("../VERSION", ProductTaxonomy.data_path)
end
def locales_defined_in_data_path
glob = Dir.glob(File.expand_path("localizations/categories/*.yml", ProductTaxonomy.data_path))
glob.map { File.basename(_1, ".yml") }
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/commands/generate_dist_command.rb | dev/lib/product_taxonomy/commands/generate_dist_command.rb | # frozen_string_literal: true
module ProductTaxonomy
class GenerateDistCommand < Command
OUTPUT_PATH = File.expand_path("../../../../dist", __dir__)
def initialize(options)
super
@version = options[:version] || File.read(version_file_path).strip
@locales = if options[:locales] == ["all"]
glob = Dir.glob(File.expand_path("localizations/categories/*.yml", ProductTaxonomy.data_path))
glob.map { File.basename(_1, ".yml") }
else
options[:locales]
end
# These two are memoized since they get merged to form the "taxonomy" json file
@categories_json_by_locale = {}
@attributes_json_by_locale = {}
end
def execute
logger.info("Version: #{@version}")
logger.info("Locales: #{@locales.join(", ")}")
load_taxonomy
logger.info("Validating localizations")
LocalizationsValidator.validate!(@locales)
@locales.each { generate_dist_files(_1) }
IntegrationVersion.generate_all_distributions(
output_path: OUTPUT_PATH,
logger:,
current_shopify_version: @version,
)
end
private
def generate_dist_files(locale)
logger.info("Generating files for #{locale}")
FileUtils.mkdir_p("#{OUTPUT_PATH}/#{locale}")
["categories", "attributes", "taxonomy", "attribute_values"].each do |type|
generate_txt_file(locale:, type:)
generate_json_file(locale:, type:)
end
end
def generate_txt_file(locale:, type:)
txt_data = case type
when "attributes" then Serializers::Attribute::Dist::TxtSerializer.serialize_all(version: @version, locale:)
when "categories" then Serializers::Category::Dist::TxtSerializer.serialize_all(version: @version, locale:)
when "taxonomy" then return
when "attribute_values" then Serializers::Value::Dist::TxtSerializer.serialize_all(version: @version, locale:)
end
File.write("#{OUTPUT_PATH}/#{locale}/#{type}.txt", txt_data + "\n")
end
def generate_json_file(locale:, type:)
json_data = case type
when "categories"
@categories_json_by_locale[locale] ||= Serializers::Category::Dist::JsonSerializer.serialize_all(
version: @version,
locale:,
)
when "attributes"
@attributes_json_by_locale[locale] ||= Serializers::Attribute::Dist::JsonSerializer.serialize_all(
version: @version,
locale:,
)
when "taxonomy"
@categories_json_by_locale[locale].merge(@attributes_json_by_locale[locale])
when "attribute_values"
Serializers::Value::Dist::JsonSerializer.serialize_all(version: @version, locale:)
end
File.write("#{OUTPUT_PATH}/#{locale}/#{type}.json", JSON.pretty_generate(json_data) + "\n")
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/commands/generate_docs_command.rb | dev/lib/product_taxonomy/commands/generate_docs_command.rb | # frozen_string_literal: true
module ProductTaxonomy
class GenerateDocsCommand < Command
UNSTABLE = "unstable"
class << self
def docs_path
File.expand_path("../docs", ProductTaxonomy.data_path)
end
end
def initialize(options)
super
@version = validate_and_sanitize_version!(options[:version]) || UNSTABLE
end
def execute
logger.info("Version: #{@version}")
load_taxonomy
generate_data_files
generate_release_folder unless @version == UNSTABLE
end
private
def generate_data_files
data_target = File.expand_path("_data/#{@version}", self.class.docs_path)
FileUtils.mkdir_p(data_target)
logger.info("Generating sibling groups...")
sibling_groups_yaml = YAML.dump(Serializers::Category::Docs::SiblingsSerializer.serialize_all, line_width: -1)
File.write("#{data_target}/sibling_groups.yml", sibling_groups_yaml)
logger.info("Generating category search index...")
search_index_json = JSON.fast_generate(Serializers::Category::Docs::SearchSerializer.serialize_all)
File.write("#{data_target}/search_index.json", search_index_json + "\n")
logger.info("Generating attributes...")
attributes_yml = YAML.dump(Serializers::Attribute::Docs::BaseAndExtendedSerializer.serialize_all, line_width: -1)
File.write("#{data_target}/attributes.yml", attributes_yml)
logger.info("Generating mappings...")
mappings_json = JSON.parse(File.read(File.expand_path(
"../dist/en/integrations/all_mappings.json",
ProductTaxonomy.data_path,
)))
mappings_data = reverse_shopify_mapping_rules(mappings_json.fetch("mappings"))
mappings_yml = YAML.dump(mappings_data, line_width: -1)
File.write("#{data_target}/mappings.yml", mappings_yml)
logger.info("Generating attributes with categories...")
reversed_attributes_yml = YAML.dump(
Serializers::Attribute::Docs::ReversedSerializer.serialize_all,
line_width: -1,
)
File.write("#{data_target}/reversed_attributes.yml", reversed_attributes_yml)
logger.info("Generating attribute with categories search index...")
attribute_search_index_json = JSON.fast_generate(Serializers::Attribute::Docs::SearchSerializer.serialize_all)
File.write("#{data_target}/attribute_search_index.json", attribute_search_index_json + "\n")
end
def generate_release_folder
logger.info("Generating release folder...")
release_path = File.expand_path("_releases/#{@version}", self.class.docs_path)
FileUtils.mkdir_p(release_path)
logger.info("Generating index.html...")
content = File.read(File.expand_path("_releases/_index_template.html", self.class.docs_path))
content.gsub!("TITLE", @version.upcase)
content.gsub!("TARGET", @version)
content.gsub!("GH_URL", "https://github.com/Shopify/product-taxonomy/releases/tag/v#{@version}")
File.write("#{release_path}/index.html", content)
logger.info("Generating attributes.html...")
content = File.read(File.expand_path("_releases/_attributes_template.html", self.class.docs_path))
content.gsub!("TITLE", @version.upcase)
content.gsub!("TARGET", @version)
content.gsub!("GH_URL", "https://github.com/Shopify/product-taxonomy/releases/tag/v#{@version}")
File.write("#{release_path}/attributes.html", content)
logger.info("Updating latest.html redirect...")
latest_html_path = File.expand_path("_releases/latest.html", self.class.docs_path)
content = File.read(latest_html_path)
content.gsub!(%r{redirect_to: /releases/.*?/}, "redirect_to: /releases/#{@version}/")
File.write(latest_html_path, content)
end
def reverse_shopify_mapping_rules(mappings)
mappings.each do |mapping|
next unless mapping["output_taxonomy"].include?("shopify")
mapping["input_taxonomy"], mapping["output_taxonomy"] = mapping["output_taxonomy"], mapping["input_taxonomy"]
mapping["rules"] = mapping["rules"].flat_map do |rule|
rule["output"]["category"].map do |output_category|
{
"input" => { "category" => output_category },
"output" => { "category" => [rule["input"]["category"]] },
}
end
end
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/commands/dump_categories_command.rb | dev/lib/product_taxonomy/commands/dump_categories_command.rb | # frozen_string_literal: true
module ProductTaxonomy
class DumpCategoriesCommand < Command
def initialize(options)
super
load_taxonomy
@verticals = options[:verticals] || Category.verticals.map(&:id)
end
def execute
logger.info("Dumping #{@verticals.size} verticals")
@verticals.each do |vertical_id|
vertical_root = Category.find_by!(id: vertical_id)
raise "Category #{vertical_id} is not a vertical" unless vertical_root.root?
logger.info("Updating `#{vertical_root.name}`...")
path = File.expand_path("categories/#{vertical_root.friendly_name}.yml", ProductTaxonomy.data_path)
data = Serializers::Category::Data::DataSerializer.serialize_all(vertical_root)
File.write(path, YAML.dump(data, line_width: -1))
logger.info("Updated `#{path}`")
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/commands/dump_integration_full_names_command.rb | dev/lib/product_taxonomy/commands/dump_integration_full_names_command.rb | # frozen_string_literal: true
module ProductTaxonomy
class DumpIntegrationFullNamesCommand < Command
def initialize(options)
super
@version = options[:version] || File.read(version_file_path).strip
end
def execute
logger.info("Dumping full names from current taxonomy for integrations...")
logger.info("Version: #{@version}")
load_taxonomy
ensure_integration_exists
path = File.expand_path("shopify/#{@version}/full_names.yml", integration_data_path)
FileUtils.mkdir_p(File.dirname(path))
data = Serializers::Category::Data::FullNamesSerializer.serialize_all
File.write(path, YAML.dump(data, line_width: -1))
logger.info("Dumped to `#{path}`")
end
private
def ensure_integration_exists
FileUtils.mkdir_p(File.expand_path("shopify/#{@version}", integration_data_path))
integration_version = "shopify/#{@version}"
integrations_file = File.expand_path("integrations.yml", integration_data_path)
integrations = YAML.safe_load_file(integrations_file)
integration = integrations.find { _1["name"] == "shopify" }
return if integration["available_versions"].include?(integration_version)
integration["available_versions"] << integration_version
File.write(integrations_file, YAML.dump(integrations, line_width: -1))
end
def integration_data_path = IntegrationVersion::INTEGRATIONS_PATH
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/commands/add_value_command.rb | dev/lib/product_taxonomy/commands/add_value_command.rb | # frozen_string_literal: true
module ProductTaxonomy
class AddValueCommand < Command
def initialize(options)
super
load_taxonomy
@name = options[:name]
@attribute_friendly_id = options[:attribute_friendly_id]
end
def execute
create_value!
update_data_files!
end
private
def create_value!
@attribute = Attribute.find_by!(friendly_id: @attribute_friendly_id)
if @attribute.extended?
raise "Attribute `#{@attribute.name}` is an extended attribute, please use a primary attribute instead"
end
friendly_id = IdentifierFormatter.format_friendly_id("#{@attribute.friendly_id}__#{@name}")
value = Value.create_validate_and_add!(
id: Value.next_id,
name: @name,
friendly_id:,
handle: IdentifierFormatter.format_handle(friendly_id),
)
@attribute.add_value(value)
logger.info("Created value `#{value.name}` for attribute `#{@attribute.name}`")
end
def update_data_files!
DumpAttributesCommand.new(options).execute
DumpValuesCommand.new(options).execute
SyncEnLocalizationsCommand.new(targets: "values").execute
GenerateDocsCommand.new({}).execute
logger.warn(
"Attribute has custom sorting, please ensure your new value is in the right position in data/attributes.yml",
) if @attribute.manually_sorted?
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/commands/generate_release_command.rb | dev/lib/product_taxonomy/commands/generate_release_command.rb | # frozen_string_literal: true
module ProductTaxonomy
class GenerateReleaseCommand < Command
def initialize(options)
super
@version = validate_and_sanitize_version!(options[:current_version])
@next_version = validate_and_sanitize_version!(options[:next_version])
if @version.end_with?("-unstable")
raise ArgumentError, "Version must not end with '-unstable' suffix"
end
unless @next_version.end_with?("-unstable")
raise ArgumentError, "Next version must end with '-unstable' suffix"
end
@locales = if options[:locales] == ["all"]
locales_defined_in_data_path
else
options[:locales]
end
end
def execute
check_git_state!
begin
logger.info("Generating release for version: #{@version}")
release_commit_hash = generate_release_version!
logger.info("Moving to next unstable version: #{@next_version}")
next_version_commit_hash = move_to_next_version!
print_summary(release_commit_hash, next_version_commit_hash)
rescue StandardError
print_rollback_instructions
raise
end
end
private
def check_git_state!
current_branch = %x(git rev-parse --abbrev-ref HEAD).strip
unless current_branch == "main"
raise "Must be on main branch to create a release. Current branch: #{current_branch}"
end
status_output = %x(git status --porcelain).strip
unless status_output.empty?
raise "Working directory is not clean. Please commit or stash changes before creating a release."
end
end
def release_commit_message = "Release version #{@version}"
def next_version_commit_message = "Bump version to #{@next_version}"
def generate_release_version!
run_git_command("pull")
run_git_command("checkout", "-b", "release-v#{@version}")
logger.info("Updating VERSION file to #{@version}...")
File.write(version_file_path, @version)
logger.info("Updating integration mappings...")
update_integration_mappings_stable_release
logger.info("Dumping integration full names...")
DumpIntegrationFullNamesCommand.new({}).execute
logger.info("Generating distribution files...")
GenerateDistCommand.new(version: @version, locales: @locales).execute
logger.info("Generating documentation files...")
GenerateDocsCommand.new(version: @version, locales: @locales).execute
logger.info("Updating README.md files...")
update_version_badge(File.expand_path("../README.md", ProductTaxonomy.data_path))
update_version_badge(File.expand_path("../dist/README.md", ProductTaxonomy.data_path))
logger.info("Committing and tagging release version #{@version}...")
run_git_command("add", ".")
run_git_command("commit", "-m", release_commit_message)
run_git_command("tag", "v#{@version}")
get_commit_hash("HEAD")
end
def move_to_next_version!
logger.info("Updating VERSION file to #{@next_version}...")
File.write(version_file_path, @next_version)
logger.info("Updating integration mappings...")
update_integration_mappings_next_unstable
logger.info("Generating distribution files...")
GenerateDistCommand.new(version: @next_version, locales: @locales).execute
logger.info("Generating documentation files...")
GenerateDocsCommand.new(locales: @locales).execute
run_git_command("add", ".")
run_git_command("commit", "-m", next_version_commit_message)
get_commit_hash("HEAD")
end
def run_git_command(*args)
result = system("git", *args, chdir: git_repo_root)
raise "Git command failed." unless result
end
def git_repo_root
@git_repo_root ||= %x(git rev-parse --show-toplevel).strip
end
def get_commit_hash(ref)
%x(git rev-parse --short #{ref}).strip
end
def update_integration_mappings_stable_release
update_mapping_files("to_shopify.yml", "output_taxonomy", "shopify/#{@version}")
update_mapping_files("from_shopify.yml", "input_taxonomy", "shopify/#{@version}")
end
def update_integration_mappings_next_unstable
update_mapping_files("from_shopify.yml", "input_taxonomy", "shopify/#{@next_version}")
end
def update_mapping_files(filename, field_name, new_value)
files = Dir.glob(File.expand_path("integrations/**/mappings/#{filename}", ProductTaxonomy.data_path))
files = [files.sort.last] if filename == "to_shopify.yml"
files.each do |file|
content = File.read(file)
content.gsub!(%r{#{field_name}: shopify/\d{4}-\d{2}(-unstable)?}, "#{field_name}: #{new_value}")
File.write(file, content)
end
end
def update_version_badge(readme_path)
content = File.read(readme_path)
content.gsub!(%r{badge/Version-.*?-blue\.svg}) do
badge_version = @version.gsub("-", "--")
"badge/Version-#{badge_version}-blue.svg"
end
File.write(readme_path, content)
end
def print_summary(release_commit_hash, next_version_commit_hash)
logger.info("\n====== Release Summary ======")
logger.info("- Created commit (#{release_commit_hash}): #{release_commit_message}")
logger.info("- Created commit (#{next_version_commit_hash}): #{next_version_commit_message}")
logger.info("- Created tag: v#{@version}")
logger.info("\nInspect changes with:")
logger.info(" git show #{release_commit_hash}")
logger.info(" git show #{next_version_commit_hash}")
logger.info(" git show v#{@version}")
logger.info("\nNext steps:")
logger.info(" 1. If the changes look good, push the branch")
logger.info(" * Run `git push origin release-v#{@version}`")
logger.info(" 2. Open a PR and follow the usual process to get approval and merge")
logger.info(" * https://github.com/Shopify/product-taxonomy/pull/new/release-v#{@version}")
logger.info(" 3. Once the PR is merged, push the tag that was created")
logger.info(" * Run `git push origin v#{@version}`")
logger.info(" 4. Create a release on GitHub")
logger.info(" * https://github.com/Shopify/product-taxonomy/releases/new?tag=v#{@version}")
end
def print_rollback_instructions
logger.info("\n====== Rollback Instructions ======")
logger.info("The release was aborted due to an error.")
logger.info("You can use the following commands to roll back to the original state:")
logger.info(" git reset --hard main")
# Check if branch exists before suggesting deletion
if system("git", "show-ref", "--verify", "--quiet", "refs/heads/release-v#{@version}")
logger.info(" git branch -D release-v#{@version}")
end
# Check if tag exists before suggesting deletion
if system("git", "show-ref", "--verify", "--quiet", "refs/tags/v#{@version}")
logger.info(" git tag -d v#{@version}")
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/commands/sync_en_localizations_command.rb | dev/lib/product_taxonomy/commands/sync_en_localizations_command.rb | # frozen_string_literal: true
module ProductTaxonomy
class SyncEnLocalizationsCommand < Command
PERMITTED_TARGETS = ["categories", "attributes", "values"].freeze
def initialize(options)
super
load_taxonomy
@targets = options[:targets]&.split(",") || PERMITTED_TARGETS
@targets.each do |target|
raise "Invalid target: #{target}. Must be one of: #{PERMITTED_TARGETS.join(", ")}" unless PERMITTED_TARGETS.include?(target)
end
end
def execute
logger.info("Syncing EN localizations")
sync_categories if @targets.include?("categories")
sync_attributes if @targets.include?("attributes")
sync_values if @targets.include?("values")
end
private
def sync_categories
logger.info("Syncing categories...")
localizations = Serializers::Category::Data::LocalizationsSerializer.serialize_all
write_localizations("categories", localizations)
end
def sync_attributes
logger.info("Syncing attributes...")
localizations = Serializers::Attribute::Data::LocalizationsSerializer.serialize_all
write_localizations("attributes", localizations)
end
def sync_values
logger.info("Syncing values...")
localizations = Serializers::Value::Data::LocalizationsSerializer.serialize_all
write_localizations("values", localizations)
end
# Writes localization data to a YAML file with 'context' keys converted to comments.
# Uses YAML.dump for formatting, then injects context as comments above entry fields.
def write_localizations(type, localizations)
file_path = File.expand_path("localizations/#{type}/en.yml", ProductTaxonomy.data_path)
context_map = extract_contexts(localizations)
yaml_output = YAML.dump(localizations, line_width: -1)
yaml_with_comments = inject_context_comments(yaml_output, context_map, type)
# Verify that comment injection didn't alter the data structure
unless YAML.load(yaml_with_comments) == localizations
raise "Failed to safely inject comments into #{type} localizations"
end
File.open(file_path, "w") do |file|
file.puts "# This file is auto-generated. Do not edit directly."
file.write(yaml_with_comments)
end
logger.info("Wrote #{type} localizations to #{file_path}")
end
# Extracts and removes 'context' keys from the localization hash.
#
# Expects a specific structure from LocalizationsSerializer:
# { "en" => { "section" => { "entry-id" => { "name" => "...", "context" => "..." } } } }
#
# Note: This creates a flat map keyed by entry ID only, so it assumes entry IDs are unique
# across all sections. In practice, each file (categories/attributes/values) contains only
# one section, so there are no collisions.
#
# Returns a map of entry IDs to their context strings.
def extract_contexts(localizations)
context_map = {}
_locale, nested = localizations.first
nested.each do |_section, entries|
entries.each do |id, data|
if data.key?("context")
context_map[id] = data.delete("context")
end
end
end
context_map
end
# Injects context strings as YAML comments below entry IDs (above the first field).
#
# Strategy: Parse YAML.dump output line-by-line to find entry IDs, then inject comments
# at the correct indentation. This adapts to YAML.dump's formatting without hardcoding indentation.
#
# Example transformation:
# aa-1-1: => aa-1-1:
# name: Activewear => # Apparel & Accessories > Clothing > Activewear
# => name: Activewear
def inject_context_comments(yaml_output, context_map, type)
lines = yaml_output.lines
result = []
lines.each_with_index do |line, index|
result << line
# Find lines that look like YAML keys (format: " key:")
if line.match?(/^(\s+)(.+):$/)
current_indent = line[/^(\s+)/, 1]
entry_id = line.strip.chomp(":")
next_line = lines[index + 1]
# Distinguish entry IDs from field names by checking indentation
# Entry IDs have their fields indented MORE (e.g., "aa-1-1:" followed by " name:")
# Field names have values at SAME level or less (e.g., " name:" followed by " value")
is_entry_id = next_line&.match?(/^(\s+)/) && next_line[/^(\s+)/, 1].length > current_indent.length
# If this is an entry ID with context, inject comment at field indentation
if is_entry_id && context_map.key?(entry_id)
# Use the next line's indentation (the field level) for the comment
field_indent = next_line[/^(\s+)/, 1]
result << "#{field_indent}# #{context_map[entry_id]}\n"
end
end
end
result.join
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Shopify/product-taxonomy | https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/commands/add_attribute_command.rb | dev/lib/product_taxonomy/commands/add_attribute_command.rb | # frozen_string_literal: true
module ProductTaxonomy
class AddAttributeCommand < Command
def initialize(options)
super
load_taxonomy
@name = options[:name]
@description = options[:description]
@values = options[:values]
@base_attribute_friendly_id = options[:base_attribute_friendly_id]
end
def execute
if @base_attribute_friendly_id
create_extended_attribute!
else
create_base_attribute_with_values!
end
update_data_files!
end
private
def create_base_attribute_with_values!
raise "Values must be provided when creating a base attribute" if value_names.empty?
@attribute = Attribute.create_validate_and_add!(
id: Attribute.next_id,
name: @name,
description: @description,
friendly_id:,
handle:,
values: find_or_create_values,
)
logger.info("Created base attribute `#{@attribute.name}` with friendly_id=`#{@attribute.friendly_id}`")
end
def create_extended_attribute!
raise "Values should not be provided when creating an extended attribute" if value_names.any?
@attribute = ExtendedAttribute.create_validate_and_add!(
name: @name,
description: @description,
friendly_id:,
handle:,
values_from: Attribute.find_by(friendly_id: @base_attribute_friendly_id) || @base_attribute_friendly_id,
)
logger.info("Created extended attribute `#{@attribute.name}` with friendly_id=`#{@attribute.friendly_id}`")
end
def update_data_files!
DumpAttributesCommand.new({}).execute
DumpValuesCommand.new({}).execute
SyncEnLocalizationsCommand.new(targets: "attributes,values").execute
GenerateDocsCommand.new({}).execute
end
def friendly_id
@friendly_id ||= IdentifierFormatter.format_friendly_id(@name)
end
def handle
@handle ||= IdentifierFormatter.format_handle(friendly_id)
end
def value_names
@values&.split(",")&.map(&:strip) || []
end
def find_or_create_values
value_names.map do |value_name|
value_friendly_id = IdentifierFormatter.format_friendly_id("#{friendly_id}__#{value_name}")
existing_value = Value.find_by(friendly_id: value_friendly_id)
next existing_value if existing_value
Value.create_validate_and_add!(
id: Value.next_id,
name: value_name,
friendly_id: value_friendly_id,
handle: IdentifierFormatter.format_handle(value_friendly_id),
)
end
end
end
end
| ruby | MIT | a1cb6132c9c0885c88ecbda53777f1dfc0e064d9 | 2026-01-04T17:02:35.318003Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.