" do
@@ -276,26 +303,50 @@ RSpec.describe HtmlToMarkdown do
it "supports " do
expect(html_to_markdown("var foo = 'bar'; ")).to eq("```\nvar foo = 'bar';\n```")
- expect(html_to_markdown("var foo = 'bar';
")).to eq("```\nvar foo = 'bar';\n```")
- expect(html_to_markdown(%Q{var foo = 'bar';
})).to eq("```javascript\nvar foo = 'bar';\n```")
- expect(html_to_markdown(" function f() {\n console.log('Hello world!');\n } ")).to eq("```\n function f() {\n console.log('Hello world!');\n }\n```")
+ expect(html_to_markdown("var foo = 'bar';
")).to eq(
+ "```\nvar foo = 'bar';\n```",
+ )
+ expect(
+ html_to_markdown(%Q{var foo = 'bar';
}),
+ ).to eq("```javascript\nvar foo = 'bar';\n```")
+ expect(
+ html_to_markdown(
+ " function f() {\n console.log('Hello world!');\n } ",
+ ),
+ ).to eq("```\n function f() {\n console.log('Hello world!');\n }\n```")
end
it "supports inside " do
- expect(html_to_markdown("var foo = 'bar';
")).to eq("> ```\n> var foo = 'bar';\n> ```")
+ expect(
+ html_to_markdown("var foo = 'bar';
"),
+ ).to eq("> ```\n> var foo = 'bar';\n> ```")
end
it "works" do
- expect(html_to_markdown("")).to eq("- A list item with a blockquote:\n\n > This is a **blockquote**\n > inside a list item.")
+ expect(
+ html_to_markdown(
+ "",
+ ),
+ ).to eq(
+ "- A list item with a blockquote:\n\n > This is a **blockquote**\n > inside a list item.",
+ )
end
it "supports html document" do
- expect(html_to_markdown("HelloWorld
")).to eq("Hello\nWorld")
+ expect(html_to_markdown("HelloWorld
")).to eq(
+ "Hello\nWorld",
+ )
end
it "handles " do
- expect(html_to_markdown("
1st paragraph
2nd paragraph
")).to eq("1st paragraph\n\n2nd paragraph")
- expect(html_to_markdown("1st paragraph
\n 2nd paragraph\n 2nd paragraph
\n3rd paragraph
")).to eq("1st paragraph\n\n2nd paragraph 2nd paragraph\n\n3rd paragraph")
+ expect(html_to_markdown("1st paragraph
2nd paragraph
")).to eq(
+ "1st paragraph\n\n2nd paragraph",
+ )
+ expect(
+ html_to_markdown(
+ "1st paragraph
\n 2nd paragraph\n 2nd paragraph
\n3rd paragraph
",
+ ),
+ ).to eq("1st paragraph\n\n2nd paragraph 2nd paragraph\n\n3rd paragraph")
end
it "handles " do
@@ -324,32 +375,42 @@ RSpec.describe HtmlToMarkdown do
end
it "handles
and
within
" do
- html = "1st paragraph2nd paragraph 3rd paragraph
4th paragraph
"
- expect(html_to_markdown(html)).to eq("1st paragraph\n2nd paragraph\n3rd paragraph\n\n4th paragraph")
+ html =
+ "1st paragraph2nd paragraph 3rd paragraph
4th paragraph
"
+ expect(html_to_markdown(html)).to eq(
+ "1st paragraph\n2nd paragraph\n3rd paragraph\n\n4th paragraph",
+ )
end
context "with an oddly placed " do
-
it "handles " do
- expect(html_to_markdown("Hello Bold World")).to eq("Hello\n**Bold** World")
- expect(html_to_markdown("Hello Bold World")).to eq("Hello **Bold**\nWorld")
- expect(html_to_markdown("Hello Bold text World")).to eq("Hello **Bold**\n**text** World")
+ expect(html_to_markdown("Hello Bold World")).to eq(
+ "Hello\n**Bold** World",
+ )
+ expect(html_to_markdown("Hello Bold World")).to eq(
+ "Hello **Bold**\nWorld",
+ )
+ expect(html_to_markdown("Hello Bold text World")).to eq(
+ "Hello **Bold**\n**text** World",
+ )
end
it "handles " do
expect(html_to_markdown("Hello Italic World")).to eq("Hello\n*Italic* World")
expect(html_to_markdown("Hello Italic World")).to eq("Hello *Italic*\nWorld")
- expect(html_to_markdown("Hello Italic text World")).to eq("Hello *Italic*\n*text* World")
+ expect(html_to_markdown("Hello Italic text World")).to eq(
+ "Hello *Italic*\n*text* World",
+ )
end
it "works" do
- expect(html_to_markdown("A B C D E F G
")).to eq("A __B *C*__\n__*D* E__\n**F** G")
+ expect(html_to_markdown("A B C D E F G
")).to eq(
+ "A __B *C*__\n__*D* E__\n**F** G",
+ )
end
-
end
context "with an empty tag" do
-
it "handles " do
expect(html_to_markdown(" ")).to eq("")
expect(html_to_markdown(" ")).to eq("")
@@ -363,11 +424,9 @@ RSpec.describe HtmlToMarkdown do
expect(html_to_markdown("Some text")).to eq("Some text")
expect(html_to_markdown("Some text")).to eq("Some text")
end
-
end
context "with spaces around text" do
-
it "handles " do
expect(html_to_markdown(" Bold ")).to eq("**Bold**")
expect(html_to_markdown(" Bold ")).to eq("**Bold**")
@@ -389,7 +448,6 @@ RSpec.describe HtmlToMarkdown do
expect(html_to_markdown("Some italic text")).to eq("Some *italic* text")
expect(html_to_markdown("Some italic text")).to eq("Some *italic* text")
end
-
end
it "supports " do
@@ -429,7 +487,9 @@ RSpec.describe HtmlToMarkdown do
expect(html_to_markdown(html)).to eq(markdown.strip)
- expect(html_to_markdown("")).to eq("| Hello | World |\n| - | - |")
+ expect(html_to_markdown("")).to eq(
+ "| Hello | World |\n| - | - |",
+ )
end
it "doesn't swallow badly formatted " do
@@ -451,5 +511,4 @@ RSpec.describe HtmlToMarkdown do
expect(html_to_markdown(html)).to eq("1 2 3 4 \nOne Two Three")
end
-
end
diff --git a/spec/lib/i18n/discourse_i18n_spec.rb b/spec/lib/i18n/discourse_i18n_spec.rb
index f0bb9f44c90..cd990834e91 100644
--- a/spec/lib/i18n/discourse_i18n_spec.rb
+++ b/spec/lib/i18n/discourse_i18n_spec.rb
@@ -1,121 +1,137 @@
# frozen_string_literal: true
-require 'i18n/backend/discourse_i18n'
-require 'translation_override'
+require "i18n/backend/discourse_i18n"
+require "translation_override"
RSpec.describe I18n::Backend::DiscourseI18n do
-
let(:backend) { I18n::Backend::DiscourseI18n.new }
before do
backend.reload!
- backend.store_translations(:en, foo: 'Foo in :en', bar: 'Bar in :en', wat: 'Hello %{count}')
- backend.store_translations(:en, items: { one: 'one item', other: '%{count} items' })
- backend.store_translations(:de, bar: 'Bar in :de')
- backend.store_translations(:en, link: '[text](url)')
+ backend.store_translations(:en, foo: "Foo in :en", bar: "Bar in :en", wat: "Hello %{count}")
+ backend.store_translations(:en, items: { one: "one item", other: "%{count} items" })
+ backend.store_translations(:de, bar: "Bar in :de")
+ backend.store_translations(:en, link: "[text](url)")
end
- after do
- backend.reload!
+ after { backend.reload! }
+
+ it "translates the basics as expected" do
+ expect(backend.translate(:en, "foo")).to eq("Foo in :en")
+ expect(backend.translate(:en, "items", count: 1)).to eq("one item")
+ expect(backend.translate(:en, "items", count: 3)).to eq("3 items")
+ expect(backend.translate(:en, "wat", count: 3)).to eq("Hello 3")
end
- it 'translates the basics as expected' do
- expect(backend.translate(:en, 'foo')).to eq('Foo in :en')
- expect(backend.translate(:en, 'items', count: 1)).to eq('one item')
- expect(backend.translate(:en, 'items', count: 3)).to eq('3 items')
- expect(backend.translate(:en, 'wat', count: 3)).to eq('Hello 3')
+ it "can be searched by key or value" do
+ expect(backend.search(:en, "fo")).to eq("foo" => "Foo in :en")
+ expect(backend.search(:en, "foo")).to eq("foo" => "Foo in :en")
+ expect(backend.search(:en, "Foo")).to eq("foo" => "Foo in :en")
+ expect(backend.search(:en, "hello")).to eq("wat" => "Hello %{count}")
+ expect(backend.search(:en, "items.one")).to eq("items.one" => "one item")
+ expect(backend.search(:en, "](")).to eq("link" => "[text](url)")
end
- it 'can be searched by key or value' do
- expect(backend.search(:en, 'fo')).to eq('foo' => 'Foo in :en')
- expect(backend.search(:en, 'foo')).to eq('foo' => 'Foo in :en')
- expect(backend.search(:en, 'Foo')).to eq('foo' => 'Foo in :en')
- expect(backend.search(:en, 'hello')).to eq('wat' => 'Hello %{count}')
- expect(backend.search(:en, 'items.one')).to eq('items.one' => 'one item')
- expect(backend.search(:en, '](')).to eq('link' => '[text](url)')
+ it "can return multiple results" do
+ results = backend.search(:en, "item")
+
+ expect(results["items.one"]).to eq("one item")
+ expect(results["items.other"]).to eq("%{count} items")
end
- it 'can return multiple results' do
- results = backend.search(:en, 'item')
-
- expect(results['items.one']).to eq('one item')
- expect(results['items.other']).to eq('%{count} items')
- end
-
- describe 'fallbacks' do
- it 'uses fallback locales for translating' do
- expect(backend.translate(:de, 'bar')).to eq('Bar in :de')
- expect(backend.translate(:de, 'foo')).to eq('Foo in :en')
+ describe "fallbacks" do
+ it "uses fallback locales for translating" do
+ expect(backend.translate(:de, "bar")).to eq("Bar in :de")
+ expect(backend.translate(:de, "foo")).to eq("Foo in :en")
end
end
- describe '#exists?' do
- it 'returns true when a key is given that exists' do
+ describe "#exists?" do
+ it "returns true when a key is given that exists" do
expect(backend.exists?(:de, :bar)).to eq(true)
end
- it 'returns true when a key is given that exists in a fallback locale of the locale' do
+ it "returns true when a key is given that exists in a fallback locale of the locale" do
expect(backend.exists?(:de, :foo)).to eq(true)
end
- it 'returns true when an existing key and an existing locale is given' do
+ it "returns true when an existing key and an existing locale is given" do
expect(backend.exists?(:en, :foo)).to eq(true)
expect(backend.exists?(:de, :bar)).to eq(true)
end
- it 'returns false when a non-existing key and an existing locale is given' do
+ it "returns false when a non-existing key and an existing locale is given" do
expect(backend.exists?(:en, :bogus)).to eq(false)
expect(backend.exists?(:de, :bogus)).to eq(false)
expect(backend.exists?(:ru, :bogus)).to eq(false)
end
- it 'returns true when a key is given which is missing from the given locale and exists in a fallback locale' do
+ it "returns true when a key is given which is missing from the given locale and exists in a fallback locale" do
expect(backend.exists?(:de, :foo)).to eq(true)
expect(backend.exists?(:ru, :foo)).to eq(true)
end
- it 'returns true when a key is given which is missing from the given locale and all its fallback locales' do
+ it "returns true when a key is given which is missing from the given locale and all its fallback locales" do
expect(backend.exists?(:de, :baz)).to eq(false)
expect(backend.exists?(:ru, :bogus)).to eq(false)
end
end
- describe '#pluralize' do
- it 'uses fallback locales when a pluralization key is missing' do
- SiteSetting.default_locale = 'ru'
+ describe "#pluralize" do
+ it "uses fallback locales when a pluralization key is missing" do
+ SiteSetting.default_locale = "ru"
- backend.store_translations(:ru, items: { one: '%{count} Russian item', many: '%{count} Russian items are many', other: '%{count} Russian items' })
+ backend.store_translations(
+ :ru,
+ items: {
+ one: "%{count} Russian item",
+ many: "%{count} Russian items are many",
+ other: "%{count} Russian items",
+ },
+ )
- expect(backend.translate(:ru, :items, count: 1)).to eq('1 Russian item')
- expect(backend.translate(:ru, :items, count: 2)).to eq('2 items')
- expect(backend.translate(:ru, :items, count: 5)).to eq('5 Russian items are many')
- expect(backend.translate(:ru, :items, count: 10.2)).to eq('10.2 Russian items')
+ expect(backend.translate(:ru, :items, count: 1)).to eq("1 Russian item")
+ expect(backend.translate(:ru, :items, count: 2)).to eq("2 items")
+ expect(backend.translate(:ru, :items, count: 5)).to eq("5 Russian items are many")
+ expect(backend.translate(:ru, :items, count: 10.2)).to eq("10.2 Russian items")
- backend.store_translations(:ru, items: { one: '%{count} Russian item', few: '%{count} Russian items are a few', many: '%{count} Russian items are many', other: '%{count} Russian items' })
- expect(backend.translate(:ru, :items, count: 2)).to eq('2 Russian items are a few')
+ backend.store_translations(
+ :ru,
+ items: {
+ one: "%{count} Russian item",
+ few: "%{count} Russian items are a few",
+ many: "%{count} Russian items are many",
+ other: "%{count} Russian items",
+ },
+ )
+ expect(backend.translate(:ru, :items, count: 2)).to eq("2 Russian items are a few")
- backend.store_translations(:en, airplanes: { one: '%{count} airplane' })
- expect(backend.translate(:ru, :airplanes, count: 1)).to eq('1 airplane')
- expect { backend.translate(:ru, :airplanes, count: 2) }.to raise_error(I18n::InvalidPluralizationData)
+ backend.store_translations(:en, airplanes: { one: "%{count} airplane" })
+ expect(backend.translate(:ru, :airplanes, count: 1)).to eq("1 airplane")
+ expect { backend.translate(:ru, :airplanes, count: 2) }.to raise_error(
+ I18n::InvalidPluralizationData,
+ )
end
end
describe ".sort_local_files" do
it "sorts an array of client ymls with '-(highest-number)' being last" do
- expect(I18n::Backend::DiscourseI18n.sort_locale_files(
- [
- 'discourse/plugins/discourse-second/config/locales/client-99.es.yml',
- 'discourse/plugins/discourse-first/config/locales/client.es.yml',
- 'discourse/plugins/discourse-third/config/locales/client-2.es.yml',
- 'discourse/plugins/discourse-third/config/locales/client-3.bs_BA.yml',
- ]
- )).to eq(
- [
- 'discourse/plugins/discourse-first/config/locales/client.es.yml',
- 'discourse/plugins/discourse-third/config/locales/client-2.es.yml',
- 'discourse/plugins/discourse-third/config/locales/client-3.bs_BA.yml',
- 'discourse/plugins/discourse-second/config/locales/client-99.es.yml',
- ]
+ expect(
+ I18n::Backend::DiscourseI18n.sort_locale_files(
+ %w[
+ discourse/plugins/discourse-second/config/locales/client-99.es.yml
+ discourse/plugins/discourse-first/config/locales/client.es.yml
+ discourse/plugins/discourse-third/config/locales/client-2.es.yml
+ discourse/plugins/discourse-third/config/locales/client-3.bs_BA.yml
+ ],
+ ),
+ ).to eq(
+ %w[
+ discourse/plugins/discourse-first/config/locales/client.es.yml
+ discourse/plugins/discourse-third/config/locales/client-2.es.yml
+ discourse/plugins/discourse-third/config/locales/client-3.bs_BA.yml
+ discourse/plugins/discourse-second/config/locales/client-99.es.yml
+ ],
)
end
end
diff --git a/spec/lib/i18n/fallback_locale_list_spec.rb b/spec/lib/i18n/fallback_locale_list_spec.rb
index 900bf370252..62471e312b0 100644
--- a/spec/lib/i18n/fallback_locale_list_spec.rb
+++ b/spec/lib/i18n/fallback_locale_list_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'i18n/backend/fallback_locale_list'
+require "i18n/backend/fallback_locale_list"
RSpec.describe I18n::Backend::FallbackLocaleList do
let(:list) { I18n::Backend::FallbackLocaleList.new }
@@ -8,25 +8,25 @@ RSpec.describe I18n::Backend::FallbackLocaleList do
it "works when default_locale is English" do
SiteSetting.default_locale = :en
- expect(list[:ru]).to eq([:ru, :en])
+ expect(list[:ru]).to eq(%i[ru en])
expect(list[:en]).to eq([:en])
end
it "works when default_locale is English (UK)" do
SiteSetting.default_locale = :en_GB
- expect(list[:ru]).to eq([:ru, :en])
- expect(list[:en_GB]).to eq([:en_GB, :en])
+ expect(list[:ru]).to eq(%i[ru en])
+ expect(list[:en_GB]).to eq(%i[en_GB en])
expect(list[:en]).to eq([:en])
end
it "works when default_locale is not English" do
SiteSetting.default_locale = :de
- expect(list[:ru]).to eq([:ru, :en])
- expect(list[:de]).to eq([:de, :en])
+ expect(list[:ru]).to eq(%i[ru en])
+ expect(list[:de]).to eq(%i[de en])
expect(list[:en]).to eq([:en])
- expect(list[:en_GB]).to eq([:en_GB, :en])
+ expect(list[:en_GB]).to eq(%i[en_GB en])
end
context "when plugin registered fallback locale" do
@@ -36,35 +36,33 @@ RSpec.describe I18n::Backend::FallbackLocaleList do
DiscoursePluginRegistry.register_locale("de_AT-formal", fallbackLocale: "de_AT")
end
- after do
- DiscoursePluginRegistry.reset!
- end
+ after { DiscoursePluginRegistry.reset! }
it "works when default_locale is English" do
SiteSetting.default_locale = :en
- expect(list[:de_AT]).to eq([:de_AT, :de, :en])
+ expect(list[:de_AT]).to eq(%i[de_AT de en])
expect(list[:"de_AT-formal"]).to eq([:"de_AT-formal", :de_AT, :de, :en])
- expect(list[:de]).to eq([:de, :en])
+ expect(list[:de]).to eq(%i[de en])
expect(list[:en]).to eq([:en])
end
it "works when default_locale is English (UK)" do
SiteSetting.default_locale = :en_GB
- expect(list[:de_AT]).to eq([:de_AT, :de, :en])
+ expect(list[:de_AT]).to eq(%i[de_AT de en])
expect(list[:"de_AT-formal"]).to eq([:"de_AT-formal", :de_AT, :de, :en])
- expect(list[:de]).to eq([:de, :en])
+ expect(list[:de]).to eq(%i[de en])
expect(list[:en]).to eq([:en])
- expect(list[:en_GB]).to eq([:en_GB, :en])
+ expect(list[:en_GB]).to eq(%i[en_GB en])
end
it "works when default_locale is not English" do
SiteSetting.default_locale = :de
- expect(list[:es_MX]).to eq([:es_MX, :es, :en])
+ expect(list[:es_MX]).to eq(%i[es_MX es en])
expect(list[:"de_AT-formal"]).to eq([:"de_AT-formal", :de_AT, :de, :en])
- expect(list[:es]).to eq([:es, :en])
+ expect(list[:es]).to eq(%i[es en])
expect(list[:en]).to eq([:en])
end
end
diff --git a/spec/lib/i18n/i18n_interpolation_keys_finder_spec.rb b/spec/lib/i18n/i18n_interpolation_keys_finder_spec.rb
index 2fd987bee52..970b223984b 100644
--- a/spec/lib/i18n/i18n_interpolation_keys_finder_spec.rb
+++ b/spec/lib/i18n/i18n_interpolation_keys_finder_spec.rb
@@ -1,10 +1,9 @@
# frozen_string_literal: true
RSpec.describe I18nInterpolationKeysFinder do
- describe '#find' do
- it 'should return the right keys' do
- expect(described_class.find('%{first} %{second} {{third}}'))
- .to eq(['first', 'second', 'third'])
+ describe "#find" do
+ it "should return the right keys" do
+ expect(described_class.find("%{first} %{second} {{third}}")).to eq(%w[first second third])
end
end
end
diff --git a/spec/lib/image_sizer_spec.rb b/spec/lib/image_sizer_spec.rb
index 483177d32f2..0e18546606b 100644
--- a/spec/lib/image_sizer_spec.rb
+++ b/spec/lib/image_sizer_spec.rb
@@ -1,73 +1,59 @@
# frozen_string_literal: true
-require 'image_sizer'
+require "image_sizer"
RSpec.describe ImageSizer do
-
before do
SiteSetting.max_image_width = 500
SiteSetting.max_image_height = 500
end
- it 'returns the same dimensions when smaller than the maximums' do
+ it "returns the same dimensions when smaller than the maximums" do
expect(ImageSizer.resize(400, 200)).to eq([400, 200])
end
- it 'returns nil if the width is nil' do
+ it "returns nil if the width is nil" do
expect(ImageSizer.resize(nil, 100)).to eq(nil)
end
- it 'returns nil if the height is nil' do
+ it "returns nil if the height is nil" do
expect(ImageSizer.resize(100, nil)).to eq(nil)
end
- it 'works with string parameters' do
- expect(ImageSizer.resize('100', '101')).to eq([100, 101])
+ it "works with string parameters" do
+ expect(ImageSizer.resize("100", "101")).to eq([100, 101])
end
- describe 'when larger than the maximum width' do
+ describe "when larger than the maximum width" do
+ before { @w, @h = ImageSizer.resize(600, 123) }
- before do
- @w, @h = ImageSizer.resize(600, 123)
- end
-
- it 'returns the maximum width if larger than the maximum' do
+ it "returns the maximum width if larger than the maximum" do
expect(@w).to eq(500)
end
- it 'resizes the height retaining the aspect ratio' do
+ it "resizes the height retaining the aspect ratio" do
expect(@h).to eq(102)
end
-
end
- describe 'when larger than the maximum height' do
+ describe "when larger than the maximum height" do
+ before { @w, @h = ImageSizer.resize(123, 600) }
- before do
- @w, @h = ImageSizer.resize(123, 600)
- end
-
- it 'returns the maximum height if larger than the maximum' do
+ it "returns the maximum height if larger than the maximum" do
expect(@h).to eq(500)
end
- it 'resizes the width retaining the aspect ratio' do
+ it "resizes the width retaining the aspect ratio" do
expect(@w).to eq(102)
end
-
end
- describe 'when larger than the maximums' do
+ describe "when larger than the maximums" do
+ before { @w, @h = ImageSizer.resize(533, 800) }
- before do
- @w, @h = ImageSizer.resize(533, 800)
- end
-
- it 'resizes both dimensions retaining the aspect ratio' do
+ it "resizes both dimensions retaining the aspect ratio" do
expect(@h).to eq(500)
expect(@w).to eq(333)
end
-
end
-
end
diff --git a/spec/lib/imap/providers/detector_spec.rb b/spec/lib/imap/providers/detector_spec.rb
index e4cac7ecdce..17b0c6cc519 100644
--- a/spec/lib/imap/providers/detector_spec.rb
+++ b/spec/lib/imap/providers/detector_spec.rb
@@ -7,7 +7,7 @@ RSpec.describe Imap::Providers::Detector do
port: 993,
ssl: true,
username: "test@gmail.com",
- password: "testpassword1"
+ password: "testpassword1",
}
expect(described_class.init_with_detected_provider(config)).to be_a(Imap::Providers::Gmail)
end
@@ -18,7 +18,7 @@ RSpec.describe Imap::Providers::Detector do
port: 993,
ssl: true,
username: "test@yo.com",
- password: "testpassword1"
+ password: "testpassword1",
}
expect(described_class.init_with_detected_provider(config)).to be_a(Imap::Providers::Generic)
end
diff --git a/spec/lib/imap/providers/generic_spec.rb b/spec/lib/imap/providers/generic_spec.rb
index 0a5a60a8b66..4d8226b40a6 100644
--- a/spec/lib/imap/providers/generic_spec.rb
+++ b/spec/lib/imap/providers/generic_spec.rb
@@ -6,26 +6,19 @@ RSpec.describe Imap::Providers::Generic do
fab!(:provider) do
described_class.new(
"imap.generic.com",
- {
- port: 993,
- ssl: true,
- username: username,
- password: password
- }
+ { port: 993, ssl: true, username: username, password: password },
)
end
let(:dummy_mailboxes) do
[
Net::IMAP::MailboxList.new([], "/", "All Mail"),
Net::IMAP::MailboxList.new([:Noselect], "/", "Other"),
- Net::IMAP::MailboxList.new([:Trash], "/", "Bin")
+ Net::IMAP::MailboxList.new([:Trash], "/", "Bin"),
]
end
let(:imap_stub) { stub }
- before do
- described_class.any_instance.stubs(:imap).returns(imap_stub)
- end
+ before { described_class.any_instance.stubs(:imap).returns(imap_stub) }
describe "#connect!" do
it "calls login with the provided username and password on the imap client" do
@@ -35,9 +28,7 @@ RSpec.describe Imap::Providers::Generic do
end
describe "#list_mailboxes" do
- before do
- imap_stub.expects(:list).with('', '*').returns(dummy_mailboxes)
- end
+ before { imap_stub.expects(:list).with("", "*").returns(dummy_mailboxes) }
it "does not return any mailboxes with the Noselect attribute" do
expect(provider.list_mailboxes).not_to include("Other")
@@ -53,9 +44,8 @@ RSpec.describe Imap::Providers::Generic do
end
describe "#trash_mailbox" do
-
before do
- imap_stub.expects(:list).with('', '*').returns(dummy_mailboxes)
+ imap_stub.expects(:list).with("", "*").returns(dummy_mailboxes)
Discourse.cache.delete("imap_trash_mailbox_#{provider.account_digest}")
end
@@ -74,55 +64,50 @@ RSpec.describe Imap::Providers::Generic do
before do
provider.stubs(:trash_mailbox).returns("Bin")
imap_stub.stubs(:examine).with("Inbox").twice
- imap_stub.stubs(:responses).returns({ 'UIDVALIDITY' => [1] })
+ imap_stub.stubs(:responses).returns({ "UIDVALIDITY" => [1] })
imap_stub.stubs(:examine).with("Bin")
- imap_stub.stubs(:responses).returns({ 'UIDVALIDITY' => [9] })
- provider.expects(:emails).with([4, 6], ['UID', 'ENVELOPE']).returns(
- [
- {
- 'ENVELOPE' => stub(message_id: ""),
- 'UID' => 4
- },
- {
- 'ENVELOPE' => stub(message_id: ""),
- 'UID' => 6
- }
- ]
- )
+ imap_stub.stubs(:responses).returns({ "UIDVALIDITY" => [9] })
+ provider
+ .expects(:emails)
+ .with([4, 6], %w[UID ENVELOPE])
+ .returns(
+ [
+ { "ENVELOPE" => stub(message_id: ""), "UID" => 4 },
+ { "ENVELOPE" => stub(message_id: ""), "UID" => 6 },
+ ],
+ )
end
- let(:message_ids) do
- [
- "h4786x34@test.com",
- "dvsfuf39@test.com",
- "f349xj84@test.com"
- ]
- end
+ let(:message_ids) { %w[h4786x34@test.com dvsfuf39@test.com f349xj84@test.com] }
it "sends the message-id search in the correct format and returns the trashed emails and UIDVALIDITY" do
provider.open_mailbox("Inbox")
- imap_stub.expects(:uid_search).with(
- "OR OR HEADER Message-ID '' HEADER Message-ID '' HEADER Message-ID ''"
-
- ).returns([4, 6])
+ imap_stub
+ .expects(:uid_search)
+ .with(
+ "OR OR HEADER Message-ID '' HEADER Message-ID '' HEADER Message-ID ''",
+ )
+ .returns([4, 6])
resp = provider.find_trashed_by_message_ids(message_ids)
- expect(resp.trashed_emails.map(&:message_id)).to match_array(['h4786x34@test.com', 'f349xj84@test.com'])
+ expect(resp.trashed_emails.map(&:message_id)).to match_array(
+ %w[h4786x34@test.com f349xj84@test.com],
+ )
expect(resp.trash_uid_validity).to eq(9)
end
end
describe "#trash" do
it "stores the \Deleted flag on the UID and expunges" do
- provider.stubs(:can?).with('MOVE').returns(false)
- provider.expects(:store).with(78, 'FLAGS', [], ['\Deleted'])
+ provider.stubs(:can?).with("MOVE").returns(false)
+ provider.expects(:store).with(78, "FLAGS", [], ['\Deleted'])
imap_stub.expects(:expunge)
provider.trash(78)
end
context "if the server supports MOVE" do
it "calls trash_move which is implemented by the provider" do
- provider.stubs(:can?).with('MOVE').returns(true)
+ provider.stubs(:can?).with("MOVE").returns(true)
provider.expects(:trash_move).with(78)
provider.trash(78)
end
@@ -154,7 +139,7 @@ RSpec.describe Imap::Providers::Generic do
describe "#open_mailbox" do
it "uses examine to get a readonly version of the mailbox" do
imap_stub.expects(:examine).with("Inbox")
- imap_stub.expects(:responses).returns({ 'UIDVALIDITY' => [1] })
+ imap_stub.expects(:responses).returns({ "UIDVALIDITY" => [1] })
provider.open_mailbox("Inbox")
end
@@ -164,7 +149,7 @@ RSpec.describe Imap::Providers::Generic do
it "raises an error" do
expect { provider.open_mailbox("Inbox", write: true) }.to raise_error(
- Imap::Providers::WriteDisabledError
+ Imap::Providers::WriteDisabledError,
)
end
end
@@ -174,7 +159,7 @@ RSpec.describe Imap::Providers::Generic do
it "does not raise an error and calls imap.select" do
imap_stub.expects(:select).with("Inbox")
- imap_stub.expects(:responses).returns({ 'UIDVALIDITY' => [1] })
+ imap_stub.expects(:responses).returns({ "UIDVALIDITY" => [1] })
expect { provider.open_mailbox("Inbox", write: true) }.not_to raise_error
end
end
@@ -182,7 +167,7 @@ RSpec.describe Imap::Providers::Generic do
end
describe "#emails" do
- let(:fields) { ['UID'] }
+ let(:fields) { ["UID"] }
let(:uids) { [99, 106] }
it "returns empty array if uid_fetch does not find any matching emails by uid" do
@@ -191,10 +176,15 @@ RSpec.describe Imap::Providers::Generic do
end
it "returns an array of attributes" do
- imap_stub.expects(:uid_fetch).with(uids, fields).returns([
- Net::IMAP::FetchData.new(1, { "UID" => 99 }),
- Net::IMAP::FetchData.new(1, { "UID" => 106 })
- ])
+ imap_stub
+ .expects(:uid_fetch)
+ .with(uids, fields)
+ .returns(
+ [
+ Net::IMAP::FetchData.new(1, { "UID" => 99 }),
+ Net::IMAP::FetchData.new(1, { "UID" => 106 }),
+ ],
+ )
expect(provider.emails(uids, fields)).to eq([{ "UID" => 99 }, { "UID" => 106 }])
end
end
diff --git a/spec/lib/imap/providers/gmail_spec.rb b/spec/lib/imap/providers/gmail_spec.rb
index bdf049acf4d..9ce1f9dad2a 100644
--- a/spec/lib/imap/providers/gmail_spec.rb
+++ b/spec/lib/imap/providers/gmail_spec.rb
@@ -1,4 +1,3 @@
-
# frozen_string_literal: true
RSpec.describe Imap::Providers::Gmail do
@@ -7,27 +6,21 @@ RSpec.describe Imap::Providers::Gmail do
fab!(:provider) do
described_class.new(
"imap.generic.com",
- {
- port: 993,
- ssl: true,
- username: username,
- password: password
- }
+ { port: 993, ssl: true, username: username, password: password },
)
end
let(:imap_stub) { stub }
let(:x_gm_thrid) { Imap::Providers::Gmail::X_GM_THRID }
let(:x_gm_labels) { Imap::Providers::Gmail::X_GM_LABELS }
- before do
- described_class.any_instance.stubs(:imap).returns(imap_stub)
- end
+ before { described_class.any_instance.stubs(:imap).returns(imap_stub) }
describe "#store" do
it "converts LABELS store to special X-GM-LABELS" do
- Imap::Providers::Generic.any_instance.expects(:store).with(
- 63, x_gm_labels, ["\\Inbox"], ["\\Inbox", "test"]
- )
+ Imap::Providers::Generic
+ .any_instance
+ .expects(:store)
+ .with(63, x_gm_labels, ["\\Inbox"], ["\\Inbox", "test"])
provider.store(63, "LABELS", ["\\Inbox"], ["\\Inbox", "test"])
end
end
@@ -45,23 +38,21 @@ RSpec.describe Imap::Providers::Gmail do
describe "#archive" do
it "gets the thread ID for the UID, and removes the Inbox label from all UIDs in the thread" do
main_uid = 78
- fake_thrid = '4398634986239754'
- imap_stub.expects(:uid_fetch).with(main_uid, [x_gm_thrid]).returns(
- [stub(attr: { x_gm_thrid => fake_thrid })]
- )
+ fake_thrid = "4398634986239754"
+ imap_stub
+ .expects(:uid_fetch)
+ .with(main_uid, [x_gm_thrid])
+ .returns([stub(attr: { x_gm_thrid => fake_thrid })])
imap_stub.expects(:uid_search).with("#{x_gm_thrid} #{fake_thrid}").returns([79, 80])
- provider.expects(:emails).with([79, 80], ["UID", "LABELS"]).returns(
- [
- {
- "UID" => 79,
- "LABELS" => ["\\Inbox", "seen"]
- },
- {
- "UID" => 80,
- "LABELS" => ["\\Inbox", "seen"]
- }
- ]
- )
+ provider
+ .expects(:emails)
+ .with([79, 80], %w[UID LABELS])
+ .returns(
+ [
+ { "UID" => 79, "LABELS" => ["\\Inbox", "seen"] },
+ { "UID" => 80, "LABELS" => ["\\Inbox", "seen"] },
+ ],
+ )
provider.expects(:store).with(79, "LABELS", ["\\Inbox", "seen"], ["seen"])
provider.expects(:store).with(80, "LABELS", ["\\Inbox", "seen"], ["seen"])
@@ -73,18 +64,18 @@ RSpec.describe Imap::Providers::Gmail do
it "filters down the gmail mailboxes to only show the relevant ones" do
mailboxes_with_attr = [
Net::IMAP::MailboxList.new([:Hasnochildren], "/", "INBOX"),
- Net::IMAP::MailboxList.new([:All, :Hasnochildren], "/", "[Gmail]/All Mail"),
- Net::IMAP::MailboxList.new([:Drafts, :Hasnochildren], "/", "[Gmail]/Drafts"),
- Net::IMAP::MailboxList.new([:Hasnochildren, :Important], "/", "[Gmail]/Important"),
- Net::IMAP::MailboxList.new([:Hasnochildren, :Sent], "/", "[Gmail]/Sent Mail"),
- Net::IMAP::MailboxList.new([:Hasnochildren, :Junk], "/", "[Gmail]/Spam"),
- Net::IMAP::MailboxList.new([:Flagged, :Hasnochildren], "/", "[Gmail]/Starred"),
- Net::IMAP::MailboxList.new([:Hasnochildren, :Trash], "/", "[Gmail]/Trash")
+ Net::IMAP::MailboxList.new(%i[All Hasnochildren], "/", "[Gmail]/All Mail"),
+ Net::IMAP::MailboxList.new(%i[Drafts Hasnochildren], "/", "[Gmail]/Drafts"),
+ Net::IMAP::MailboxList.new(%i[Hasnochildren Important], "/", "[Gmail]/Important"),
+ Net::IMAP::MailboxList.new(%i[Hasnochildren Sent], "/", "[Gmail]/Sent Mail"),
+ Net::IMAP::MailboxList.new(%i[Hasnochildren Junk], "/", "[Gmail]/Spam"),
+ Net::IMAP::MailboxList.new(%i[Flagged Hasnochildren], "/", "[Gmail]/Starred"),
+ Net::IMAP::MailboxList.new(%i[Hasnochildren Trash], "/", "[Gmail]/Trash"),
]
- expect(provider.filter_mailboxes(mailboxes_with_attr)).to match_array([
- "INBOX", "[Gmail]/All Mail", "[Gmail]/Important"
- ])
+ expect(provider.filter_mailboxes(mailboxes_with_attr)).to match_array(
+ ["INBOX", "[Gmail]/All Mail", "[Gmail]/Important"],
+ )
end
end
end
diff --git a/spec/lib/imap/sync_spec.rb b/spec/lib/imap/sync_spec.rb
index e68ba4a6818..991ab4c38f4 100644
--- a/spec/lib/imap/sync_spec.rb
+++ b/spec/lib/imap/sync_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'imap/sync'
+require "imap/sync"
RSpec.describe Imap::Sync do
before do
@@ -15,32 +15,31 @@ RSpec.describe Imap::Sync do
let(:group) do
Fabricate(
:group,
- imap_server: 'imap.gmail.com',
+ imap_server: "imap.gmail.com",
imap_port: 993,
- email_username: 'groupemailusername@example.com',
- email_password: 'password',
- imap_mailbox_name: '[Gmail]/All Mail'
+ email_username: "groupemailusername@example.com",
+ email_password: "password",
+ imap_mailbox_name: "[Gmail]/All Mail",
)
end
let(:sync_handler) { Imap::Sync.new(group) }
before do
- mocked_imap_provider = MockedImapProvider.new(
- group.imap_server,
- port: group.imap_port,
- ssl: group.imap_ssl,
- username: group.email_username,
- password: group.email_password
- )
- Imap::Providers::Detector.stubs(:init_with_detected_provider).returns(
- mocked_imap_provider
- )
+ mocked_imap_provider =
+ MockedImapProvider.new(
+ group.imap_server,
+ port: group.imap_port,
+ ssl: group.imap_ssl,
+ username: group.email_username,
+ password: group.email_password,
+ )
+ Imap::Providers::Detector.stubs(:init_with_detected_provider).returns(mocked_imap_provider)
end
- describe 'no previous sync' do
- let(:from) { 'john@free.fr' }
- let(:subject) { 'Testing email post' }
+ describe "no previous sync" do
+ let(:from) { "john@free.fr" }
+ let(:subject) { "Testing email post" }
let(:message_id) { "#{SecureRandom.hex}@example.com" }
let(:email) do
@@ -48,7 +47,8 @@ RSpec.describe Imap::Sync do
from: from,
to: group.email_username,
subject: subject,
- message_id: message_id)
+ message_id: message_id,
+ )
end
before do
@@ -60,20 +60,19 @@ RSpec.describe Imap::Sync do
provider.stubs(:emails).returns(
[
{
- 'UID' => 100,
- 'LABELS' => %w[\\Important test-label],
- 'FLAGS' => %i[Seen],
- 'RFC822' => email
- }
- ]
+ "UID" => 100,
+ "LABELS" => %w[\\Important test-label],
+ "FLAGS" => %i[Seen],
+ "RFC822" => email,
+ },
+ ],
)
end
- it 'creates a topic from an incoming email' do
- expect { sync_handler.process }
- .to change { Topic.count }.by(1)
- .and change { Post.where(post_type: Post.types[:regular]).count }.by(1)
- .and change { IncomingEmail.count }.by(1)
+ it "creates a topic from an incoming email" do
+ expect { sync_handler.process }.to change { Topic.count }.by(1).and change {
+ Post.where(post_type: Post.types[:regular]).count
+ }.by(1).and change { IncomingEmail.count }.by(1)
expect(IncomingEmail.last.created_via).to eq(IncomingEmail.created_via_types[:imap])
@@ -86,7 +85,7 @@ RSpec.describe Imap::Sync do
expect(topic.tags.pluck(:name)).to contain_exactly("seen", "important", "test-label")
post = topic.first_post
- expect(post.raw).to eq('This is an email *body*. :smile:')
+ expect(post.raw).to eq("This is an email *body*. :smile:")
incoming_email = post.incoming_email
expect(incoming_email.raw.lines.map(&:strip)).to eq(email.lines.map(&:strip))
@@ -100,15 +99,12 @@ RSpec.describe Imap::Sync do
end
context "when tagging not enabled" do
- before do
- SiteSetting.tagging_enabled = false
- end
+ before { SiteSetting.tagging_enabled = false }
it "creates a topic from an incoming email but with no tags added" do
- expect { sync_handler.process }
- .to change { Topic.count }.by(1)
- .and change { Post.where(post_type: Post.types[:regular]).count }.by(1)
- .and change { IncomingEmail.count }.by(1)
+ expect { sync_handler.process }.to change { Topic.count }.by(1).and change {
+ Post.where(post_type: Post.types[:regular]).count
+ }.by(1).and change { IncomingEmail.count }.by(1)
expect(group.imap_uid_validity).to eq(1)
expect(group.imap_last_uid).to eq(100)
@@ -120,25 +116,22 @@ RSpec.describe Imap::Sync do
end
end
- it 'does not duplicate topics' do
- expect { sync_handler.process }
- .to change { Topic.count }.by(1)
- .and change { Post.where(post_type: Post.types[:regular]).count }.by(1)
- .and change { IncomingEmail.count }.by(1)
+ it "does not duplicate topics" do
+ expect { sync_handler.process }.to change { Topic.count }.by(1).and change {
+ Post.where(post_type: Post.types[:regular]).count
+ }.by(1).and change { IncomingEmail.count }.by(1)
- expect { sync_handler.process }
- .to not_change { Topic.count }
- .and not_change { Post.where(post_type: Post.types[:regular]).count }
- .and not_change { IncomingEmail.count }
+ expect { sync_handler.process }.to not_change { Topic.count }.and not_change {
+ Post.where(post_type: Post.types[:regular]).count
+ }.and not_change { IncomingEmail.count }
end
- it 'creates a new incoming email if the message ID does not match the receiver post id regex' do
+ it "creates a new incoming email if the message ID does not match the receiver post id regex" do
incoming_email = Fabricate(:incoming_email, message_id: message_id)
- expect { sync_handler.process }
- .to change { Topic.count }.by(1)
- .and change { Post.where(post_type: Post.types[:regular]).count }.by(1)
- .and change { IncomingEmail.count }.by(1)
+ expect { sync_handler.process }.to change { Topic.count }.by(1).and change {
+ Post.where(post_type: Post.types[:regular]).count
+ }.by(1).and change { IncomingEmail.count }.by(1)
last_incoming = IncomingEmail.where(message_id: message_id).last
expect(last_incoming.message_id).to eq(message_id)
@@ -150,13 +143,12 @@ RSpec.describe Imap::Sync do
context "when the message id matches the receiver post id regex" do
let(:message_id) { "topic/999/324@test.localhost" }
- it 'does not duplicate incoming email' do
+ it "does not duplicate incoming email" do
incoming_email = Fabricate(:incoming_email, message_id: message_id)
- expect { sync_handler.process }
- .to not_change { Topic.count }
- .and not_change { Post.where(post_type: Post.types[:regular]).count }
- .and not_change { IncomingEmail.count }
+ expect { sync_handler.process }.to not_change { Topic.count }.and not_change {
+ Post.where(post_type: Post.types[:regular]).count
+ }.and not_change { IncomingEmail.count }
incoming_email.reload
expect(incoming_email.message_id).to eq(message_id)
@@ -168,44 +160,47 @@ RSpec.describe Imap::Sync do
end
end
- describe 'previous sync' do
- let(:subject) { 'Testing email post' }
+ describe "previous sync" do
+ let(:subject) { "Testing email post" }
- let(:first_from) { 'john@free.fr' }
+ let(:first_from) { "john@free.fr" }
let(:first_message_id) { SecureRandom.hex }
- let(:first_body) { 'This is the first message of this exchange.' }
+ let(:first_body) { "This is the first message of this exchange." }
- let(:second_from) { 'sam@free.fr' }
+ let(:second_from) { "sam@free.fr" }
let(:second_message_id) { SecureRandom.hex }
- let(:second_body) { 'This is an answer to this message.
' }
+ let(:second_body) { "This is an answer to this message.
" }
- it 'continues with new emails' do
+ it "continues with new emails" do
provider = MockedImapProvider.any_instance
provider.stubs(:open_mailbox).returns(uid_validity: 1)
provider.stubs(:uids).with.returns([100])
- provider.stubs(:emails).with([100], ['UID', 'FLAGS', 'LABELS', 'RFC822'], anything).returns(
- [
- {
- 'UID' => 100,
- 'LABELS' => %w[\\Inbox],
- 'FLAGS' => %i[Seen],
- 'RFC822' => EmailFabricator(
- message_id: first_message_id,
- from: first_from,
- to: group.email_username,
- cc: second_from,
- subject: subject,
- body: first_body
- )
- }
- ]
- )
+ provider
+ .stubs(:emails)
+ .with([100], %w[UID FLAGS LABELS RFC822], anything)
+ .returns(
+ [
+ {
+ "UID" => 100,
+ "LABELS" => %w[\\Inbox],
+ "FLAGS" => %i[Seen],
+ "RFC822" =>
+ EmailFabricator(
+ message_id: first_message_id,
+ from: first_from,
+ to: group.email_username,
+ cc: second_from,
+ subject: subject,
+ body: first_body,
+ ),
+ },
+ ],
+ )
- expect { sync_handler.process }
- .to change { Topic.count }.by(1)
- .and change { Post.where(post_type: Post.types[:regular]).count }.by(1)
- .and change { IncomingEmail.count }.by(1)
+ expect { sync_handler.process }.to change { Topic.count }.by(1).and change {
+ Post.where(post_type: Post.types[:regular]).count
+ }.by(1).and change { IncomingEmail.count }.by(1)
topic = Topic.last
expect(topic.title).to eq(subject)
@@ -219,37 +214,35 @@ RSpec.describe Imap::Sync do
provider.stubs(:uids).with(to: 100).returns([100])
provider.stubs(:uids).with(from: 101).returns([200])
- provider.stubs(:emails).with([100], ['UID', 'FLAGS', 'LABELS', 'ENVELOPE'], anything).returns(
- [
- {
- 'UID' => 100,
- 'LABELS' => %w[\\Inbox],
- 'FLAGS' => %i[Seen]
- }
- ]
- )
- provider.stubs(:emails).with([200], ['UID', 'FLAGS', 'LABELS', 'RFC822'], anything).returns(
- [
- {
- 'UID' => 200,
- 'LABELS' => %w[\\Inbox],
- 'FLAGS' => %i[Recent],
- 'RFC822' => EmailFabricator(
- message_id: SecureRandom.hex,
- in_reply_to: first_message_id,
- from: second_from,
- to: group.email_username,
- subject: "Re: #{subject}",
- body: second_body
- )
- }
- ]
- )
+ provider
+ .stubs(:emails)
+ .with([100], %w[UID FLAGS LABELS ENVELOPE], anything)
+ .returns([{ "UID" => 100, "LABELS" => %w[\\Inbox], "FLAGS" => %i[Seen] }])
+ provider
+ .stubs(:emails)
+ .with([200], %w[UID FLAGS LABELS RFC822], anything)
+ .returns(
+ [
+ {
+ "UID" => 200,
+ "LABELS" => %w[\\Inbox],
+ "FLAGS" => %i[Recent],
+ "RFC822" =>
+ EmailFabricator(
+ message_id: SecureRandom.hex,
+ in_reply_to: first_message_id,
+ from: second_from,
+ to: group.email_username,
+ subject: "Re: #{subject}",
+ body: second_body,
+ ),
+ },
+ ],
+ )
- expect { sync_handler.process }
- .to not_change { Topic.count }
- .and change { Post.where(post_type: Post.types[:regular]).count }.by(1)
- .and change { IncomingEmail.count }.by(1)
+ expect { sync_handler.process }.to not_change { Topic.count }.and change {
+ Post.where(post_type: Post.types[:regular]).count
+ }.by(1).and change { IncomingEmail.count }.by(1)
post = Post.where(post_type: Post.types[:regular]).last
expect(post.user.email).to eq(second_from)
@@ -259,25 +252,19 @@ RSpec.describe Imap::Sync do
provider.stubs(:uids).with(to: 200).returns([100, 200])
provider.stubs(:uids).with(from: 201).returns([])
- provider.stubs(:emails).with([100, 200], ['UID', 'FLAGS', 'LABELS', 'ENVELOPE'], anything).returns(
- [
- {
- 'UID' => 100,
- 'LABELS' => %w[],
- 'FLAGS' => %i[Seen]
- },
- {
- 'UID' => 200,
- 'LABELS' => %w[],
- 'FLAGS' => %i[Recent],
- }
- ]
- )
+ provider
+ .stubs(:emails)
+ .with([100, 200], %w[UID FLAGS LABELS ENVELOPE], anything)
+ .returns(
+ [
+ { "UID" => 100, "LABELS" => %w[], "FLAGS" => %i[Seen] },
+ { "UID" => 200, "LABELS" => %w[], "FLAGS" => %i[Recent] },
+ ],
+ )
- expect { sync_handler.process }
- .to not_change { Topic.count }
- .and not_change { Post.where(post_type: Post.types[:regular]).count }
- .and not_change { IncomingEmail.count }
+ expect { sync_handler.process }.to not_change { Topic.count }.and not_change {
+ Post.where(post_type: Post.types[:regular]).count
+ }.and not_change { IncomingEmail.count }
topic = Topic.last
expect(topic.title).to eq(subject)
@@ -292,24 +279,27 @@ RSpec.describe Imap::Sync do
provider.stubs(:open_mailbox).returns(uid_validity: 1)
provider.stubs(:uids).with.returns([100])
- provider.stubs(:emails).with([100], ['UID', 'FLAGS', 'LABELS', 'RFC822'], anything).returns(
- [
- {
- 'UID' => 100,
- 'LABELS' => %w[\\Inbox],
- 'FLAGS' => %i[Seen],
- 'RFC822' => EmailFabricator(
- message_id: first_message_id,
- from: first_from,
- to: group.email_username,
- cc: second_from,
- subject: subject,
- body: first_body
- )
- }
- ]
- )
-
+ provider
+ .stubs(:emails)
+ .with([100], %w[UID FLAGS LABELS RFC822], anything)
+ .returns(
+ [
+ {
+ "UID" => 100,
+ "LABELS" => %w[\\Inbox],
+ "FLAGS" => %i[Seen],
+ "RFC822" =>
+ EmailFabricator(
+ message_id: first_message_id,
+ from: first_from,
+ to: group.email_username,
+ cc: second_from,
+ subject: subject,
+ body: first_body,
+ ),
+ },
+ ],
+ )
end
it "detects previously synced UIDs are missing and deletes the posts if they are in the trash mailbox" do
@@ -322,14 +312,9 @@ RSpec.describe Imap::Sync do
provider.stubs(:find_spam_by_message_ids).returns(stub(spam_emails: []))
provider.stubs(:find_trashed_by_message_ids).returns(
stub(
- trashed_emails: [
- stub(
- uid: 10,
- message_id: incoming_100.message_id
- )
- ],
- trash_uid_validity: 99
- )
+ trashed_emails: [stub(uid: 10, message_id: incoming_100.message_id)],
+ trash_uid_validity: 99,
+ ),
)
sync_handler.process
@@ -350,14 +335,9 @@ RSpec.describe Imap::Sync do
provider.stubs(:find_trashed_by_message_ids).returns(stub(trashed_emails: []))
provider.stubs(:find_spam_by_message_ids).returns(
stub(
- spam_emails: [
- stub(
- uid: 10,
- message_id: incoming_100.message_id
- )
- ],
- spam_uid_validity: 99
- )
+ spam_emails: [stub(uid: 10, message_id: incoming_100.message_id)],
+ spam_uid_validity: 99,
+ ),
)
sync_handler.process
@@ -394,31 +374,31 @@ RSpec.describe Imap::Sync do
provider.stubs(:uids).with(from: 101).returns([])
PostDestroyer.new(Discourse.system_user, incoming_100.post).destroy
- provider.stubs(:emails).with([100], ['UID', 'FLAGS', 'LABELS', 'ENVELOPE'], anything).returns(
- [
- {
- 'UID' => 100,
- 'LABELS' => %w[\\Inbox],
- 'FLAGS' => %i[Seen],
- 'RFC822' => EmailFabricator(
- message_id: first_message_id,
- from: first_from,
- to: group.email_username,
- cc: second_from,
- subject: subject,
- body: first_body
- )
- }
- ]
- )
- provider.stubs(:emails).with(100, ['FLAGS', 'LABELS']).returns(
- [
- {
- 'LABELS' => %w[\\Inbox],
- 'FLAGS' => %i[Seen]
- }
- ]
- )
+ provider
+ .stubs(:emails)
+ .with([100], %w[UID FLAGS LABELS ENVELOPE], anything)
+ .returns(
+ [
+ {
+ "UID" => 100,
+ "LABELS" => %w[\\Inbox],
+ "FLAGS" => %i[Seen],
+ "RFC822" =>
+ EmailFabricator(
+ message_id: first_message_id,
+ from: first_from,
+ to: group.email_username,
+ cc: second_from,
+ subject: subject,
+ body: first_body,
+ ),
+ },
+ ],
+ )
+ provider
+ .stubs(:emails)
+ .with(100, %w[FLAGS LABELS])
+ .returns([{ "LABELS" => %w[\\Inbox], "FLAGS" => %i[Seen] }])
provider.expects(:trash).with(100)
sync_handler.process
@@ -430,14 +410,9 @@ RSpec.describe Imap::Sync do
provider.stubs(:find_spam_by_message_ids).returns(stub(spam_emails: []))
provider.stubs(:find_trashed_by_message_ids).returns(
stub(
- trashed_emails: [
- stub(
- uid: 10,
- message_id: incoming_100.message_id
- )
- ],
- trash_uid_validity: 99
- )
+ trashed_emails: [stub(uid: 10, message_id: incoming_100.message_id)],
+ trash_uid_validity: 99,
+ ),
)
PostDestroyer.expects(:new).never
@@ -456,23 +431,27 @@ RSpec.describe Imap::Sync do
provider.stubs(:open_mailbox).returns(uid_validity: 1)
provider.stubs(:uids).with.returns([100])
- provider.stubs(:emails).with([100], ['UID', 'FLAGS', 'LABELS', 'RFC822'], anything).returns(
- [
- {
- 'UID' => 100,
- 'LABELS' => %w[\\Inbox],
- 'FLAGS' => %i[Seen],
- 'RFC822' => EmailFabricator(
- message_id: first_message_id,
- from: first_from,
- to: group.email_username,
- cc: second_from,
- subject: subject,
- body: first_body
- )
- }
- ]
- )
+ provider
+ .stubs(:emails)
+ .with([100], %w[UID FLAGS LABELS RFC822], anything)
+ .returns(
+ [
+ {
+ "UID" => 100,
+ "LABELS" => %w[\\Inbox],
+ "FLAGS" => %i[Seen],
+ "RFC822" =>
+ EmailFabricator(
+ message_id: first_message_id,
+ from: first_from,
+ to: group.email_username,
+ cc: second_from,
+ subject: subject,
+ body: first_body,
+ ),
+ },
+ ],
+ )
sync_handler.process
@incoming_email = IncomingEmail.find_by(message_id: first_message_id)
@@ -480,34 +459,23 @@ RSpec.describe Imap::Sync do
provider.stubs(:uids).with(to: 100).returns([100])
provider.stubs(:uids).with(from: 101).returns([101])
- provider.stubs(:emails).with([100], ['UID', 'FLAGS', 'LABELS', 'ENVELOPE'], anything).returns(
- [
- {
- 'UID' => 100,
- 'LABELS' => %w[\\Inbox],
- 'FLAGS' => %i[Seen]
- }
- ]
- )
- provider.stubs(:emails).with([101], ['UID', 'FLAGS', 'LABELS', 'RFC822'], anything).returns(
- []
- )
- provider.stubs(:emails).with(100, ['FLAGS', 'LABELS']).returns(
- [
- {
- 'LABELS' => %w[\\Inbox],
- 'FLAGS' => %i[Seen]
- }
- ]
- )
+ provider
+ .stubs(:emails)
+ .with([100], %w[UID FLAGS LABELS ENVELOPE], anything)
+ .returns([{ "UID" => 100, "LABELS" => %w[\\Inbox], "FLAGS" => %i[Seen] }])
+ provider.stubs(:emails).with([101], %w[UID FLAGS LABELS RFC822], anything).returns([])
+ provider
+ .stubs(:emails)
+ .with(100, %w[FLAGS LABELS])
+ .returns([{ "LABELS" => %w[\\Inbox], "FLAGS" => %i[Seen] }])
end
it "archives an email on the IMAP server when archived in discourse" do
GroupArchivedMessage.archive!(group.id, @topic, skip_imap_sync: false)
@incoming_email.update(imap_sync: true)
- provider.stubs(:store).with(100, 'FLAGS', anything, anything)
- provider.stubs(:store).with(100, 'LABELS', ["\\Inbox"], ["seen"])
+ provider.stubs(:store).with(100, "FLAGS", anything, anything)
+ provider.stubs(:store).with(100, "LABELS", ["\\Inbox"], ["seen"])
provider.expects(:archive).with(100)
sync_handler.process
@@ -515,111 +483,118 @@ RSpec.describe Imap::Sync do
it "does not archive email if not archived in discourse, it unarchives it instead" do
@incoming_email.update(imap_sync: true)
- provider.stubs(:store).with(100, 'FLAGS', anything, anything)
- provider.stubs(:store).with(100, 'LABELS', ["\\Inbox"], ["\\Inbox", "seen"])
+ provider.stubs(:store).with(100, "FLAGS", anything, anything)
+ provider.stubs(:store).with(100, "LABELS", ["\\Inbox"], ["\\Inbox", "seen"])
provider.expects(:archive).with(100).never
provider.expects(:unarchive).with(100)
sync_handler.process
end
end
-
end
- describe 'invalidated previous sync' do
- let(:subject) { 'Testing email post' }
+ describe "invalidated previous sync" do
+ let(:subject) { "Testing email post" }
- let(:first_from) { 'john@free.fr' }
+ let(:first_from) { "john@free.fr" }
let(:first_message_id) { SecureRandom.hex }
- let(:first_body) { 'This is the first message of this exchange.' }
+ let(:first_body) { "This is the first message of this exchange." }
- let(:second_from) { 'sam@free.fr' }
+ let(:second_from) { "sam@free.fr" }
let(:second_message_id) { SecureRandom.hex }
- let(:second_body) { 'This is an answer to this message.
' }
+ let(:second_body) { "This is an answer to this message.
" }
# TODO: Improve the invalidating flow for mailbox change. This is a destructive
# action so it should not be done often.
- xit 'is updated' do
+ xit "is updated" do
provider = MockedImapProvider.any_instance
provider.stubs(:open_mailbox).returns(uid_validity: 1)
provider.stubs(:uids).with.returns([100, 200])
- provider.stubs(:emails).with([100, 200], ['UID', 'FLAGS', 'LABELS', 'RFC822'], anything).returns(
- [
- {
- 'UID' => 100,
- 'LABELS' => %w[\\Inbox],
- 'FLAGS' => %i[Seen],
- 'RFC822' => EmailFabricator(
- message_id: first_message_id,
- from: first_from,
- to: group.email_username,
- cc: second_from,
- subject: subject,
- body: first_body
- )
- },
- {
- 'UID' => 200,
- 'LABELS' => %w[\\Inbox],
- 'FLAGS' => %i[Recent],
- 'RFC822' => EmailFabricator(
- message_id: second_message_id,
- in_reply_to: first_message_id,
- from: second_from,
- to: group.email_username,
- subject: "Re: #{subject}",
- body: second_body
- )
- }
- ]
- )
+ provider
+ .stubs(:emails)
+ .with([100, 200], %w[UID FLAGS LABELS RFC822], anything)
+ .returns(
+ [
+ {
+ "UID" => 100,
+ "LABELS" => %w[\\Inbox],
+ "FLAGS" => %i[Seen],
+ "RFC822" =>
+ EmailFabricator(
+ message_id: first_message_id,
+ from: first_from,
+ to: group.email_username,
+ cc: second_from,
+ subject: subject,
+ body: first_body,
+ ),
+ },
+ {
+ "UID" => 200,
+ "LABELS" => %w[\\Inbox],
+ "FLAGS" => %i[Recent],
+ "RFC822" =>
+ EmailFabricator(
+ message_id: second_message_id,
+ in_reply_to: first_message_id,
+ from: second_from,
+ to: group.email_username,
+ subject: "Re: #{subject}",
+ body: second_body,
+ ),
+ },
+ ],
+ )
- expect { sync_handler.process }
- .to change { Topic.count }.by(1)
- .and change { Post.where(post_type: Post.types[:regular]).count }.by(2)
- .and change { IncomingEmail.count }.by(2)
+ expect { sync_handler.process }.to change { Topic.count }.by(1).and change {
+ Post.where(post_type: Post.types[:regular]).count
+ }.by(2).and change { IncomingEmail.count }.by(2)
imap_data = Topic.last.incoming_email.pluck(:imap_uid_validity, :imap_uid, :imap_group_id)
expect(imap_data).to contain_exactly([1, 100, group.id], [1, 200, group.id])
provider.stubs(:open_mailbox).returns(uid_validity: 2)
provider.stubs(:uids).with.returns([111, 222])
- provider.stubs(:emails).with([111, 222], ['UID', 'FLAGS', 'LABELS', 'RFC822'], anything).returns(
- [
- {
- 'UID' => 111,
- 'LABELS' => %w[\\Inbox],
- 'FLAGS' => %i[Seen],
- 'RFC822' => EmailFabricator(
- message_id: first_message_id,
- from: first_from,
- to: group.email_username,
- cc: second_from,
- subject: subject,
- body: first_body
- )
- },
- {
- 'UID' => 222,
- 'LABELS' => %w[\\Inbox],
- 'FLAGS' => %i[Recent],
- 'RFC822' => EmailFabricator(
- message_id: second_message_id,
- in_reply_to: first_message_id,
- from: second_from,
- to: group.email_username,
- subject: "Re: #{subject}",
- body: second_body
- )
- }
- ]
- )
+ provider
+ .stubs(:emails)
+ .with([111, 222], %w[UID FLAGS LABELS RFC822], anything)
+ .returns(
+ [
+ {
+ "UID" => 111,
+ "LABELS" => %w[\\Inbox],
+ "FLAGS" => %i[Seen],
+ "RFC822" =>
+ EmailFabricator(
+ message_id: first_message_id,
+ from: first_from,
+ to: group.email_username,
+ cc: second_from,
+ subject: subject,
+ body: first_body,
+ ),
+ },
+ {
+ "UID" => 222,
+ "LABELS" => %w[\\Inbox],
+ "FLAGS" => %i[Recent],
+ "RFC822" =>
+ EmailFabricator(
+ message_id: second_message_id,
+ in_reply_to: first_message_id,
+ from: second_from,
+ to: group.email_username,
+ subject: "Re: #{subject}",
+ body: second_body,
+ ),
+ },
+ ],
+ )
- expect { sync_handler.process }
- .to not_change { Topic.count }
- .and not_change { Post.where(post_type: Post.types[:regular]).count }
- .and not_change { IncomingEmail.count }
+ expect { sync_handler.process }.to not_change { Topic.count }.and not_change {
+ Post.where(post_type: Post.types[:regular]).count
+ }.and not_change { IncomingEmail.count }
imap_data = Topic.last.incoming_email.pluck(:imap_uid_validity, :imap_uid, :imap_group_id)
expect(imap_data).to contain_exactly([2, 111, group.id], [2, 222, group.id])
diff --git a/spec/lib/import/normalize_spec.rb b/spec/lib/import/normalize_spec.rb
index 77b483fa580..0fd7e384c5f 100644
--- a/spec/lib/import/normalize_spec.rb
+++ b/spec/lib/import/normalize_spec.rb
@@ -12,7 +12,8 @@ RSpec.describe Import::Normalize do
test
this is a ""
MD
- expected = " \n \n```\n I am a te \"\n \n```\n\n test \n \n```\nthis is a \"\"\n```\n\n"
+ expected =
+ " \n \n```\n I am a te \"\n \n```\n\n test \n \n```\nthis is a \"\"\n```\n\n"
expect(Import::Normalize.normalize_code_blocks(markdown)).to eq(expected)
end
end
diff --git a/spec/lib/inline_oneboxer_spec.rb b/spec/lib/inline_oneboxer_spec.rb
index 18acb78f5e3..ab27dd4589d 100644
--- a/spec/lib/inline_oneboxer_spec.rb
+++ b/spec/lib/inline_oneboxer_spec.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
RSpec.describe InlineOneboxer do
-
it "should return nothing with empty input" do
expect(InlineOneboxer.new([]).process).to be_blank
end
@@ -23,14 +22,15 @@ RSpec.describe InlineOneboxer do
describe "caching" do
fab!(:topic) { Fabricate(:topic) }
- before do
- InlineOneboxer.invalidate(topic.url)
- end
+ before { InlineOneboxer.invalidate(topic.url) }
it "puts an entry in the cache" do
SiteSetting.enable_inline_onebox_on_all_domains = true
url = "https://example.com/good-url"
- stub_request(:get, url).to_return(status: 200, body: "a blog ")
+ stub_request(:get, url).to_return(
+ status: 200,
+ body: "a blog ",
+ )
InlineOneboxer.invalidate(url)
expect(InlineOneboxer.cache_lookup(url)).to be_blank
@@ -40,7 +40,7 @@ RSpec.describe InlineOneboxer do
cached = InlineOneboxer.cache_lookup(url)
expect(cached[:url]).to eq(url)
- expect(cached[:title]).to eq('a blog')
+ expect(cached[:title]).to eq("a blog")
end
end
@@ -56,25 +56,52 @@ RSpec.describe InlineOneboxer do
topic2 = Fabricate(:topic, category: category2)
# Link to `topic` from new topic (same category)
- onebox = InlineOneboxer.lookup(topic.url, user_id: admin.id, category_id: category.id, skip_cache: true)
+ onebox =
+ InlineOneboxer.lookup(
+ topic.url,
+ user_id: admin.id,
+ category_id: category.id,
+ skip_cache: true,
+ )
expect(onebox).to be_present
expect(onebox[:url]).to eq(topic.url)
expect(onebox[:title]).to eq(topic.title)
# Link to `topic` from `topic`
- onebox = InlineOneboxer.lookup(topic.url, user_id: admin.id, category_id: topic.category_id, topic_id: topic.id, skip_cache: true)
+ onebox =
+ InlineOneboxer.lookup(
+ topic.url,
+ user_id: admin.id,
+ category_id: topic.category_id,
+ topic_id: topic.id,
+ skip_cache: true,
+ )
expect(onebox).to be_present
expect(onebox[:url]).to eq(topic.url)
expect(onebox[:title]).to eq(topic.title)
# Link to `topic` from `topic1` (same category)
- onebox = InlineOneboxer.lookup(topic.url, user_id: admin.id, category_id: topic1.category_id, topic_id: topic1.id, skip_cache: true)
+ onebox =
+ InlineOneboxer.lookup(
+ topic.url,
+ user_id: admin.id,
+ category_id: topic1.category_id,
+ topic_id: topic1.id,
+ skip_cache: true,
+ )
expect(onebox).to be_present
expect(onebox[:url]).to eq(topic.url)
expect(onebox[:title]).to eq(topic.title)
# Link to `topic` from `topic2` (different category)
- onebox = InlineOneboxer.lookup(topic.url, user_id: admin.id, category_id: topic2.category_id, topic_id: topic2.id, skip_cache: true)
+ onebox =
+ InlineOneboxer.lookup(
+ topic.url,
+ user_id: admin.id,
+ category_id: topic2.category_id,
+ topic_id: topic2.id,
+ skip_cache: true,
+ )
expect(onebox).to be_blank
end
@@ -103,12 +130,9 @@ RSpec.describe InlineOneboxer do
topic = Fabricate(:topic, title: "Inline oneboxer")
Fabricate(:post, topic: topic) # OP
Fabricate(:post, topic: topic)
- lookup = -> (number) do
- InlineOneboxer.lookup(
- "#{topic.url}/#{number}",
- skip_cache: true
- )[:title]
- end
+ lookup = ->(number) {
+ InlineOneboxer.lookup("#{topic.url}/#{number}", skip_cache: true)[:title]
+ }
posts = topic.reload.posts.order("post_number ASC")
expect(lookup.call(0)).to eq("Inline oneboxer")
@@ -139,14 +163,13 @@ RSpec.describe InlineOneboxer do
it "will crawl anything if allowed to" do
SiteSetting.enable_inline_onebox_on_all_domains = true
- stub_request(:get, "https://eviltrout.com/some-path").
- to_return(status: 200, body: "a blog ")
-
- onebox = InlineOneboxer.lookup(
- "https://eviltrout.com/some-path",
- skip_cache: true
+ stub_request(:get, "https://eviltrout.com/some-path").to_return(
+ status: 200,
+ body: "a blog ",
)
+ onebox = InlineOneboxer.lookup("https://eviltrout.com/some-path", skip_cache: true)
+
expect(onebox).to be_present
expect(onebox[:url]).to eq("https://eviltrout.com/some-path")
expect(onebox[:title]).to eq("a blog")
@@ -155,14 +178,13 @@ RSpec.describe InlineOneboxer do
it "will not return a onebox if it does not meet minimal length" do
SiteSetting.enable_inline_onebox_on_all_domains = true
- stub_request(:get, "https://eviltrout.com/some-path").
- to_return(status: 200, body: "a ")
-
- onebox = InlineOneboxer.lookup(
- "https://eviltrout.com/some-path",
- skip_cache: true
+ stub_request(:get, "https://eviltrout.com/some-path").to_return(
+ status: 200,
+ body: "a ",
)
+ onebox = InlineOneboxer.lookup("https://eviltrout.com/some-path", skip_cache: true)
+
expect(onebox).to be_present
expect(onebox[:url]).to eq("https://eviltrout.com/some-path")
expect(onebox[:title]).to eq(nil)
@@ -172,10 +194,7 @@ RSpec.describe InlineOneboxer do
SiteSetting.allowed_inline_onebox_domains = "eviltrout.com"
RetrieveTitle.stubs(:crawl).returns("Evil Trout's Blog")
- onebox = InlineOneboxer.lookup(
- "https://eviltrout.com/some-path",
- skip_cache: true
- )
+ onebox = InlineOneboxer.lookup("https://eviltrout.com/some-path", skip_cache: true)
expect(onebox).to be_present
expect(onebox[:url]).to eq("https://eviltrout.com/some-path")
expect(onebox[:title]).to eq("Evil Trout's Blog")
@@ -184,11 +203,10 @@ RSpec.describe InlineOneboxer do
describe "lookups for blocked domains in the hostname" do
shared_examples "blocks the domain" do |setting, domain_to_test|
it "does not retrieve title" do
- stub_request(:get, domain_to_test)
- .to_return(
- status: 200,
- body: "hello world ",
- )
+ stub_request(:get, domain_to_test).to_return(
+ status: 200,
+ body: "hello world ",
+ )
SiteSetting.blocked_onebox_domains = setting
onebox = InlineOneboxer.lookup(domain_to_test, skip_cache: true)
@@ -199,11 +217,10 @@ RSpec.describe InlineOneboxer do
shared_examples "does not fulfil blocked domain" do |setting, domain_to_test|
it "retrieves title" do
- stub_request(:get, domain_to_test)
- .to_return(
- status: 200,
- body: "hello world ",
- )
+ stub_request(:get, domain_to_test).to_return(
+ status: 200,
+ body: "hello world ",
+ )
SiteSetting.blocked_onebox_domains = setting
onebox = InlineOneboxer.lookup(domain_to_test, skip_cache: true)
@@ -226,39 +243,55 @@ RSpec.describe InlineOneboxer do
it "doesn't retrieve title if a blocked domain is encountered anywhere in the redirect chain" do
SiteSetting.blocked_onebox_domains = "redirect.com"
- stub_request(:get, "https://mainwebsite.com/blah")
- .to_return(status: 301, body: "", headers: { "location" => "https://redirect.com/blah" })
- stub_request(:get, "https://redirect.com/blah")
- .to_return(status: 301, body: "", headers: { "location" => "https://finalwebsite.com/blah" })
- stub_request(:get, "https://finalwebsite.com/blah")
- .to_return(status: 200, body: "hello world ")
+ stub_request(:get, "https://mainwebsite.com/blah").to_return(
+ status: 301,
+ body: "",
+ headers: {
+ "location" => "https://redirect.com/blah",
+ },
+ )
+ stub_request(:get, "https://redirect.com/blah").to_return(
+ status: 301,
+ body: "",
+ headers: {
+ "location" => "https://finalwebsite.com/blah",
+ },
+ )
+ stub_request(:get, "https://finalwebsite.com/blah").to_return(
+ status: 200,
+ body: "hello world ",
+ )
onebox = InlineOneboxer.lookup("https://mainwebsite.com/blah", skip_cache: true)
expect(onebox[:title]).to be_blank
end
it "doesn't retrieve title if the Discourse-No-Onebox header == 1" do
- stub_request(:get, "https://mainwebsite.com/blah")
- .to_return(
- status: 200,
- body: "hello world ",
- headers: { "Discourse-No-Onebox" => "1" }
- )
+ stub_request(:get, "https://mainwebsite.com/blah").to_return(
+ status: 200,
+ body: "hello world ",
+ headers: {
+ "Discourse-No-Onebox" => "1",
+ },
+ )
onebox = InlineOneboxer.lookup("https://mainwebsite.com/blah", skip_cache: true)
expect(onebox[:title]).to be_blank
- stub_request(:get, "https://mainwebsite.com/blah/2")
- .to_return(
- status: 301,
- body: "",
- headers: { "location" => "https://mainwebsite.com/blah/2/redirect" }
- )
- stub_request(:get, "https://mainwebsite.com/blah/2/redirect")
- .to_return(
- status: 301,
- body: "",
- headers: { "Discourse-No-Onebox" => "1", "location" => "https://somethingdoesnotmatter.com" }
- )
+ stub_request(:get, "https://mainwebsite.com/blah/2").to_return(
+ status: 301,
+ body: "",
+ headers: {
+ "location" => "https://mainwebsite.com/blah/2/redirect",
+ },
+ )
+ stub_request(:get, "https://mainwebsite.com/blah/2/redirect").to_return(
+ status: 301,
+ body: "",
+ headers: {
+ "Discourse-No-Onebox" => "1",
+ "location" => "https://somethingdoesnotmatter.com",
+ },
+ )
onebox = InlineOneboxer.lookup("https://mainwebsite.com/blah/2", skip_cache: true)
expect(onebox[:title]).to be_blank
onebox = InlineOneboxer.lookup("https://mainwebsite.com/blah/2/redirect", skip_cache: true)
@@ -267,48 +300,46 @@ RSpec.describe InlineOneboxer do
end
context "when block_onebox_on_redirect is enabled" do
- before do
- SiteSetting.block_onebox_on_redirect = true
- end
+ before { SiteSetting.block_onebox_on_redirect = true }
- after do
- FinalDestination.clear_https_cache!("redirects.com")
- end
+ after { FinalDestination.clear_https_cache!("redirects.com") }
it "doesn't onebox if the URL redirects" do
- stub_request(:get, "https://redirects.com/blah/gg")
- .to_return(
- status: 301,
- body: "",
- headers: { "location" => "https://redirects.com/blah/gg/redirect" }
- )
+ stub_request(:get, "https://redirects.com/blah/gg").to_return(
+ status: 301,
+ body: "",
+ headers: {
+ "location" => "https://redirects.com/blah/gg/redirect",
+ },
+ )
onebox = InlineOneboxer.lookup("https://redirects.com/blah/gg", skip_cache: true)
expect(onebox[:title]).to be_blank
end
it "allows an initial http -> https redirect if the redirect URL is identical to the original" do
- stub_request(:get, "http://redirects.com/blah/gg")
- .to_return(
- status: 301,
- body: "",
- headers: { "location" => "https://redirects.com/blah/gg" }
- )
- stub_request(:get, "https://redirects.com/blah/gg")
- .to_return(
- status: 200,
- body: "The Redirects Website "
- )
+ stub_request(:get, "http://redirects.com/blah/gg").to_return(
+ status: 301,
+ body: "",
+ headers: {
+ "location" => "https://redirects.com/blah/gg",
+ },
+ )
+ stub_request(:get, "https://redirects.com/blah/gg").to_return(
+ status: 200,
+ body: "The Redirects Website ",
+ )
onebox = InlineOneboxer.lookup("http://redirects.com/blah/gg", skip_cache: true)
expect(onebox[:title]).to eq("The Redirects Website")
end
it "doesn't allow an initial http -> https redirect if the redirect URL is different to the original" do
- stub_request(:get, "http://redirects.com/blah/gg")
- .to_return(
- status: 301,
- body: "",
- headers: { "location" => "https://redirects.com/blah/gg/2" }
- )
+ stub_request(:get, "http://redirects.com/blah/gg").to_return(
+ status: 301,
+ body: "",
+ headers: {
+ "location" => "https://redirects.com/blah/gg/2",
+ },
+ )
onebox = InlineOneboxer.lookup("http://redirects.com/blah/gg", skip_cache: true)
expect(onebox[:title]).to be_blank
end
@@ -319,14 +350,13 @@ RSpec.describe InlineOneboxer do
SiteSetting.enable_inline_onebox_on_all_domains = true
- stub_request(:get, "https://eviltrout.com/some-path").
- to_return(status: 200, body: "welcome to my blog ")
-
- onebox = InlineOneboxer.lookup(
- "https://eviltrout.com/some-path",
- skip_cache: true
+ stub_request(:get, "https://eviltrout.com/some-path").to_return(
+ status: 200,
+ body: "welcome to my blog ",
)
+ onebox = InlineOneboxer.lookup("https://eviltrout.com/some-path", skip_cache: true)
+
expect(onebox).to be_present
expect(onebox[:url]).to eq("https://eviltrout.com/some-path")
expect(onebox[:title]).to eq("welcome to ■■ blog")
@@ -337,13 +367,9 @@ RSpec.describe InlineOneboxer do
SiteSetting.enable_inline_onebox_on_all_domains = true
- stub_request(:get, "https://eviltrout.com/some-path").
- to_return(status: 404, body: "")
+ stub_request(:get, "https://eviltrout.com/some-path").to_return(status: 404, body: "")
- onebox = InlineOneboxer.lookup(
- "https://eviltrout.com/some-path",
- skip_cache: true
- )
+ onebox = InlineOneboxer.lookup("https://eviltrout.com/some-path", skip_cache: true)
expect(onebox).to be_present
expect(onebox[:url]).to eq("https://eviltrout.com/some-path")
@@ -353,15 +379,15 @@ RSpec.describe InlineOneboxer do
describe ".register_local_handler" do
it "calls registered local handler" do
- InlineOneboxer.register_local_handler('wizard') do |url, route|
- { url: url, title: 'Custom Onebox for Wizard' }
+ InlineOneboxer.register_local_handler("wizard") do |url, route|
+ { url: url, title: "Custom Onebox for Wizard" }
end
url = "#{Discourse.base_url}/wizard"
results = InlineOneboxer.new([url], skip_cache: true).process
expect(results).to be_present
expect(results[0][:url]).to eq(url)
- expect(results[0][:title]).to eq('Custom Onebox for Wizard')
+ expect(results[0][:title]).to eq("Custom Onebox for Wizard")
end
end
end
diff --git a/spec/lib/js_locale_helper_spec.rb b/spec/lib/js_locale_helper_spec.rb
index 775db523eb0..984fb64c66a 100644
--- a/spec/lib/js_locale_helper_spec.rb
+++ b/spec/lib/js_locale_helper_spec.rb
@@ -1,9 +1,8 @@
# frozen_string_literal: true
-require 'mini_racer'
+require "mini_racer"
RSpec.describe JsLocaleHelper do
-
module StubLoadTranslations
def set_translations(locale, translations)
@loaded_translations ||= HashWithIndifferentAccess.new
@@ -22,13 +21,15 @@ RSpec.describe JsLocaleHelper do
after { JsLocaleHelper.clear_cache! }
describe "#output_locale" do
-
it "doesn't change the cached translations hash" do
I18n.locale = :fr
- expect(JsLocaleHelper.output_locale('fr').length).to be > 0
- expect(JsLocaleHelper.translations_for('fr')['fr'].keys).to contain_exactly("js", "admin_js", "wizard_js")
+ expect(JsLocaleHelper.output_locale("fr").length).to be > 0
+ expect(JsLocaleHelper.translations_for("fr")["fr"].keys).to contain_exactly(
+ "js",
+ "admin_js",
+ "wizard_js",
+ )
end
-
end
describe "message format" do
@@ -37,11 +38,11 @@ RSpec.describe JsLocaleHelper do
end
def setup_message_format(format)
- filename = message_format_filename('en')
- compiled = JsLocaleHelper.compile_message_format(filename, 'en', format)
+ filename = message_format_filename("en")
+ compiled = JsLocaleHelper.compile_message_format(filename, "en", format)
@ctx = MiniRacer::Context.new
- @ctx.eval('MessageFormat = {locale: {}};')
+ @ctx.eval("MessageFormat = {locale: {}};")
@ctx.load(filename)
@ctx.eval("var test = #{compiled}")
end
@@ -50,71 +51,84 @@ RSpec.describe JsLocaleHelper do
@ctx.eval("test(#{opts.to_json})")
end
- it 'handles plurals' do
- setup_message_format('{NUM_RESULTS, plural,
+ it "handles plurals" do
+ setup_message_format(
+ "{NUM_RESULTS, plural,
one {1 result}
other {# results}
- }')
- expect(localize(NUM_RESULTS: 1)).to eq('1 result')
- expect(localize(NUM_RESULTS: 2)).to eq('2 results')
+ }",
+ )
+ expect(localize(NUM_RESULTS: 1)).to eq("1 result")
+ expect(localize(NUM_RESULTS: 2)).to eq("2 results")
end
- it 'handles double plurals' do
- setup_message_format('{NUM_RESULTS, plural,
+ it "handles double plurals" do
+ setup_message_format(
+ "{NUM_RESULTS, plural,
one {1 result}
other {# results}
} and {NUM_APPLES, plural,
one {1 apple}
other {# apples}
- }')
+ }",
+ )
- expect(localize(NUM_RESULTS: 1, NUM_APPLES: 2)).to eq('1 result and 2 apples')
- expect(localize(NUM_RESULTS: 2, NUM_APPLES: 1)).to eq('2 results and 1 apple')
+ expect(localize(NUM_RESULTS: 1, NUM_APPLES: 2)).to eq("1 result and 2 apples")
+ expect(localize(NUM_RESULTS: 2, NUM_APPLES: 1)).to eq("2 results and 1 apple")
end
- it 'handles select' do
- setup_message_format('{GENDER, select, male {He} female {She} other {They}} read a book')
- expect(localize(GENDER: 'male')).to eq('He read a book')
- expect(localize(GENDER: 'female')).to eq('She read a book')
- expect(localize(GENDER: 'none')).to eq('They read a book')
+ it "handles select" do
+ setup_message_format("{GENDER, select, male {He} female {She} other {They}} read a book")
+ expect(localize(GENDER: "male")).to eq("He read a book")
+ expect(localize(GENDER: "female")).to eq("She read a book")
+ expect(localize(GENDER: "none")).to eq("They read a book")
end
- it 'can strip out message formats' do
+ it "can strip out message formats" do
hash = { "a" => "b", "c" => { "d" => { "f_MF" => "bob" } } }
expect(JsLocaleHelper.strip_out_message_formats!(hash)).to eq("c.d.f_MF" => "bob")
expect(hash["c"]["d"]).to eq({})
end
- it 'handles message format special keys' do
- JsLocaleHelper.set_translations('en', "en" => {
+ it "handles message format special keys" do
+ JsLocaleHelper.set_translations(
+ "en",
+ "en" => {
"js" => {
"hello" => "world",
"test_MF" => "{HELLO} {COUNT, plural, one {1 duck} other {# ducks}}",
"error_MF" => "{{BLA}",
- "simple_MF" => "{COUNT, plural, one {1} other {#}}"
+ "simple_MF" => "{COUNT, plural, one {1} other {#}}",
},
"admin_js" => {
- "foo_MF" => "{HELLO} {COUNT, plural, one {1 duck} other {# ducks}}"
- }
- })
+ "foo_MF" => "{HELLO} {COUNT, plural, one {1 duck} other {# ducks}}",
+ },
+ },
+ )
ctx = MiniRacer::Context.new
ctx.eval("I18n = { pluralizationRules: {} };")
- ctx.eval(JsLocaleHelper.output_locale('en'))
+ ctx.eval(JsLocaleHelper.output_locale("en"))
expect(ctx.eval('I18n.translations["en"]["js"]["hello"]')).to eq("world")
expect(ctx.eval('I18n.translations["en"]["js"]["test_MF"]')).to eq(nil)
- expect(ctx.eval('I18n.messageFormat("test_MF", { HELLO: "hi", COUNT: 3 })')).to eq("hi 3 ducks")
- expect(ctx.eval('I18n.messageFormat("error_MF", { HELLO: "hi", COUNT: 3 })')).to match(/Invalid Format/)
+ expect(ctx.eval('I18n.messageFormat("test_MF", { HELLO: "hi", COUNT: 3 })')).to eq(
+ "hi 3 ducks",
+ )
+ expect(ctx.eval('I18n.messageFormat("error_MF", { HELLO: "hi", COUNT: 3 })')).to match(
+ /Invalid Format/,
+ )
expect(ctx.eval('I18n.messageFormat("missing", {})')).to match(/missing/)
expect(ctx.eval('I18n.messageFormat("simple_MF", {})')).to match(/COUNT/) # error
- expect(ctx.eval('I18n.messageFormat("foo_MF", { HELLO: "hi", COUNT: 4 })')).to eq("hi 4 ducks")
+ expect(ctx.eval('I18n.messageFormat("foo_MF", { HELLO: "hi", COUNT: 4 })')).to eq(
+ "hi 4 ducks",
+ )
end
- it 'load pluralization rules before precompile' do
- message = JsLocaleHelper.compile_message_format(message_format_filename('ru'), 'ru', 'format')
- expect(message).not_to match 'Plural Function not found'
+ it "load pluralization rules before precompile" do
+ message = JsLocaleHelper.compile_message_format(message_format_filename("ru"), "ru", "format")
+ expect(message).not_to match "Plural Function not found"
end
it "uses message formats from fallback locale" do
@@ -128,33 +142,42 @@ RSpec.describe JsLocaleHelper do
end
end
- it 'performs fallbacks to English if a translation is not available' do
- JsLocaleHelper.set_translations('en', "en" => {
+ it "performs fallbacks to English if a translation is not available" do
+ JsLocaleHelper.set_translations(
+ "en",
+ "en" => {
"js" => {
"only_english" => "1-en",
"english_and_site" => "3-en",
"english_and_user" => "5-en",
"all_three" => "7-en",
- }
- })
+ },
+ },
+ )
- JsLocaleHelper.set_translations('ru', "ru" => {
+ JsLocaleHelper.set_translations(
+ "ru",
+ "ru" => {
"js" => {
"only_site" => "2-ru",
"english_and_site" => "3-ru",
"site_and_user" => "6-ru",
"all_three" => "7-ru",
- }
- })
+ },
+ },
+ )
- JsLocaleHelper.set_translations('uk', "uk" => {
+ JsLocaleHelper.set_translations(
+ "uk",
+ "uk" => {
"js" => {
"only_user" => "4-uk",
"english_and_user" => "5-uk",
"site_and_user" => "6-uk",
"all_three" => "7-uk",
- }
- })
+ },
+ },
+ )
expected = {
"none" => "[uk.js.none]",
@@ -164,39 +187,37 @@ RSpec.describe JsLocaleHelper do
"only_user" => "4-uk",
"english_and_user" => "5-uk",
"site_and_user" => "6-uk",
- "all_three" => "7-uk"
+ "all_three" => "7-uk",
}
- SiteSetting.default_locale = 'ru'
+ SiteSetting.default_locale = "ru"
I18n.locale = :uk
ctx = MiniRacer::Context.new
- ctx.eval('var window = this;')
- ctx.load(Rails.root + 'app/assets/javascripts/locales/i18n.js')
+ ctx.eval("var window = this;")
+ ctx.load(Rails.root + "app/assets/javascripts/locales/i18n.js")
ctx.eval(JsLocaleHelper.output_locale(I18n.locale))
ctx.eval('I18n.defaultLocale = "ru";')
- expect(ctx.eval('I18n.translations').keys).to contain_exactly("uk", "en")
- expect(ctx.eval('I18n.translations.uk.js').keys).to contain_exactly("all_three", "english_and_user", "only_user", "site_and_user")
- expect(ctx.eval('I18n.translations.en.js').keys).to contain_exactly("only_english", "english_and_site")
+ expect(ctx.eval("I18n.translations").keys).to contain_exactly("uk", "en")
+ expect(ctx.eval("I18n.translations.uk.js").keys).to contain_exactly(
+ "all_three",
+ "english_and_user",
+ "only_user",
+ "site_and_user",
+ )
+ expect(ctx.eval("I18n.translations.en.js").keys).to contain_exactly(
+ "only_english",
+ "english_and_site",
+ )
- expected.each do |key, expect|
- expect(ctx.eval("I18n.t(#{"js.#{key}".inspect})")).to eq(expect)
- end
+ expected.each { |key, expect| expect(ctx.eval("I18n.t(#{"js.#{key}".inspect})")).to eq(expect) }
end
it "correctly evaluates message formats in en fallback" do
- JsLocaleHelper.set_translations("en", "en" => {
- "js" => {
- "something_MF" => "en mf",
- },
- })
+ JsLocaleHelper.set_translations("en", "en" => { "js" => { "something_MF" => "en mf" } })
- JsLocaleHelper.set_translations("de", "de" => {
- "js" => {
- "something_MF" => "de mf",
- },
- })
+ JsLocaleHelper.set_translations("de", "de" => { "js" => { "something_MF" => "de mf" } })
TranslationOverride.upsert!("en", "js.something_MF", <<~MF.strip)
There {
@@ -219,15 +240,17 @@ RSpec.describe JsLocaleHelper do
}
JS
- expect(ctx.eval("I18n.messageFormat('something_MF', { UNREAD: 1 })")).to eq("There is one unread")
+ expect(ctx.eval("I18n.messageFormat('something_MF', { UNREAD: 1 })")).to eq(
+ "There is one unread",
+ )
end
LocaleSiteSetting.values.each do |locale|
it "generates valid date helpers for #{locale[:value]} locale" do
js = JsLocaleHelper.output_locale(locale[:value])
ctx = MiniRacer::Context.new
- ctx.eval('var window = this;')
- ctx.load(Rails.root + 'app/assets/javascripts/locales/i18n.js')
+ ctx.eval("var window = this;")
+ ctx.load(Rails.root + "app/assets/javascripts/locales/i18n.js")
ctx.eval(js)
end
@@ -235,32 +258,36 @@ RSpec.describe JsLocaleHelper do
content = JsLocaleHelper.moment_locale(locale[:value])
if (locale[:value] == SiteSettings::DefaultsProvider::DEFAULT_LOCALE)
- expect(content).to eq('')
+ expect(content).to eq("")
else
- expect(content).to_not eq('')
+ expect(content).to_not eq("")
end
end
end
describe ".find_message_format_locale" do
it "finds locale's message format rules" do
- locale, filename = JsLocaleHelper.find_message_format_locale([:de], fallback_to_english: false)
+ locale, filename =
+ JsLocaleHelper.find_message_format_locale([:de], fallback_to_english: false)
expect(locale).to eq("de")
expect(filename).to end_with("/de.js")
end
it "finds locale for en_GB" do
- locale, filename = JsLocaleHelper.find_message_format_locale([:en_GB], fallback_to_english: false)
+ locale, filename =
+ JsLocaleHelper.find_message_format_locale([:en_GB], fallback_to_english: false)
expect(locale).to eq("en")
expect(filename).to end_with("/en.js")
- locale, filename = JsLocaleHelper.find_message_format_locale(["en_GB"], fallback_to_english: false)
+ locale, filename =
+ JsLocaleHelper.find_message_format_locale(["en_GB"], fallback_to_english: false)
expect(locale).to eq("en")
expect(filename).to end_with("/en.js")
end
it "falls back to en when locale doesn't have own message format rules" do
- locale, filename = JsLocaleHelper.find_message_format_locale([:nonexistent], fallback_to_english: true)
+ locale, filename =
+ JsLocaleHelper.find_message_format_locale([:nonexistent], fallback_to_english: true)
expect(locale).to eq("en")
expect(filename).to end_with("/en.js")
end
diff --git a/spec/lib/json_error_spec.rb b/spec/lib/json_error_spec.rb
index cee3760b037..14211498ec6 100644
--- a/spec/lib/json_error_spec.rb
+++ b/spec/lib/json_error_spec.rb
@@ -8,12 +8,11 @@ RSpec.shared_examples "a generic error" do
end
it "has a generic error message" do
- expect(result[:errors]).to eq([I18n.t('js.generic_error')])
+ expect(result[:errors]).to eq([I18n.t("js.generic_error")])
end
end
RSpec.describe JsonError do
-
let(:creator) { Object.new.extend(JsonError) }
describe "with a nil argument" do
@@ -49,5 +48,4 @@ RSpec.describe JsonError do
expect(result[:errors]).not_to be_blank
end
end
-
end
diff --git a/spec/lib/letter_avatar_spec.rb b/spec/lib/letter_avatar_spec.rb
index b5e49eec4e4..3dd910ab6ad 100644
--- a/spec/lib/letter_avatar_spec.rb
+++ b/spec/lib/letter_avatar_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'letter_avatar'
+require "letter_avatar"
RSpec.describe LetterAvatar do
it "can cleanup correctly" do
diff --git a/spec/lib/message_id_service_spec.rb b/spec/lib/message_id_service_spec.rb
index d20c59fe207..dc8fa436fcc 100644
--- a/spec/lib/message_id_service_spec.rb
+++ b/spec/lib/message_id_service_spec.rb
@@ -11,38 +11,56 @@ RSpec.describe Email::MessageIdService do
it "generates for the post using the message_id on the post's incoming_email" do
Fabricate(:incoming_email, message_id: "test@test.localhost", post: post)
post.reload
- expect(subject.generate_for_post(post, use_incoming_email_if_present: true)).to eq("")
+ expect(subject.generate_for_post(post, use_incoming_email_if_present: true)).to eq(
+ "",
+ )
end
it "generates for the post without an incoming_email record" do
expect(subject.generate_for_post(post)).to match(subject.message_id_post_id_regexp)
- expect(subject.generate_for_post(post, use_incoming_email_if_present: true)).to match(subject.message_id_post_id_regexp)
+ expect(subject.generate_for_post(post, use_incoming_email_if_present: true)).to match(
+ subject.message_id_post_id_regexp,
+ )
end
end
describe "#generate_for_topic" do
it "generates for the topic using the message_id on the first post's incoming_email" do
- Fabricate(:incoming_email, message_id: "test213428@somemailservice.com", post: post, created_via: IncomingEmail.created_via_types[:handle_mail])
- post.reload
- expect(subject.generate_for_topic(topic, use_incoming_email_if_present: true)).to eq("")
- end
-
- it "does not use the first post's incoming email if it was created via group_smtp, only handle_mail" do
- incoming = Fabricate(
+ Fabricate(
:incoming_email,
message_id: "test213428@somemailservice.com",
post: post,
- created_via: IncomingEmail.created_via_types[:group_smtp]
+ created_via: IncomingEmail.created_via_types[:handle_mail],
)
post.reload
- expect(subject.generate_for_topic(topic, use_incoming_email_if_present: true)).to match(subject.message_id_topic_id_regexp)
+ expect(subject.generate_for_topic(topic, use_incoming_email_if_present: true)).to eq(
+ "",
+ )
+ end
+
+ it "does not use the first post's incoming email if it was created via group_smtp, only handle_mail" do
+ incoming =
+ Fabricate(
+ :incoming_email,
+ message_id: "test213428@somemailservice.com",
+ post: post,
+ created_via: IncomingEmail.created_via_types[:group_smtp],
+ )
+ post.reload
+ expect(subject.generate_for_topic(topic, use_incoming_email_if_present: true)).to match(
+ subject.message_id_topic_id_regexp,
+ )
incoming.update(created_via: IncomingEmail.created_via_types[:handle_mail])
- expect(subject.generate_for_topic(topic, use_incoming_email_if_present: true)).to eq("")
+ expect(subject.generate_for_topic(topic, use_incoming_email_if_present: true)).to eq(
+ "",
+ )
end
it "generates for the topic without an incoming_email record" do
expect(subject.generate_for_topic(topic)).to match(subject.message_id_topic_id_regexp)
- expect(subject.generate_for_topic(topic, use_incoming_email_if_present: true)).to match(subject.message_id_topic_id_regexp)
+ expect(subject.generate_for_topic(topic, use_incoming_email_if_present: true)).to match(
+ subject.message_id_topic_id_regexp,
+ )
end
it "generates canonical for the topic" do
@@ -67,17 +85,34 @@ RSpec.describe Email::MessageIdService do
it "handles bulk posts with a mixture of existing and new outbound_message_ids, returning in created_at order" do
topic = Fabricate(:topic)
- post_bulk1 = Fabricate(:post, topic: topic, created_at: 10.days.ago, outbound_message_id: "blah@test.host")
+ post_bulk1 =
+ Fabricate(
+ :post,
+ topic: topic,
+ created_at: 10.days.ago,
+ outbound_message_id: "blah@test.host",
+ )
post_bulk2 = Fabricate(:post, topic: topic, created_at: 12.days.ago, outbound_message_id: nil)
- post_bulk3 = Fabricate(:post, topic: topic, created_at: 11.days.ago, outbound_message_id: "sf92c349438509=3453@test.host")
+ post_bulk3 =
+ Fabricate(
+ :post,
+ topic: topic,
+ created_at: 11.days.ago,
+ outbound_message_id: "sf92c349438509=3453@test.host",
+ )
post_bulk4 = Fabricate(:post, topic: topic, created_at: 3.days.ago, outbound_message_id: nil)
- result = subject.generate_or_use_existing([post_bulk1.id, post_bulk2.id, post_bulk3.id, post_bulk4.id])
- expect(result).to eq([
- "",
- "",
- "",
- ""
- ])
+ result =
+ subject.generate_or_use_existing(
+ [post_bulk1.id, post_bulk2.id, post_bulk3.id, post_bulk4.id],
+ )
+ expect(result).to eq(
+ [
+ "",
+ "",
+ "",
+ "",
+ ],
+ )
end
end
@@ -86,7 +121,9 @@ RSpec.describe Email::MessageIdService do
let(:topic_format_message_id) { "" }
let(:discourse_format_message_id) { "" }
let(:default_format_message_id) { "<36ac1ddd-5083-461d-b72c-6372fb0e7f33@test.localhost>" }
- let(:gmail_format_message_id) { "" }
+ let(:gmail_format_message_id) do
+ ""
+ end
it "finds a post based only on a post-format message id" do
expect(subject.find_post_from_message_ids([post_format_message_id])).to eq(post)
@@ -106,25 +143,30 @@ RSpec.describe Email::MessageIdService do
end
it "finds a post from the email log" do
- email_log = Fabricate(:email_log, message_id: subject.message_id_clean(default_format_message_id))
+ email_log =
+ Fabricate(:email_log, message_id: subject.message_id_clean(default_format_message_id))
expect(subject.find_post_from_message_ids([default_format_message_id])).to eq(email_log.post)
end
it "finds a post from the incoming email log" do
- incoming_email = Fabricate(
- :incoming_email,
- message_id: subject.message_id_clean(gmail_format_message_id),
- post: Fabricate(:post)
+ incoming_email =
+ Fabricate(
+ :incoming_email,
+ message_id: subject.message_id_clean(gmail_format_message_id),
+ post: Fabricate(:post),
+ )
+ expect(subject.find_post_from_message_ids([gmail_format_message_id])).to eq(
+ incoming_email.post,
)
- expect(subject.find_post_from_message_ids([gmail_format_message_id])).to eq(incoming_email.post)
end
it "gets the last created post if multiple are returned" do
- incoming_email = Fabricate(
- :incoming_email,
- message_id: subject.message_id_clean(post_format_message_id),
- post: Fabricate(:post, created_at: 10.days.ago)
- )
+ incoming_email =
+ Fabricate(
+ :incoming_email,
+ message_id: subject.message_id_clean(post_format_message_id),
+ post: Fabricate(:post, created_at: 10.days.ago),
+ )
expect(subject.find_post_from_message_ids([post_format_message_id])).to eq(post)
end
end
@@ -147,7 +189,9 @@ RSpec.describe Email::MessageIdService do
expect(check_format("")).to eq(true)
expect(check_format("topic/1223@blah")).to eq(false)
- expect(check_format("")).to eq(false)
+ expect(
+ check_format(""),
+ ).to eq(false)
expect(check_format("t/1223@test.localhost")).to eq(false)
end
end
diff --git a/spec/lib/method_profiler_spec.rb b/spec/lib/method_profiler_spec.rb
index fe372cdddee..408a52defb5 100644
--- a/spec/lib/method_profiler_spec.rb
+++ b/spec/lib/method_profiler_spec.rb
@@ -6,9 +6,7 @@ RSpec.describe MethodProfiler do
end
def recurse(count = 5)
- if count > 0
- recurse(count - 1)
- end
+ recurse(count - 1) if count > 0
end
end
@@ -29,11 +27,13 @@ RSpec.describe MethodProfiler do
Sneetch.new.beach
data = MethodProfiler.transfer
result = nil
- Thread.new do
- MethodProfiler.start(data)
- Sneetch.new.beach
- result = MethodProfiler.stop
- end.join
+ Thread
+ .new do
+ MethodProfiler.start(data)
+ Sneetch.new.beach
+ result = MethodProfiler.stop
+ end
+ .join
expect(result[:at_beach][:calls]).to eq(2)
end
diff --git a/spec/lib/middleware/anonymous_cache_spec.rb b/spec/lib/middleware/anonymous_cache_spec.rb
index 34eff03ea22..05a496c8cb1 100644
--- a/spec/lib/middleware/anonymous_cache_spec.rb
+++ b/spec/lib/middleware/anonymous_cache_spec.rb
@@ -18,7 +18,9 @@ RSpec.describe Middleware::AnonymousCache do
end
it "is false for non GET" do
- expect(new_helper("ANON_CACHE_DURATION" => 10, "REQUEST_METHOD" => "POST").cacheable?).to eq(false)
+ expect(
+ new_helper("ANON_CACHE_DURATION" => 10, "REQUEST_METHOD" => "POST").cacheable?,
+ ).to eq(false)
end
it "is false if it has a valid auth cookie" do
@@ -97,12 +99,13 @@ RSpec.describe Middleware::AnonymousCache do
end
context "when cached" do
- let!(:helper) do
- new_helper("ANON_CACHE_DURATION" => 10)
- end
+ let!(:helper) { new_helper("ANON_CACHE_DURATION" => 10) }
let!(:crawler) do
- new_helper("ANON_CACHE_DURATION" => 10, "HTTP_USER_AGENT" => "AdsBot-Google (+http://www.google.com/adsbot.html)")
+ new_helper(
+ "ANON_CACHE_DURATION" => 10,
+ "HTTP_USER_AGENT" => "AdsBot-Google (+http://www.google.com/adsbot.html)",
+ )
end
after do
@@ -110,9 +113,7 @@ RSpec.describe Middleware::AnonymousCache do
crawler.clear_cache
end
- before do
- global_setting :anon_cache_store_threshold, 1
- end
+ before { global_setting :anon_cache_store_threshold, 1 }
it "compresses body on demand" do
global_setting :compress_anon_cache, true
@@ -121,7 +122,9 @@ RSpec.describe Middleware::AnonymousCache do
helper.cache([200, { "HELLO" => "WORLD" }, [payload]])
helper = new_helper("ANON_CACHE_DURATION" => 10)
- expect(helper.cached).to eq([200, { "X-Discourse-Cached" => "true", "HELLO" => "WORLD" }, [payload]])
+ expect(helper.cached).to eq(
+ [200, { "X-Discourse-Cached" => "true", "HELLO" => "WORLD" }, [payload]],
+ )
# depends on i7z implementation, but lets assume it is stable unless we discover
# otherwise
@@ -132,7 +135,9 @@ RSpec.describe Middleware::AnonymousCache do
helper.cache([200, { "HELLO" => "WORLD" }, ["hello ", "my world"]])
helper = new_helper("ANON_CACHE_DURATION" => 10)
- expect(helper.cached).to eq([200, { "X-Discourse-Cached" => "true", "HELLO" => "WORLD" }, ["hello my world"]])
+ expect(helper.cached).to eq(
+ [200, { "X-Discourse-Cached" => "true", "HELLO" => "WORLD" }, ["hello my world"]],
+ )
helper = new_helper("ANON_CACHE_DURATION" => 10, "HTTP_ACCEPT_ENCODING" => "gz, br")
expect(helper.cached).to eq(nil)
@@ -145,35 +150,35 @@ RSpec.describe Middleware::AnonymousCache do
helper = new_helper("ANON_CACHE_DURATION" => 10)
helper.is_mobile = true
- expect(helper.cached).to eq([200, { "X-Discourse-Cached" => "true", "HELLO" => "WORLD" }, ["hello my world"]])
+ expect(helper.cached).to eq(
+ [200, { "X-Discourse-Cached" => "true", "HELLO" => "WORLD" }, ["hello my world"]],
+ )
expect(crawler.cached).to eq(nil)
crawler.cache([200, { "HELLO" => "WORLD" }, ["hello ", "world"]])
- expect(crawler.cached).to eq([200, { "X-Discourse-Cached" => "true", "HELLO" => "WORLD" }, ["hello world"]])
+ expect(crawler.cached).to eq(
+ [200, { "X-Discourse-Cached" => "true", "HELLO" => "WORLD" }, ["hello world"]],
+ )
end
end
end
- describe 'background request rate limit' do
- it 'will rate limit background requests' do
-
- app = Middleware::AnonymousCache.new(
- lambda do |env|
- [200, {}, ["ok"]]
- end
- )
+ describe "background request rate limit" do
+ it "will rate limit background requests" do
+ app = Middleware::AnonymousCache.new(lambda { |env| [200, {}, ["ok"]] })
global_setting :background_requests_max_queue_length, "0.5"
cookie = create_auth_cookie(token: SecureRandom.hex)
- env = create_request_env.merge(
- "HTTP_COOKIE" => "_t=#{cookie}",
- "HOST" => "site.com",
- "REQUEST_METHOD" => "GET",
- "REQUEST_URI" => "/somewhere/rainbow",
- "REQUEST_QUEUE_SECONDS" => 2.1,
- "rack.input" => StringIO.new
- )
+ env =
+ create_request_env.merge(
+ "HTTP_COOKIE" => "_t=#{cookie}",
+ "HOST" => "site.com",
+ "REQUEST_METHOD" => "GET",
+ "REQUEST_URI" => "/somewhere/rainbow",
+ "REQUEST_QUEUE_SECONDS" => 2.1,
+ "rack.input" => StringIO.new,
+ )
# non background ... long request
env["REQUEST_QUEUE_SECONDS"] = 2
@@ -193,41 +198,39 @@ RSpec.describe Middleware::AnonymousCache do
status, _ = app.call(env.dup)
expect(status).to eq(200)
-
end
end
- describe '#force_anonymous!' do
- before do
- RateLimiter.enable
- end
-
- it 'will revert to anonymous once we reach the limit' do
+ describe "#force_anonymous!" do
+ before { RateLimiter.enable }
+ it "will revert to anonymous once we reach the limit" do
RateLimiter.clear_all!
is_anon = false
- app = Middleware::AnonymousCache.new(
- lambda do |env|
- is_anon = env["HTTP_COOKIE"].nil? && env["HTTP_DISCOURSE_LOGGED_IN"].nil?
- [200, {}, ["ok"]]
- end
- )
+ app =
+ Middleware::AnonymousCache.new(
+ lambda do |env|
+ is_anon = env["HTTP_COOKIE"].nil? && env["HTTP_DISCOURSE_LOGGED_IN"].nil?
+ [200, {}, ["ok"]]
+ end,
+ )
global_setting :force_anonymous_min_per_10_seconds, 2
global_setting :force_anonymous_min_queue_seconds, 1
cookie = create_auth_cookie(token: SecureRandom.hex)
- env = create_request_env.merge(
- "HTTP_COOKIE" => "_t=#{cookie}",
- "HTTP_DISCOURSE_LOGGED_IN" => "true",
- "HOST" => "site.com",
- "REQUEST_METHOD" => "GET",
- "REQUEST_URI" => "/somewhere/rainbow",
- "REQUEST_QUEUE_SECONDS" => 2.1,
- "rack.input" => StringIO.new
- )
+ env =
+ create_request_env.merge(
+ "HTTP_COOKIE" => "_t=#{cookie}",
+ "HTTP_DISCOURSE_LOGGED_IN" => "true",
+ "HOST" => "site.com",
+ "REQUEST_METHOD" => "GET",
+ "REQUEST_URI" => "/somewhere/rainbow",
+ "REQUEST_QUEUE_SECONDS" => 2.1,
+ "rack.input" => StringIO.new,
+ )
is_anon = false
app.call(env.dup)
@@ -244,7 +247,7 @@ RSpec.describe Middleware::AnonymousCache do
is_anon = false
_status, headers, _body = app.call(env.dup)
expect(is_anon).to eq(true)
- expect(headers['Set-Cookie']).to eq('dosp=1; Path=/')
+ expect(headers["Set-Cookie"]).to eq("dosp=1; Path=/")
# tricky change, a 50ms delay still will trigger protection
# once it is tripped
@@ -263,11 +266,10 @@ RSpec.describe Middleware::AnonymousCache do
end
end
- describe 'invalid request payload' do
- it 'returns 413 for GET request with payload' do
- status, headers, _ = middleware.call(env.tap do |environment|
- environment[Rack::RACK_INPUT].write("test")
- end)
+ describe "invalid request payload" do
+ it "returns 413 for GET request with payload" do
+ status, headers, _ =
+ middleware.call(env.tap { |environment| environment[Rack::RACK_INPUT].write("test") })
expect(status).to eq(413)
expect(headers["Cache-Control"]).to eq("private, max-age=0, must-revalidate")
@@ -278,104 +280,105 @@ RSpec.describe Middleware::AnonymousCache do
let :non_crawler do
{
"HTTP_USER_AGENT" =>
- "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
+ "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
}
end
def get(path, options)
- @env = env({
- "REQUEST_URI" => path,
- "PATH_INFO" => path,
- "REQUEST_PATH" => path
- }.merge(options[:headers]))
+ @env =
+ env(
+ { "REQUEST_URI" => path, "PATH_INFO" => path, "REQUEST_PATH" => path }.merge(
+ options[:headers],
+ ),
+ )
@status, @response_header, @response = middleware.call(@env)
end
it "applies allowed_crawler_user_agents correctly" do
- SiteSetting.allowed_crawler_user_agents = 'Googlebot'
+ SiteSetting.allowed_crawler_user_agents = "Googlebot"
- get '/', headers: {
- 'HTTP_USER_AGENT' => 'Googlebot/2.1 (+http://www.google.com/bot.html)'
- }
+ get "/", headers: { "HTTP_USER_AGENT" => "Googlebot/2.1 (+http://www.google.com/bot.html)" }
expect(@status).to eq(200)
- get '/', headers: {
- 'HTTP_USER_AGENT' => 'Anotherbot/2.1 (+http://www.notgoogle.com/bot.html)'
- }
+ get "/",
+ headers: {
+ "HTTP_USER_AGENT" => "Anotherbot/2.1 (+http://www.notgoogle.com/bot.html)",
+ }
expect(@status).to eq(403)
expect(@response).to be_an(Array)
- get '/', headers: non_crawler
+ get "/", headers: non_crawler
expect(@status).to eq(200)
end
it "doesn't block api requests" do
- SiteSetting.allowed_crawler_user_agents = 'Googlebot'
+ SiteSetting.allowed_crawler_user_agents = "Googlebot"
api_key = Fabricate(:api_key)
- get "/latest?api_key=#{api_key.key}&api_username=system", headers: {
- "QUERY_STRING" => "api_key=#{api_key.key}&api_username=system"
- }
+ get "/latest?api_key=#{api_key.key}&api_username=system",
+ headers: {
+ "QUERY_STRING" => "api_key=#{api_key.key}&api_username=system",
+ }
expect(@status).to eq(200)
end
it "applies blocked_crawler_user_agents correctly" do
- SiteSetting.blocked_crawler_user_agents = 'Googlebot'
+ SiteSetting.blocked_crawler_user_agents = "Googlebot"
- get '/', headers: non_crawler
+ get "/", headers: non_crawler
expect(@status).to eq(200)
- get '/', headers: {
- 'HTTP_USER_AGENT' => 'Googlebot/2.1 (+http://www.google.com/bot.html)'
- }
+ get "/", headers: { "HTTP_USER_AGENT" => "Googlebot/2.1 (+http://www.google.com/bot.html)" }
expect(@status).to eq(403)
- get '/', headers: {
- 'HTTP_USER_AGENT' => 'Twitterbot/2.1 (+http://www.notgoogle.com/bot.html)'
- }
+ get "/",
+ headers: {
+ "HTTP_USER_AGENT" => "Twitterbot/2.1 (+http://www.notgoogle.com/bot.html)",
+ }
expect(@status).to eq(200)
end
it "should never block robots.txt" do
- SiteSetting.blocked_crawler_user_agents = 'Googlebot'
+ SiteSetting.blocked_crawler_user_agents = "Googlebot"
- get '/robots.txt', headers: {
- 'HTTP_USER_AGENT' => 'Googlebot/2.1 (+http://www.google.com/bot.html)'
- }
+ get "/robots.txt",
+ headers: {
+ "HTTP_USER_AGENT" => "Googlebot/2.1 (+http://www.google.com/bot.html)",
+ }
expect(@status).to eq(200)
end
it "should never block srv/status" do
- SiteSetting.blocked_crawler_user_agents = 'Googlebot'
+ SiteSetting.blocked_crawler_user_agents = "Googlebot"
- get '/srv/status', headers: {
- 'HTTP_USER_AGENT' => 'Googlebot/2.1 (+http://www.google.com/bot.html)'
- }
+ get "/srv/status",
+ headers: {
+ "HTTP_USER_AGENT" => "Googlebot/2.1 (+http://www.google.com/bot.html)",
+ }
expect(@status).to eq(200)
end
it "blocked crawlers shouldn't log page views" do
- SiteSetting.blocked_crawler_user_agents = 'Googlebot'
+ SiteSetting.blocked_crawler_user_agents = "Googlebot"
- get '/', headers: {
- 'HTTP_USER_AGENT' => 'Googlebot/2.1 (+http://www.google.com/bot.html)'
- }
+ get "/", headers: { "HTTP_USER_AGENT" => "Googlebot/2.1 (+http://www.google.com/bot.html)" }
expect(@env["discourse.request_tracker.skip"]).to eq(true)
end
it "blocks json requests" do
- SiteSetting.blocked_crawler_user_agents = 'Googlebot'
+ SiteSetting.blocked_crawler_user_agents = "Googlebot"
- get '/srv/status.json', headers: {
- 'HTTP_USER_AGENT' => 'Googlebot/2.1 (+http://www.google.com/bot.html)'
- }
+ get "/srv/status.json",
+ headers: {
+ "HTTP_USER_AGENT" => "Googlebot/2.1 (+http://www.google.com/bot.html)",
+ }
expect(@status).to eq(403)
end
diff --git a/spec/lib/middleware/discourse_public_exceptions_spec.rb b/spec/lib/middleware/discourse_public_exceptions_spec.rb
index 557bb916188..e3545bb9cf6 100644
--- a/spec/lib/middleware/discourse_public_exceptions_spec.rb
+++ b/spec/lib/middleware/discourse_public_exceptions_spec.rb
@@ -6,28 +6,27 @@ RSpec.describe Middleware::DiscoursePublicExceptions do
Rails.logger = @fake_logger = FakeLogger.new
end
- after do
- Rails.logger = @orig_logger
- end
+ after { Rails.logger = @orig_logger }
def env(opts = {})
{
"HTTP_HOST" => "http://test.com",
"REQUEST_URI" => "/path?bla=1",
"REQUEST_METHOD" => "GET",
- "rack.input" => ""
+ "rack.input" => "",
}.merge(opts)
end
it "should not log for invalid mime type requests" do
ex = Middleware::DiscoursePublicExceptions.new("/test")
- ex.call(env(
- "HTTP_ACCEPT" => "../broken../",
- "action_dispatch.exception" => ActionController::RoutingError.new("abc")
- ))
+ ex.call(
+ env(
+ "HTTP_ACCEPT" => "../broken../",
+ "action_dispatch.exception" => ActionController::RoutingError.new("abc"),
+ ),
+ )
expect(@fake_logger.warnings.length).to eq(0)
end
-
end
diff --git a/spec/lib/middleware/enforce_hostname_spec.rb b/spec/lib/middleware/enforce_hostname_spec.rb
index 61f0873ae2d..d17657fbdc5 100644
--- a/spec/lib/middleware/enforce_hostname_spec.rb
+++ b/spec/lib/middleware/enforce_hostname_spec.rb
@@ -1,21 +1,23 @@
# frozen_string_literal: true
RSpec.describe Middleware::EnforceHostname do
-
before do
- RailsMultisite::ConnectionManagement.stubs(:current_db_hostnames).returns(['primary.example.com', 'secondary.example.com'])
- RailsMultisite::ConnectionManagement.stubs(:current_hostname).returns('primary.example.com')
+ RailsMultisite::ConnectionManagement.stubs(:current_db_hostnames).returns(
+ %w[primary.example.com secondary.example.com],
+ )
+ RailsMultisite::ConnectionManagement.stubs(:current_hostname).returns("primary.example.com")
end
def check_returned_host(input_host)
resolved_host = nil
- app = described_class.new(
- lambda do |env|
- resolved_host = env["HTTP_HOST"]
- [200, {}, ["ok"]]
- end
- )
+ app =
+ described_class.new(
+ lambda do |env|
+ resolved_host = env["HTTP_HOST"]
+ [200, {}, ["ok"]]
+ end,
+ )
app.call({ "HTTP_HOST" => input_host })
diff --git a/spec/lib/middleware/request_tracker_spec.rb b/spec/lib/middleware/request_tracker_spec.rb
index d00fc3f7592..7c4c7720a7d 100644
--- a/spec/lib/middleware/request_tracker_spec.rb
+++ b/spec/lib/middleware/request_tracker_spec.rb
@@ -5,10 +5,12 @@ RSpec.describe Middleware::RequestTracker do
path = opts.delete(:path) || "/path?bla=1"
create_request_env(path: path).merge(
"HTTP_HOST" => "http://test.com",
- "HTTP_USER_AGENT" => "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
+ "HTTP_USER_AGENT" =>
+ "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
"REQUEST_METHOD" => "GET",
- "HTTP_ACCEPT" => "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
- "rack.input" => StringIO.new
+ "HTTP_ACCEPT" =>
+ "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
+ "rack.input" => StringIO.new,
).merge(opts)
end
@@ -27,12 +29,13 @@ RSpec.describe Middleware::RequestTracker do
it "can handle rogue user agents" do
agent = (+"Evil Googlebot String \xc3\x28").force_encoding("Windows-1252")
- middleware = Middleware::RequestTracker.new(->(env) { ["200", { "Content-Type" => "text/html" }, [""]] })
+ middleware =
+ Middleware::RequestTracker.new(->(env) { ["200", { "Content-Type" => "text/html" }, [""]] })
middleware.call(env("HTTP_USER_AGENT" => agent))
CachedCounting.flush
- expect(WebCrawlerRequest.where(user_agent: agent.encode('utf-8')).count).to eq(1)
+ expect(WebCrawlerRequest.where(user_agent: agent.encode("utf-8")).count).to eq(1)
end
end
@@ -43,9 +46,12 @@ RSpec.describe Middleware::RequestTracker do
end
def log_tracked_view(val)
- data = Middleware::RequestTracker.get_data(env(
- "HTTP_DISCOURSE_TRACK_VIEW" => val
- ), ["200", { "Content-Type" => 'text/html' }], 0.2)
+ data =
+ Middleware::RequestTracker.get_data(
+ env("HTTP_DISCOURSE_TRACK_VIEW" => val),
+ ["200", { "Content-Type" => "text/html" }],
+ 0.2,
+ )
Middleware::RequestTracker.log_request(data)
end
@@ -62,29 +68,43 @@ RSpec.describe Middleware::RequestTracker do
end
it "can log requests correctly" do
- data = Middleware::RequestTracker.get_data(env(
- "HTTP_USER_AGENT" => "AdsBot-Google (+http://www.google.com/adsbot.html)"
- ), ["200", { "Content-Type" => 'text/html' }], 0.1)
+ data =
+ Middleware::RequestTracker.get_data(
+ env("HTTP_USER_AGENT" => "AdsBot-Google (+http://www.google.com/adsbot.html)"),
+ ["200", { "Content-Type" => "text/html" }],
+ 0.1,
+ )
Middleware::RequestTracker.log_request(data)
- data = Middleware::RequestTracker.get_data(env(
- "HTTP_DISCOURSE_TRACK_VIEW" => "1"
- ), ["200", {}], 0.1)
+ data =
+ Middleware::RequestTracker.get_data(
+ env("HTTP_DISCOURSE_TRACK_VIEW" => "1"),
+ ["200", {}],
+ 0.1,
+ )
Middleware::RequestTracker.log_request(data)
- data = Middleware::RequestTracker.get_data(env(
- "HTTP_USER_AGENT" => "Mozilla/5.0 (iPhone; CPU iPhone OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B410 Safari/600.1.4"
- ), ["200", { "Content-Type" => 'text/html' }], 0.1)
+ data =
+ Middleware::RequestTracker.get_data(
+ env(
+ "HTTP_USER_AGENT" =>
+ "Mozilla/5.0 (iPhone; CPU iPhone OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B410 Safari/600.1.4",
+ ),
+ ["200", { "Content-Type" => "text/html" }],
+ 0.1,
+ )
Middleware::RequestTracker.log_request(data)
# /srv/status is never a tracked view because content-type is text/plain
- data = Middleware::RequestTracker.get_data(env(
- "HTTP_USER_AGENT" => "kube-probe/1.18",
- "REQUEST_URI" => "/srv/status?shutdown_ok=1",
- ), ["200", { "Content-Type" => 'text/plain' }], 0.1)
+ data =
+ Middleware::RequestTracker.get_data(
+ env("HTTP_USER_AGENT" => "kube-probe/1.18", "REQUEST_URI" => "/srv/status?shutdown_ok=1"),
+ ["200", { "Content-Type" => "text/plain" }],
+ 0.1,
+ )
Middleware::RequestTracker.log_request(data)
@@ -101,21 +121,26 @@ RSpec.describe Middleware::RequestTracker do
end
it "logs API requests correctly" do
- data = Middleware::RequestTracker.get_data(
- env("_DISCOURSE_API" => "1"), ["200", { "Content-Type" => 'text/json' }], 0.1
- )
+ data =
+ Middleware::RequestTracker.get_data(
+ env("_DISCOURSE_API" => "1"),
+ ["200", { "Content-Type" => "text/json" }],
+ 0.1,
+ )
Middleware::RequestTracker.log_request(data)
- data = Middleware::RequestTracker.get_data(
- env("_DISCOURSE_API" => "1"), ["404", { "Content-Type" => 'text/json' }], 0.1
- )
+ data =
+ Middleware::RequestTracker.get_data(
+ env("_DISCOURSE_API" => "1"),
+ ["404", { "Content-Type" => "text/json" }],
+ 0.1,
+ )
Middleware::RequestTracker.log_request(data)
- data = Middleware::RequestTracker.get_data(
- env("_DISCOURSE_USER_API" => "1"), ["200", {}], 0.1
- )
+ data =
+ Middleware::RequestTracker.get_data(env("_DISCOURSE_USER_API" => "1"), ["200", {}], 0.1)
Middleware::RequestTracker.log_request(data)
CachedCounting.flush
@@ -129,9 +154,12 @@ RSpec.describe Middleware::RequestTracker do
it "can log Discourse user agent requests correctly" do
# log discourse api agents as crawlers for page view stats...
- data = Middleware::RequestTracker.get_data(env(
- "HTTP_USER_AGENT" => "DiscourseAPI Ruby Gem 0.19.0"
- ), ["200", { "Content-Type" => 'text/html' }], 0.1)
+ data =
+ Middleware::RequestTracker.get_data(
+ env("HTTP_USER_AGENT" => "DiscourseAPI Ruby Gem 0.19.0"),
+ ["200", { "Content-Type" => "text/html" }],
+ 0.1,
+ )
Middleware::RequestTracker.log_request(data)
@@ -141,9 +169,12 @@ RSpec.describe Middleware::RequestTracker do
expect(ApplicationRequest.page_view_crawler.first.count).to eq(1)
# ...but count our mobile app user agents as regular visits
- data = Middleware::RequestTracker.get_data(env(
- "HTTP_USER_AGENT" => "Mozilla/5.0 AppleWebKit/605.1.15 Mobile/15E148 DiscourseHub)"
- ), ["200", { "Content-Type" => 'text/html' }], 0.1)
+ data =
+ Middleware::RequestTracker.get_data(
+ env("HTTP_USER_AGENT" => "Mozilla/5.0 AppleWebKit/605.1.15 Mobile/15E148 DiscourseHub)"),
+ ["200", { "Content-Type" => "text/html" }],
+ 0.1,
+ )
Middleware::RequestTracker.log_request(data)
@@ -155,24 +186,35 @@ RSpec.describe Middleware::RequestTracker do
context "when ignoring anonymous page views" do
let(:anon_data) do
- Middleware::RequestTracker.get_data(env(
- "HTTP_USER_AGENT" => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36"
- ), ["200", { "Content-Type" => 'text/html' }], 0.1)
+ Middleware::RequestTracker.get_data(
+ env(
+ "HTTP_USER_AGENT" =>
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36",
+ ),
+ ["200", { "Content-Type" => "text/html" }],
+ 0.1,
+ )
end
let(:logged_in_data) do
user = Fabricate(:user, active: true)
token = UserAuthToken.generate!(user_id: user.id)
- cookie = create_auth_cookie(
- token: token.unhashed_auth_token,
- user_id: user.id,
- trust_level: user.trust_level,
- issued_at: 5.minutes.ago
+ cookie =
+ create_auth_cookie(
+ token: token.unhashed_auth_token,
+ user_id: user.id,
+ trust_level: user.trust_level,
+ issued_at: 5.minutes.ago,
+ )
+ Middleware::RequestTracker.get_data(
+ env(
+ "HTTP_USER_AGENT" =>
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36",
+ "HTTP_COOKIE" => "_t=#{cookie};",
+ ),
+ ["200", { "Content-Type" => "text/html" }],
+ 0.1,
)
- Middleware::RequestTracker.get_data(env(
- "HTTP_USER_AGENT" => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36",
- "HTTP_COOKIE" => "_t=#{cookie};"
- ), ["200", { "Content-Type" => 'text/html' }], 0.1)
end
it "does not ignore anonymous requests for public sites" do
@@ -218,17 +260,13 @@ RSpec.describe Middleware::RequestTracker do
# rate limiter tests depend on checks for retry-after
# they can be sensitive to clock skew during test runs
- freeze_time DateTime.parse('2021-01-01 01:00')
+ freeze_time DateTime.parse("2021-01-01 01:00")
end
- after do
- Rails.logger = @orig_logger
- end
+ after { Rails.logger = @orig_logger }
let :middleware do
- app = lambda do |env|
- [200, {}, ["OK"]]
- end
+ app = lambda { |env| [200, {}, ["OK"]] }
Middleware::RequestTracker.new(app)
end
@@ -245,10 +283,21 @@ RSpec.describe Middleware::RequestTracker do
it "blocks private IPs if not skipped" do
global_setting :max_reqs_per_ip_per_10_seconds, 1
- global_setting :max_reqs_per_ip_mode, 'warn+block'
+ global_setting :max_reqs_per_ip_mode, "warn+block"
global_setting :max_reqs_rate_limit_on_private, true
- addresses = %w[127.1.2.3 127.0.0.2 192.168.1.2 10.0.1.2 172.16.9.8 172.19.1.2 172.20.9.8 172.29.1.2 172.30.9.8 172.31.1.2]
+ addresses = %w[
+ 127.1.2.3
+ 127.0.0.2
+ 192.168.1.2
+ 10.0.1.2
+ 172.16.9.8
+ 172.19.1.2
+ 172.20.9.8
+ 172.29.1.2
+ 172.30.9.8
+ 172.31.1.2
+ ]
warn_count = 1
addresses.each do |addr|
env1 = env("REMOTE_ADDR" => addr)
@@ -256,7 +305,9 @@ RSpec.describe Middleware::RequestTracker do
status, _ = middleware.call(env1)
status, _ = middleware.call(env1)
- expect(@fake_logger.warnings.count { |w| w.include?("Global IP rate limit exceeded") }).to eq(warn_count)
+ expect(
+ @fake_logger.warnings.count { |w| w.include?("Global IP rate limit exceeded") },
+ ).to eq(warn_count)
expect(status).to eq(429)
warn_count += 1
end
@@ -264,7 +315,7 @@ RSpec.describe Middleware::RequestTracker do
it "blocks if the ip isn't static skipped" do
global_setting :max_reqs_per_ip_per_10_seconds, 1
- global_setting :max_reqs_per_ip_mode, 'block'
+ global_setting :max_reqs_per_ip_mode, "block"
env1 = env("REMOTE_ADDR" => "1.1.1.1")
status, _ = middleware.call(env1)
@@ -273,9 +324,13 @@ RSpec.describe Middleware::RequestTracker do
end
it "doesn't block if rate limiter is enabled but IP is on the static exception list" do
- stub_const(Middleware::RequestTracker, "STATIC_IP_SKIPPER", "177.33.14.73 191.209.88.192/30"&.split&.map { |ip| IPAddr.new(ip) }) do
+ stub_const(
+ Middleware::RequestTracker,
+ "STATIC_IP_SKIPPER",
+ "177.33.14.73 191.209.88.192/30"&.split&.map { |ip| IPAddr.new(ip) },
+ ) do
global_setting :max_reqs_per_ip_per_10_seconds, 1
- global_setting :max_reqs_per_ip_mode, 'block'
+ global_setting :max_reqs_per_ip_mode, "block"
env1 = env("REMOTE_ADDR" => "177.33.14.73")
env2 = env("REMOTE_ADDR" => "191.209.88.194")
@@ -296,16 +351,12 @@ RSpec.describe Middleware::RequestTracker do
describe "register_ip_skipper" do
before do
- Middleware::RequestTracker.register_ip_skipper do |ip|
- ip == "1.1.1.2"
- end
+ Middleware::RequestTracker.register_ip_skipper { |ip| ip == "1.1.1.2" }
global_setting :max_reqs_per_ip_per_10_seconds, 1
- global_setting :max_reqs_per_ip_mode, 'block'
+ global_setting :max_reqs_per_ip_mode, "block"
end
- after do
- Middleware::RequestTracker.unregister_ip_skipper
- end
+ after { Middleware::RequestTracker.unregister_ip_skipper }
it "won't block if the ip is skipped" do
env1 = env("REMOTE_ADDR" => "1.1.1.2")
@@ -324,47 +375,64 @@ RSpec.describe Middleware::RequestTracker do
it "does nothing for private IPs if skipped" do
global_setting :max_reqs_per_ip_per_10_seconds, 1
- global_setting :max_reqs_per_ip_mode, 'warn+block'
+ global_setting :max_reqs_per_ip_mode, "warn+block"
global_setting :max_reqs_rate_limit_on_private, false
- addresses = %w[127.1.2.3 127.0.3.1 192.168.1.2 10.0.1.2 172.16.9.8 172.19.1.2 172.20.9.8 172.29.1.2 172.30.9.8 172.31.1.2]
+ addresses = %w[
+ 127.1.2.3
+ 127.0.3.1
+ 192.168.1.2
+ 10.0.1.2
+ 172.16.9.8
+ 172.19.1.2
+ 172.20.9.8
+ 172.29.1.2
+ 172.30.9.8
+ 172.31.1.2
+ ]
addresses.each do |addr|
env1 = env("REMOTE_ADDR" => addr)
status, _ = middleware.call(env1)
status, _ = middleware.call(env1)
- expect(@fake_logger.warnings.count { |w| w.include?("Global IP rate limit exceeded") }).to eq(0)
+ expect(
+ @fake_logger.warnings.count { |w| w.include?("Global IP rate limit exceeded") },
+ ).to eq(0)
expect(status).to eq(200)
end
end
it "does warn if rate limiter is enabled via warn+block" do
global_setting :max_reqs_per_ip_per_10_seconds, 1
- global_setting :max_reqs_per_ip_mode, 'warn+block'
+ global_setting :max_reqs_per_ip_mode, "warn+block"
status, _ = middleware.call(env)
status, headers = middleware.call(env)
- expect(@fake_logger.warnings.count { |w| w.include?("Global IP rate limit exceeded") }).to eq(1)
+ expect(@fake_logger.warnings.count { |w| w.include?("Global IP rate limit exceeded") }).to eq(
+ 1,
+ )
expect(status).to eq(429)
expect(headers["Retry-After"]).to eq("10")
end
it "does warn if rate limiter is enabled" do
global_setting :max_reqs_per_ip_per_10_seconds, 1
- global_setting :max_reqs_per_ip_mode, 'warn'
+ global_setting :max_reqs_per_ip_mode, "warn"
status, _ = middleware.call(env)
status, _ = middleware.call(env)
- expect(@fake_logger.warnings.count { |w| w.include?("Global IP rate limit exceeded") }).to eq(1)
+ expect(@fake_logger.warnings.count { |w| w.include?("Global IP rate limit exceeded") }).to eq(
+ 1,
+ )
expect(status).to eq(200)
end
it "allows assets for more requests" do
global_setting :max_reqs_per_ip_per_10_seconds, 1
- global_setting :max_reqs_per_ip_mode, 'block'
+ global_setting :max_reqs_per_ip_mode, "block"
global_setting :max_asset_reqs_per_ip_per_10_seconds, 3
env1 = env("REMOTE_ADDR" => "1.1.1.1", "DISCOURSE_IS_ASSET_PATH" => 1)
@@ -388,7 +456,7 @@ RSpec.describe Middleware::RequestTracker do
it "does block if rate limiter is enabled" do
global_setting :max_reqs_per_ip_per_10_seconds, 1
- global_setting :max_reqs_per_ip_mode, 'block'
+ global_setting :max_reqs_per_ip_mode, "block"
env1 = env("REMOTE_ADDR" => "1.1.1.1")
env2 = env("REMOTE_ADDR" => "1.1.1.2")
@@ -408,10 +476,11 @@ RSpec.describe Middleware::RequestTracker do
it "is included when the requests-per-10-seconds limit is reached" do
global_setting :max_reqs_per_ip_per_10_seconds, 1
called = 0
- app = lambda do |_|
- called += 1
- [200, {}, ["OK"]]
- end
+ app =
+ lambda do |_|
+ called += 1
+ [200, {}, ["OK"]]
+ end
env = env("REMOTE_ADDR" => "1.1.1.1")
middleware = Middleware::RequestTracker.new(app)
status, = middleware.call(env)
@@ -430,10 +499,11 @@ RSpec.describe Middleware::RequestTracker do
it "is included when the requests-per-minute limit is reached" do
global_setting :max_reqs_per_ip_per_minute, 1
called = 0
- app = lambda do |_|
- called += 1
- [200, {}, ["OK"]]
- end
+ app =
+ lambda do |_|
+ called += 1
+ [200, {}, ["OK"]]
+ end
env = env("REMOTE_ADDR" => "1.1.1.1")
middleware = Middleware::RequestTracker.new(app)
status, = middleware.call(env)
@@ -452,11 +522,12 @@ RSpec.describe Middleware::RequestTracker do
it "is included when the assets-requests-per-10-seconds limit is reached" do
global_setting :max_asset_reqs_per_ip_per_10_seconds, 1
called = 0
- app = lambda do |env|
- called += 1
- env["DISCOURSE_IS_ASSET_PATH"] = true
- [200, {}, ["OK"]]
- end
+ app =
+ lambda do |env|
+ called += 1
+ env["DISCOURSE_IS_ASSET_PATH"] = true
+ [200, {}, ["OK"]]
+ end
env = env("REMOTE_ADDR" => "1.1.1.1")
middleware = Middleware::RequestTracker.new(app)
status, = middleware.call(env)
@@ -477,23 +548,26 @@ RSpec.describe Middleware::RequestTracker do
global_setting :max_reqs_per_ip_per_minute, 1
global_setting :skip_per_ip_rate_limit_trust_level, 3
- envs = 3.times.map do |n|
- user = Fabricate(:user, trust_level: 3)
- token = UserAuthToken.generate!(user_id: user.id)
- cookie = create_auth_cookie(
- token: token.unhashed_auth_token,
- user_id: user.id,
- trust_level: user.trust_level,
- issued_at: 5.minutes.ago
- )
- env("HTTP_COOKIE" => "_t=#{cookie}", "REMOTE_ADDR" => "1.1.1.1")
- end
+ envs =
+ 3.times.map do |n|
+ user = Fabricate(:user, trust_level: 3)
+ token = UserAuthToken.generate!(user_id: user.id)
+ cookie =
+ create_auth_cookie(
+ token: token.unhashed_auth_token,
+ user_id: user.id,
+ trust_level: user.trust_level,
+ issued_at: 5.minutes.ago,
+ )
+ env("HTTP_COOKIE" => "_t=#{cookie}", "REMOTE_ADDR" => "1.1.1.1")
+ end
called = 0
- app = lambda do |env|
- called += 1
- [200, {}, ["OK"]]
- end
+ app =
+ lambda do |env|
+ called += 1
+ [200, {}, ["OK"]]
+ end
envs.each do |env|
middleware = Middleware::RequestTracker.new(app)
status, = middleware.call(env)
@@ -517,19 +591,21 @@ RSpec.describe Middleware::RequestTracker do
global_setting :skip_per_ip_rate_limit_trust_level, 3
user = Fabricate(:user, trust_level: 3)
token = UserAuthToken.generate!(user_id: user.id)
- cookie = create_auth_cookie(
- token: token.unhashed_auth_token,
- user_id: user.id,
- trust_level: user.trust_level,
- issued_at: 5.minutes.ago
- )
+ cookie =
+ create_auth_cookie(
+ token: token.unhashed_auth_token,
+ user_id: user.id,
+ trust_level: user.trust_level,
+ issued_at: 5.minutes.ago,
+ )
env = env("HTTP_COOKIE" => "_t=#{cookie}", "REMOTE_ADDR" => "1.1.1.1")
called = 0
- app = lambda do |_|
- called += 1
- [200, {}, ["OK"]]
- end
+ app =
+ lambda do |_|
+ called += 1
+ [200, {}, ["OK"]]
+ end
freeze_time(12.minutes.from_now) do
middleware = Middleware::RequestTracker.new(app)
status, = middleware.call(env)
@@ -549,20 +625,22 @@ RSpec.describe Middleware::RequestTracker do
global_setting :skip_per_ip_rate_limit_trust_level, 3
user = Fabricate(:user, trust_level: 3)
token = UserAuthToken.generate!(user_id: user.id)
- cookie = create_auth_cookie(
- token: token.unhashed_auth_token,
- user_id: user.id,
- trust_level: user.trust_level,
- issued_at: Time.zone.now
- )
+ cookie =
+ create_auth_cookie(
+ token: token.unhashed_auth_token,
+ user_id: user.id,
+ trust_level: user.trust_level,
+ issued_at: Time.zone.now,
+ )
cookie = swap_2_different_characters(cookie)
env = env("HTTP_COOKIE" => "_t=#{cookie}", "REMOTE_ADDR" => "1.1.1.1")
called = 0
- app = lambda do |_|
- called += 1
- [200, {}, ["OK"]]
- end
+ app =
+ lambda do |_|
+ called += 1
+ [200, {}, ["OK"]]
+ end
middleware = Middleware::RequestTracker.new(app)
status, = middleware.call(env)
@@ -579,30 +657,22 @@ RSpec.describe Middleware::RequestTracker do
describe "callbacks" do
def app(result, sql_calls: 0, redis_calls: 0)
lambda do |env|
- sql_calls.times do
- User.where(id: -100).pluck(:id)
- end
- redis_calls.times do
- Discourse.redis.get("x")
- end
+ sql_calls.times { User.where(id: -100).pluck(:id) }
+ redis_calls.times { Discourse.redis.get("x") }
result
end
end
let(:logger) do
- ->(env, data) do
+ ->(env, data) {
@env = env
@data = data
- end
+ }
end
- before do
- Middleware::RequestTracker.register_detailed_request_logger(logger)
- end
+ before { Middleware::RequestTracker.register_detailed_request_logger(logger) }
- after do
- Middleware::RequestTracker.unregister_detailed_request_logger(logger)
- end
+ after { Middleware::RequestTracker.unregister_detailed_request_logger(logger) }
it "can report data from anon cache" do
cache = Middleware::AnonymousCache.new(app([200, {}, ["i am a thing"]]))
@@ -610,16 +680,24 @@ RSpec.describe Middleware::RequestTracker do
uri = "/path?#{SecureRandom.hex}"
- request_params = {
- "a" => "b",
- "action" => "bob",
- "controller" => "jane"
- }
+ request_params = { "a" => "b", "action" => "bob", "controller" => "jane" }
- tracker.call(env("REQUEST_URI" => uri, "ANON_CACHE_DURATION" => 60, "action_dispatch.request.parameters" => request_params))
+ tracker.call(
+ env(
+ "REQUEST_URI" => uri,
+ "ANON_CACHE_DURATION" => 60,
+ "action_dispatch.request.parameters" => request_params,
+ ),
+ )
expect(@data[:cache]).to eq("skip")
- tracker.call(env("REQUEST_URI" => uri, "ANON_CACHE_DURATION" => 60, "action_dispatch.request.parameters" => request_params))
+ tracker.call(
+ env(
+ "REQUEST_URI" => uri,
+ "ANON_CACHE_DURATION" => 60,
+ "action_dispatch.request.parameters" => request_params,
+ ),
+ )
expect(@data[:cache]).to eq("store")
tracker.call(env("REQUEST_URI" => uri, "ANON_CACHE_DURATION" => 60))
@@ -678,7 +756,7 @@ RSpec.describe Middleware::RequestTracker do
expect(@data[:is_background]).to eq(true)
expect(@data[:background_type]).to eq("message-bus-dlp")
- tracker.call(env("HTTP_DONT_CHUNK" => "True", path: "/message-bus/abcde/poll"))
+ tracker.call(env("HTTP_DONT_CHUNK" => "True", :path => "/message-bus/abcde/poll"))
expect(@data[:is_background]).to eq(true)
expect(@data[:background_type]).to eq("message-bus-dontchunk")
end
diff --git a/spec/lib/migration/column_dropper_spec.rb b/spec/lib/migration/column_dropper_spec.rb
index 2684bf17688..d5a42177a39 100644
--- a/spec/lib/migration/column_dropper_spec.rb
+++ b/spec/lib/migration/column_dropper_spec.rb
@@ -13,30 +13,22 @@ RSpec.describe Migration::ColumnDropper do
end
describe ".execute_drop" do
- let(:columns) { %w{junk junk2} }
+ let(:columns) { %w[junk junk2] }
- before do
- columns.each do |column|
- DB.exec("ALTER TABLE topics ADD COLUMN #{column} int")
- end
- end
+ before { columns.each { |column| DB.exec("ALTER TABLE topics ADD COLUMN #{column} int") } }
after do
- columns.each do |column|
- DB.exec("ALTER TABLE topics DROP COLUMN IF EXISTS #{column}")
- end
+ columns.each { |column| DB.exec("ALTER TABLE topics DROP COLUMN IF EXISTS #{column}") }
end
it "drops the columns" do
Migration::ColumnDropper.execute_drop("topics", columns)
- columns.each do |column|
- expect(has_column?('topics', column)).to eq(false)
- end
+ columns.each { |column| expect(has_column?("topics", column)).to eq(false) }
end
end
- describe '.mark_readonly' do
+ describe ".mark_readonly" do
let(:table_name) { "table_with_readonly_column" }
before do
@@ -47,7 +39,7 @@ RSpec.describe Migration::ColumnDropper do
VALUES (1, 'something@email.com');
SQL
- Migration::ColumnDropper.mark_readonly(table_name, 'email')
+ Migration::ColumnDropper.mark_readonly(table_name, "email")
end
after do
@@ -55,21 +47,21 @@ RSpec.describe Migration::ColumnDropper do
DB.exec <<~SQL
DROP TABLE IF EXISTS #{table_name};
- DROP FUNCTION IF EXISTS #{Migration::BaseDropper.readonly_function_name(table_name, 'email')} CASCADE;
+ DROP FUNCTION IF EXISTS #{Migration::BaseDropper.readonly_function_name(table_name, "email")} CASCADE;
SQL
end
- it 'should be droppable' do
- Migration::ColumnDropper.execute_drop(table_name, ['email'])
+ it "should be droppable" do
+ Migration::ColumnDropper.execute_drop(table_name, ["email"])
- expect(has_trigger?(Migration::BaseDropper.readonly_trigger_name(
- table_name, 'email'
- ))).to eq(false)
+ expect(has_trigger?(Migration::BaseDropper.readonly_trigger_name(table_name, "email"))).to eq(
+ false,
+ )
- expect(has_column?(table_name, 'email')).to eq(false)
+ expect(has_column?(table_name, "email")).to eq(false)
end
- it 'should prevent updates to the readonly column' do
+ it "should prevent updates to the readonly column" do
begin
DB.exec <<~SQL
UPDATE #{table_name}
@@ -79,46 +71,39 @@ RSpec.describe Migration::ColumnDropper do
rescue PG::RaiseException => e
[
"Discourse: email in #{table_name} is readonly",
- 'discourse_functions.raise_table_with_readonly_column_email_readonly()'
- ].each do |message|
- expect(e.message).to include(message)
- end
+ "discourse_functions.raise_table_with_readonly_column_email_readonly()",
+ ].each { |message| expect(e.message).to include(message) }
end
end
- it 'should allow updates to the other columns' do
+ it "should allow updates to the other columns" do
DB.exec <<~SQL
UPDATE #{table_name}
SET topic_id = 2
WHERE topic_id = 1
SQL
- expect(
- DB.query("SELECT * FROM #{table_name};").first.values
- ).to include 2, "something@email.com"
+ expect(DB.query("SELECT * FROM #{table_name};").first.values).to include 2,
+ "something@email.com"
end
- it 'should prevent insertions to the readonly column' do
- expect do
- ActiveRecord::Base.connection.raw_connection.exec <<~SQL
+ it "should prevent insertions to the readonly column" do
+ expect do ActiveRecord::Base.connection.raw_connection.exec <<~SQL end.to raise_error(
INSERT INTO #{table_name} (topic_id, email)
VALUES (2, 'something@email.com');
SQL
- end.to raise_error(
PG::RaiseException,
- /Discourse: email in table_with_readonly_column is readonly/
+ /Discourse: email in table_with_readonly_column is readonly/,
)
end
- it 'should allow insertions to the other columns' do
+ it "should allow insertions to the other columns" do
DB.exec <<~SQL
INSERT INTO #{table_name} (topic_id)
VALUES (2);
SQL
- expect(
- DB.query_single("SELECT topic_id FROM #{table_name} WHERE topic_id = 2")
- ).to eq([2])
+ expect(DB.query_single("SELECT topic_id FROM #{table_name} WHERE topic_id = 2")).to eq([2])
end
end
end
diff --git a/spec/lib/migration/safe_migrate_spec.rb b/spec/lib/migration/safe_migrate_spec.rb
index a0c8e736cda..06c15e985b3 100644
--- a/spec/lib/migration/safe_migrate_spec.rb
+++ b/spec/lib/migration/safe_migrate_spec.rb
@@ -1,9 +1,7 @@
# frozen_string_literal: true
RSpec.describe Migration::SafeMigrate do
- before do
- Migration::SafeMigrate::SafeMigration.disable_safe!
- end
+ before { Migration::SafeMigrate::SafeMigration.disable_safe! }
after do
Migration::SafeMigrate.disable!
@@ -12,7 +10,12 @@ RSpec.describe Migration::SafeMigrate do
def migrate_up(path)
migrations = ActiveRecord::MigrationContext.new(path, ActiveRecord::SchemaMigration).migrations
- ActiveRecord::Migrator.new(:up, migrations, ActiveRecord::SchemaMigration, migrations.first.version).run
+ ActiveRecord::Migrator.new(
+ :up,
+ migrations,
+ ActiveRecord::SchemaMigration,
+ migrations.first.version,
+ ).run
end
it "bans all table removal" do
@@ -20,11 +23,7 @@ RSpec.describe Migration::SafeMigrate do
path = File.expand_path "#{Rails.root}/spec/fixtures/db/migrate/drop_table"
- output = capture_stdout do
- expect do
- migrate_up(path)
- end.to raise_error(StandardError)
- end
+ output = capture_stdout { expect do migrate_up(path) end.to raise_error(StandardError) }
expect(output).to include("rails g post_migration")
@@ -37,11 +36,7 @@ RSpec.describe Migration::SafeMigrate do
path = File.expand_path "#{Rails.root}/spec/fixtures/db/migrate/rename_table"
- output = capture_stdout do
- expect do
- migrate_up(path)
- end.to raise_error(StandardError)
- end
+ output = capture_stdout { expect do migrate_up(path) end.to raise_error(StandardError) }
expect { User.first }.not_to raise_error
expect(User.first).not_to eq(nil)
@@ -54,11 +49,7 @@ RSpec.describe Migration::SafeMigrate do
path = File.expand_path "#{Rails.root}/spec/fixtures/db/migrate/remove_column"
- output = capture_stdout do
- expect do
- migrate_up(path)
- end.to raise_error(StandardError)
- end
+ output = capture_stdout { expect do migrate_up(path) end.to raise_error(StandardError) }
expect(output).to include("rails g post_migration")
@@ -71,11 +62,7 @@ RSpec.describe Migration::SafeMigrate do
path = File.expand_path "#{Rails.root}/spec/fixtures/db/migrate/rename_column"
- output = capture_stdout do
- expect do
- migrate_up(path)
- end.to raise_error(StandardError)
- end
+ output = capture_stdout { expect do migrate_up(path) end.to raise_error(StandardError) }
expect(output).to include("rails g post_migration")
@@ -89,34 +76,28 @@ RSpec.describe Migration::SafeMigrate do
path = File.expand_path "#{Rails.root}/spec/fixtures/db/migrate/drop_table"
- output = capture_stdout do
- migrate_up(path)
- end
+ output = capture_stdout { migrate_up(path) }
expect(output).to include("drop_table(:email_logs)")
end
- describe 'for a post deployment migration' do
- it 'should not ban unsafe migrations using up' do
+ describe "for a post deployment migration" do
+ it "should not ban unsafe migrations using up" do
Migration::SafeMigrate::SafeMigration.enable_safe!
path = File.expand_path "#{Rails.root}/spec/fixtures/db/post_migrate/drop_table"
- output = capture_stdout do
- migrate_up(path)
- end
+ output = capture_stdout { migrate_up(path) }
expect(output).to include("drop_table(:email_logs)")
end
- it 'should not ban unsafe migrations using change' do
+ it "should not ban unsafe migrations using change" do
Migration::SafeMigrate::SafeMigration.enable_safe!
path = File.expand_path "#{Rails.root}/spec/fixtures/db/post_migrate/change"
- output = capture_stdout do
- migrate_up(path)
- end
+ output = capture_stdout { migrate_up(path) }
expect(output).to include("drop_table(:email_logs)")
end
diff --git a/spec/lib/migration/table_dropper_spec.rb b/spec/lib/migration/table_dropper_spec.rb
index 535e67388a0..6b15603c1c4 100644
--- a/spec/lib/migration/table_dropper_spec.rb
+++ b/spec/lib/migration/table_dropper_spec.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
RSpec.describe Migration::TableDropper do
-
def table_exists?(table_name)
DB.exec(<<~SQL) > 0
SELECT 1
@@ -11,7 +10,7 @@ RSpec.describe Migration::TableDropper do
SQL
end
- def function_exists?(function_name, schema_name = 'public')
+ def function_exists?(function_name, schema_name = "public")
DB.exec(<<~SQL) > 0
SELECT 1
FROM information_schema.routines
@@ -21,7 +20,7 @@ RSpec.describe Migration::TableDropper do
SQL
end
- let(:table_name) { 'table_with_old_name' }
+ let(:table_name) { "table_with_old_name" }
before do
DB.exec "CREATE TABLE #{table_name} (topic_id INTEGER)"
@@ -40,9 +39,7 @@ RSpec.describe Migration::TableDropper do
end
describe ".readonly_only_table" do
- before do
- Migration::TableDropper.read_only_table(table_name)
- end
+ before { Migration::TableDropper.read_only_table(table_name) }
after do
ActiveRecord::Base.connection.reset!
@@ -53,12 +50,10 @@ RSpec.describe Migration::TableDropper do
SQL
end
- it 'should be droppable' do
+ it "should be droppable" do
Migration::TableDropper.execute_drop(table_name)
- expect(has_trigger?(Migration::BaseDropper.readonly_trigger_name(
- table_name
- ))).to eq(false)
+ expect(has_trigger?(Migration::BaseDropper.readonly_trigger_name(table_name))).to eq(false)
expect(table_exists?(table_name)).to eq(false)
end
@@ -66,14 +61,13 @@ RSpec.describe Migration::TableDropper do
it "should drop the read_only function" do
Migration::TableDropper.execute_drop(table_name)
- schema_name, function_name = Migration::BaseDropper
- .readonly_function_name(table_name)
- .delete_suffix('()').split('.')
+ schema_name, function_name =
+ Migration::BaseDropper.readonly_function_name(table_name).delete_suffix("()").split(".")
expect(function_exists?(function_name, schema_name)).to eq(false)
end
- it 'should prevent insertions to the table' do
+ it "should prevent insertions to the table" do
begin
DB.exec <<~SQL
INSERT INTO #{table_name} (topic_id) VALUES (2)
@@ -81,10 +75,8 @@ RSpec.describe Migration::TableDropper do
rescue PG::RaiseException => e
[
"Discourse: #{table_name} is read only",
- 'discourse_functions.raise_table_with_old_name_readonly()'
- ].each do |message|
- expect(e.message).to include(message)
- end
+ "discourse_functions.raise_table_with_old_name_readonly()",
+ ].each { |message| expect(e.message).to include(message) }
end
end
end
diff --git a/spec/lib/mini_sql_multisite_connection_spec.rb b/spec/lib/mini_sql_multisite_connection_spec.rb
index 2a30ac161bd..5a2b32fa500 100644
--- a/spec/lib/mini_sql_multisite_connection_spec.rb
+++ b/spec/lib/mini_sql_multisite_connection_spec.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
RSpec.describe MiniSqlMultisiteConnection do
-
describe "after_commit" do
it "works for 'fake' (joinable) transactions" do
outputString = "1"
@@ -28,14 +27,14 @@ RSpec.describe MiniSqlMultisiteConnection do
ActiveRecord::Base.transaction(requires_new: true, joinable: false) do
outputString += "2"
DB.exec("SELECT 1")
- ActiveRecord::Base.transaction(requires_new: true) do
- DB.exec("SELECT 2")
- outputString += "3"
- DB.after_commit { outputString += "6" }
- outputString += "4"
- end
- DB.after_commit { outputString += "7" }
- outputString += "5"
+ ActiveRecord::Base.transaction(requires_new: true) do
+ DB.exec("SELECT 2")
+ outputString += "3"
+ DB.after_commit { outputString += "6" }
+ outputString += "4"
+ end
+ DB.after_commit { outputString += "7" }
+ outputString += "5"
end
expect(outputString).to eq("1234567")
@@ -47,9 +46,7 @@ RSpec.describe MiniSqlMultisiteConnection do
ActiveRecord::Base.transaction do
outputString += "2"
- DB.after_commit do
- outputString += "4"
- end
+ DB.after_commit { outputString += "4" }
outputString += "3"
@@ -62,9 +59,7 @@ RSpec.describe MiniSqlMultisiteConnection do
it "runs immediately if there is no transaction" do
outputString = "1"
- DB.after_commit do
- outputString += "2"
- end
+ DB.after_commit { outputString += "2" }
outputString += "3"
@@ -75,7 +70,5 @@ RSpec.describe MiniSqlMultisiteConnection do
DB.prepared.query("SELECT ?", 1)
DB.prepared.query("SELECT ?", 2)
end
-
end
-
end
diff --git a/spec/lib/mobile_detection_spec.rb b/spec/lib/mobile_detection_spec.rb
index 5267383150d..853fe24b1be 100644
--- a/spec/lib/mobile_detection_spec.rb
+++ b/spec/lib/mobile_detection_spec.rb
@@ -43,5 +43,4 @@ Mozilla/5.0 (iPhone; CPU iPhone OS 14_8 like Mac OS X) AppleWebKit/605.1.15 (KHT
expect(MobileDetection.modern_mobile_device?(agent)).to eq(false)
end
end
-
end
diff --git a/spec/lib/new_post_manager_spec.rb b/spec/lib/new_post_manager_spec.rb
index c602df9a528..7edc8c61080 100644
--- a/spec/lib/new_post_manager_spec.rb
+++ b/spec/lib/new_post_manager_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'new_post_manager'
+require "new_post_manager"
RSpec.describe NewPostManager do
fab!(:user) { Fabricate(:user) }
@@ -8,7 +8,7 @@ RSpec.describe NewPostManager do
describe "default action" do
it "creates the post by default" do
- manager = NewPostManager.new(user, raw: 'this is a new post', topic_id: topic.id)
+ manager = NewPostManager.new(user, raw: "this is a new post", topic_id: topic.id)
result = manager.perform
expect(result.action).to eq(:create_post)
@@ -25,11 +25,14 @@ RSpec.describe NewPostManager do
Group.refresh_automatic_groups!
SiteSetting.approve_unless_trust_level = 4
- manager = NewPostManager.new(user,
- raw: 'this is a new post',
- title: 'this is a new title',
- archetype: Archetype.private_message,
- target_usernames: other_user.username)
+ manager =
+ NewPostManager.new(
+ user,
+ raw: "this is a new post",
+ title: "this is a new title",
+ archetype: Archetype.private_message,
+ target_usernames: other_user.username,
+ )
result = manager.perform
@@ -40,9 +43,7 @@ RSpec.describe NewPostManager do
expect(result.post).to be_a(Post)
# It doesn't enqueue replies to the private message either
- manager = NewPostManager.new(user,
- raw: 'this is a new reply',
- topic_id: result.post.topic_id)
+ manager = NewPostManager.new(user, raw: "this is a new reply", topic_id: result.post.topic_id)
result = manager.perform
@@ -62,13 +63,14 @@ RSpec.describe NewPostManager do
category.custom_fields[Category::REQUIRE_TOPIC_APPROVAL] = true
category.save!
- manager = NewPostManager.new(
- user,
- raw: 'this is a new post',
- title: 'this is a new post',
- category: category.id,
- tags: [tag1.name, tag3.name]
- )
+ manager =
+ NewPostManager.new(
+ user,
+ raw: "this is a new post",
+ title: "this is a new post",
+ category: category.id,
+ tags: [tag1.name, tag3.name],
+ )
result = manager.perform
expect(result.success?).to eq(false)
expect(result.reviewable.persisted?).to eq(false)
@@ -77,17 +79,18 @@ RSpec.describe NewPostManager do
"tags.forbidden.category_does_not_allow_tags",
count: 1,
category: category.name,
- tags: tag3.name
- )
+ tags: tag3.name,
+ ),
)
- manager = NewPostManager.new(
- user,
- raw: 'this is a new post',
- title: 'this is a new post',
- category: category.id,
- tags: [tag2.name, tag3.name]
- )
+ manager =
+ NewPostManager.new(
+ user,
+ raw: "this is a new post",
+ title: "this is a new post",
+ category: category.id,
+ tags: [tag2.name, tag3.name],
+ )
result = manager.perform
expect(result.success?).to eq(false)
expect(result.reviewable.persisted?).to eq(false)
@@ -96,16 +99,16 @@ RSpec.describe NewPostManager do
"tags.forbidden.category_does_not_allow_tags",
count: 1,
category: category.name,
- tags: tag3.name
- )
+ tags: tag3.name,
+ ),
)
end
end
describe "default handler" do
- let(:manager) { NewPostManager.new(user, raw: 'this is new post content', topic_id: topic.id) }
+ let(:manager) { NewPostManager.new(user, raw: "this is new post content", topic_id: topic.id) }
- context 'with the settings zeroed out' do
+ context "with the settings zeroed out" do
before do
SiteSetting.approve_post_count = 0
SiteSetting.approve_unless_trust_level = 0
@@ -118,10 +121,8 @@ RSpec.describe NewPostManager do
end
end
- context 'with basic post/topic count restrictions' do
- before do
- SiteSetting.approve_post_count = 1
- end
+ context "with basic post/topic count restrictions" do
+ before { SiteSetting.approve_post_count = 1 }
it "works with a correct `user_stat.post_count`" do
result = NewPostManager.default_handler(manager)
@@ -144,7 +145,7 @@ RSpec.describe NewPostManager do
end
end
- context 'with a high approval post count and TL0' do
+ context "with a high approval post count and TL0" do
before do
SiteSetting.approve_post_count = 100
topic.user.trust_level = 0
@@ -157,7 +158,7 @@ RSpec.describe NewPostManager do
end
end
- context 'with a high approval post count and TL1' do
+ context "with a high approval post count and TL1" do
before do
SiteSetting.approve_post_count = 100
topic.user.trust_level = 1
@@ -170,7 +171,7 @@ RSpec.describe NewPostManager do
end
end
- context 'with a high approval post count, but TL2' do
+ context "with a high approval post count, but TL2" do
before do
SiteSetting.approve_post_count = 100
user.update!(trust_level: 2)
@@ -182,28 +183,27 @@ RSpec.describe NewPostManager do
end
end
- context 'with a high approval post count and secure category' do
- it 'does not create topic' do
+ context "with a high approval post count and secure category" do
+ it "does not create topic" do
SiteSetting.approve_post_count = 100
user = Fabricate(:user)
category_group = Fabricate(:category_group, permission_type: 2)
Fabricate(:group_user, group: category_group.group, user_id: user.id)
- manager = NewPostManager.new(
- user,
- raw: 'this is a new topic',
- title: "Let's start a new topic!",
- category: category_group.category_id
- )
+ manager =
+ NewPostManager.new(
+ user,
+ raw: "this is a new topic",
+ title: "Let's start a new topic!",
+ category: category_group.category_id,
+ )
expect(manager.perform.errors["base"][0]).to eq(I18n.t("js.errors.reasons.forbidden"))
end
end
- context 'with a high trust level setting' do
- before do
- SiteSetting.approve_unless_trust_level = 4
- end
+ context "with a high trust level setting" do
+ before { SiteSetting.approve_unless_trust_level = 4 }
it "will return an enqueue result" do
result = NewPostManager.default_handler(manager)
expect(NewPostManager.queue_enabled?).to eq(true)
@@ -219,12 +219,13 @@ RSpec.describe NewPostManager do
end
it "will return an enqueue result" do
- npm = NewPostManager.new(
- Fabricate(:user),
- title: 'this is a new topic title',
- raw: "this is the raw content",
- category: Fabricate(:category).id
- )
+ npm =
+ NewPostManager.new(
+ Fabricate(:user),
+ title: "this is a new topic title",
+ raw: "this is the raw content",
+ category: Fabricate(:category).id,
+ )
result = NewPostManager.default_handler(npm)
expect(NewPostManager.queue_enabled?).to eq(true)
@@ -233,7 +234,7 @@ RSpec.describe NewPostManager do
end
end
- context 'with staged moderation setting enabled' do
+ context "with staged moderation setting enabled" do
before do
SiteSetting.approve_unless_staged = true
user.update!(staged: true)
@@ -247,23 +248,19 @@ RSpec.describe NewPostManager do
end
end
- context 'with a high trust level setting for new topics but post responds to existing topic' do
- before do
- SiteSetting.approve_new_topics_unless_trust_level = 4
- end
+ context "with a high trust level setting for new topics but post responds to existing topic" do
+ before { SiteSetting.approve_new_topics_unless_trust_level = 4 }
it "doesn't return a result action" do
result = NewPostManager.default_handler(manager)
expect(result).to eq(nil)
end
end
- context 'with a fast typer' do
- before do
- user.update!(trust_level: 0)
- end
+ context "with a fast typer" do
+ before { user.update!(trust_level: 0) }
it "adds the silence reason in the system locale" do
- manager = build_manager_with('this is new post content')
+ manager = build_manager_with("this is new post content")
I18n.with_locale(:fr) do # Simulate french user
result = NewPostManager.default_handler(manager)
@@ -273,9 +270,9 @@ RSpec.describe NewPostManager do
expect(user.silence_reason).to eq(I18n.t("user.new_user_typed_too_fast", locale: :en))
end
- it 'runs the watched words check before checking if the user is a fast typer' do
+ it "runs the watched words check before checking if the user is a fast typer" do
Fabricate(:watched_word, word: "darn", action: WatchedWord.actions[:require_approval])
- manager = build_manager_with('this is darn new post content')
+ manager = build_manager_with("this is darn new post content")
result = NewPostManager.default_handler(manager)
@@ -288,23 +285,24 @@ RSpec.describe NewPostManager do
end
end
- context 'with media' do
+ context "with media" do
let(:manager_opts) do
{
- raw: 'this is new post content', topic_id: topic.id, first_post_checks: false,
+ raw: "this is new post content",
+ topic_id: topic.id,
+ first_post_checks: false,
image_sizes: {
"http://localhost:3000/uploads/default/original/1X/652fc9667040b1b89dc4d9b061a823ddb3c0cef0.jpeg" => {
- "width" => "500", "height" => "500"
- }
- }
+ "width" => "500",
+ "height" => "500",
+ },
+ },
}
end
- before do
- user.update!(trust_level: 0)
- end
+ before { user.update!(trust_level: 0) }
- it 'queues the post for review because if it contains embedded media.' do
+ it "queues the post for review because if it contains embedded media." do
SiteSetting.review_media_unless_trust_level = 1
manager = NewPostManager.new(user, manager_opts)
@@ -314,7 +312,7 @@ RSpec.describe NewPostManager do
expect(result.reason).to eq(:contains_media)
end
- it 'does not enqueue the post if the poster is a trusted user' do
+ it "does not enqueue the post if the poster is a trusted user" do
SiteSetting.review_media_unless_trust_level = 0
manager = NewPostManager.new(user, manager_opts)
@@ -326,11 +324,11 @@ RSpec.describe NewPostManager do
end
describe "new topic handler" do
- let(:manager) { NewPostManager.new(user, raw: 'this is new topic content', title: 'new topic title') }
- context 'with a high trust level setting for new topics' do
- before do
- SiteSetting.approve_new_topics_unless_trust_level = 4
- end
+ let(:manager) do
+ NewPostManager.new(user, raw: "this is new topic content", title: "new topic title")
+ end
+ context "with a high trust level setting for new topics" do
+ before { SiteSetting.approve_new_topics_unless_trust_level = 4 }
it "will return an enqueue result" do
result = NewPostManager.default_handler(manager)
expect(NewPostManager.queue_enabled?).to eq(true)
@@ -341,9 +339,7 @@ RSpec.describe NewPostManager do
end
describe "extensibility priority" do
- after do
- NewPostManager.clear_handlers!
- end
+ after { NewPostManager.clear_handlers! }
let(:default_handler) { NewPostManager.method(:default_handler) }
@@ -370,32 +366,33 @@ RSpec.describe NewPostManager do
before do
@counter = 0
- @counter_handler = lambda do |manager|
- result = nil
- if manager.args[:raw] == 'this post increases counter'
- @counter += 1
- result = NewPostResult.new(:counter, true)
+ @counter_handler =
+ lambda do |manager|
+ result = nil
+ if manager.args[:raw] == "this post increases counter"
+ @counter += 1
+ result = NewPostResult.new(:counter, true)
+ end
+
+ result
end
- result
- end
-
- @queue_handler = -> (manager) { manager.args[:raw] =~ /queue me/ ? manager.enqueue('default') : nil }
+ @queue_handler = ->(manager) {
+ manager.args[:raw] =~ /queue me/ ? manager.enqueue("default") : nil
+ }
NewPostManager.add_handler(&@counter_handler)
NewPostManager.add_handler(&@queue_handler)
end
- after do
- NewPostManager.clear_handlers!
- end
+ after { NewPostManager.clear_handlers! }
it "has a queue enabled" do
expect(NewPostManager.queue_enabled?).to eq(true)
end
it "calls custom handlers" do
- manager = NewPostManager.new(user, raw: 'this post increases counter', topic_id: topic.id)
+ manager = NewPostManager.new(user, raw: "this post increases counter", topic_id: topic.id)
result = manager.perform
@@ -411,25 +408,26 @@ RSpec.describe NewPostManager do
SiteSetting.min_trust_to_create_tag = 0
SiteSetting.min_trust_level_to_tag_topics = 0
- manager = NewPostManager.new(
- topic.user,
- raw: 'to the handler I say enqueue me!',
- title: 'this is the title of the queued post',
- tags: ['hello', 'world'],
- category: topic.category_id
- )
+ manager =
+ NewPostManager.new(
+ topic.user,
+ raw: "to the handler I say enqueue me!",
+ title: "this is the title of the queued post",
+ tags: %w[hello world],
+ category: topic.category_id,
+ )
result = manager.perform
reviewable = result.reviewable
expect(reviewable).to be_present
- expect(reviewable.payload['title']).to eq('this is the title of the queued post')
+ expect(reviewable.payload["title"]).to eq("this is the title of the queued post")
expect(reviewable.reviewable_scores).to be_present
expect(reviewable.force_review).to eq(true)
expect(reviewable.reviewable_by_moderator?).to eq(true)
expect(reviewable.category).to be_present
- expect(reviewable.payload['tags']).to eq(['hello', 'world'])
+ expect(reviewable.payload["tags"]).to eq(%w[hello world])
expect(result.action).to eq(:enqueued)
expect(result).to be_success
expect(result.pending_count).to eq(1)
@@ -439,11 +437,12 @@ RSpec.describe NewPostManager do
reviewable.perform(Discourse.system_user, :approve_post)
- manager = NewPostManager.new(
- topic.user,
- raw: 'another post by this user queue me',
- topic_id: topic.id
- )
+ manager =
+ NewPostManager.new(
+ topic.user,
+ raw: "another post by this user queue me",
+ topic_id: topic.id,
+ )
result = manager.perform
reviewable = result.reviewable
@@ -453,7 +452,7 @@ RSpec.describe NewPostManager do
end
it "if nothing returns a result it creates a post" do
- manager = NewPostManager.new(user, raw: 'this is a new post', topic_id: topic.id)
+ manager = NewPostManager.new(user, raw: "this is a new post", topic_id: topic.id)
result = manager.perform
@@ -491,41 +490,43 @@ RSpec.describe NewPostManager do
end
end
- context 'when posting in the category requires approval' do
+ context "when posting in the category requires approval" do
let!(:user) { Fabricate(:user) }
let!(:review_group) { Fabricate(:group) }
let!(:category) { Fabricate(:category, reviewable_by_group_id: review_group.id) }
- context 'when new topics require approval' do
+ context "when new topics require approval" do
before do
SiteSetting.tagging_enabled = true
category.custom_fields[Category::REQUIRE_TOPIC_APPROVAL] = true
category.save
end
- it 'enqueues new topics' do
- manager = NewPostManager.new(
- user,
- raw: 'this is a new topic',
- title: "Let's start a new topic!",
- category: category.id
- )
+ it "enqueues new topics" do
+ manager =
+ NewPostManager.new(
+ user,
+ raw: "this is a new topic",
+ title: "Let's start a new topic!",
+ category: category.id,
+ )
result = manager.perform
expect(result.action).to eq(:enqueued)
expect(result.reason).to eq(:category)
end
- it 'does not enqueue the topic when the poster is a category group moderator' do
+ it "does not enqueue the topic when the poster is a category group moderator" do
SiteSetting.enable_category_group_moderation = true
review_group.users << user
- manager = NewPostManager.new(
- user,
- raw: 'this is a new topic',
- title: "Let's start a new topic!",
- category: category.id
- )
+ manager =
+ NewPostManager.new(
+ user,
+ raw: "this is a new topic",
+ title: "Let's start a new topic!",
+ category: category.id,
+ )
result = manager.perform
expect(result.action).to eq(:create_post)
@@ -534,32 +535,34 @@ RSpec.describe NewPostManager do
context "when the category has tagging rules" do
context "when there is a minimum number of tags required for the category" do
- before do
- category.update(minimum_required_tags: 1)
- end
+ before { category.update(minimum_required_tags: 1) }
it "errors when there are no tags provided" do
- manager = NewPostManager.new(
- user,
- raw: 'this is a new topic',
- title: "Let's start a new topic!",
- category: category.id
- )
+ manager =
+ NewPostManager.new(
+ user,
+ raw: "this is a new topic",
+ title: "Let's start a new topic!",
+ category: category.id,
+ )
result = manager.perform
expect(result.action).to eq(:enqueued)
- expect(result.errors.full_messages).to include(I18n.t("tags.minimum_required_tags", count: category.minimum_required_tags))
+ expect(result.errors.full_messages).to include(
+ I18n.t("tags.minimum_required_tags", count: category.minimum_required_tags),
+ )
end
it "enqueues the topic if there are tags provided" do
tag = Fabricate(:tag)
- manager = NewPostManager.new(
- user,
- raw: 'this is a new topic',
- title: "Let's start a new topic!",
- category: category.id,
- tags: tag.name
- )
+ manager =
+ NewPostManager.new(
+ user,
+ raw: "this is a new topic",
+ title: "Let's start a new topic!",
+ category: category.id,
+ tags: tag.name,
+ )
result = manager.perform
expect(result.action).to eq(:enqueued)
@@ -572,16 +575,21 @@ RSpec.describe NewPostManager do
let(:tag) { Fabricate(:tag) }
before do
TagGroupMembership.create(tag: tag, tag_group: tag_group)
- category.update(category_required_tag_groups: [CategoryRequiredTagGroup.new(tag_group: tag_group, min_count: 1)])
+ category.update(
+ category_required_tag_groups: [
+ CategoryRequiredTagGroup.new(tag_group: tag_group, min_count: 1),
+ ],
+ )
end
it "errors when there are no tags from the group provided" do
- manager = NewPostManager.new(
- user,
- raw: 'this is a new topic',
- title: "Let's start a new topic!",
- category: category.id
- )
+ manager =
+ NewPostManager.new(
+ user,
+ raw: "this is a new topic",
+ title: "Let's start a new topic!",
+ category: category.id,
+ )
result = manager.perform
expect(result.action).to eq(:enqueued)
@@ -590,19 +598,20 @@ RSpec.describe NewPostManager do
"tags.required_tags_from_group",
count: category.category_required_tag_groups.first.min_count,
tag_group_name: category.category_required_tag_groups.first.tag_group.name,
- tags: tag.name
- )
+ tags: tag.name,
+ ),
)
end
it "enqueues the topic if there are tags provided" do
- manager = NewPostManager.new(
- user,
- raw: 'this is a new topic',
- title: "Let's start a new topic!",
- category: category.id,
- tags: [tag.name]
- )
+ manager =
+ NewPostManager.new(
+ user,
+ raw: "this is a new topic",
+ title: "Let's start a new topic!",
+ category: category.id,
+ tags: [tag.name],
+ )
result = manager.perform
expect(result.action).to eq(:enqueued)
@@ -612,7 +621,7 @@ RSpec.describe NewPostManager do
end
end
- context 'when new posts require approval' do
+ context "when new posts require approval" do
let!(:topic) { Fabricate(:topic, category: category) }
before do
@@ -620,8 +629,8 @@ RSpec.describe NewPostManager do
category.save
end
- it 'enqueues new posts' do
- manager = NewPostManager.new(user, raw: 'this is a new post', topic_id: topic.id)
+ it "enqueues new posts" do
+ manager = NewPostManager.new(user, raw: "this is a new post", topic_id: topic.id)
result = manager.perform
expect(result.action).to eq(:enqueued)
@@ -630,24 +639,16 @@ RSpec.describe NewPostManager do
it "doesn't blow up with invalid topic_id" do
expect do
- manager = NewPostManager.new(
- user,
- raw: 'this is a new topic',
- topic_id: 97546
- )
+ manager = NewPostManager.new(user, raw: "this is a new topic", topic_id: 97_546)
expect(manager.perform.action).to eq(:create_post)
end.not_to raise_error
end
- it 'does not enqueue the post when the poster is a category group moderator' do
+ it "does not enqueue the post when the poster is a category group moderator" do
SiteSetting.enable_category_group_moderation = true
review_group.users << user
- manager = NewPostManager.new(
- user,
- raw: 'this is a new post',
- topic_id: topic.id
- )
+ manager = NewPostManager.new(user, raw: "this is a new post", topic_id: topic.id)
result = manager.perform
expect(result.action).to eq(:create_post)
@@ -660,24 +661,24 @@ RSpec.describe NewPostManager do
let(:manager) do
NewPostManager.new(
topic.user,
- raw: 'this is emailed content',
+ raw: "this is emailed content",
topic_id: topic.id,
via_email: true,
- raw_email: 'raw email contents'
+ raw_email: "raw email contents",
)
end
- before do
- SiteSetting.approve_post_count = 100
- topic.user.trust_level = 0
- end
+ before do
+ SiteSetting.approve_post_count = 100
+ topic.user.trust_level = 0
+ end
it "will store via_email and raw_email in the enqueued post" do
result = manager.perform
expect(result.action).to eq(:enqueued)
expect(result.reviewable).to be_present
- expect(result.reviewable.payload['via_email']).to eq(true)
- expect(result.reviewable.payload['raw_email']).to eq('raw email contents')
+ expect(result.reviewable.payload["via_email"]).to eq(true)
+ expect(result.reviewable.payload["raw_email"]).to eq("raw email contents")
post = result.reviewable.perform(Discourse.system_user, :approve_post).created_post
expect(post.via_email).to eq(true)
@@ -690,14 +691,15 @@ RSpec.describe NewPostManager do
let(:admin) { Fabricate(:admin) }
it "silences users if its their first post" do
- manager = NewPostManager.new(
- user,
- raw: 'this is emailed content',
- via_email: true,
- raw_email: 'raw email contents',
- email_spam: true,
- first_post_checks: true
- )
+ manager =
+ NewPostManager.new(
+ user,
+ raw: "this is emailed content",
+ via_email: true,
+ raw_email: "raw email contents",
+ email_spam: true,
+ first_post_checks: true,
+ )
result = manager.perform
expect(result.action).to eq(:enqueued)
@@ -705,14 +707,15 @@ RSpec.describe NewPostManager do
end
it "doesn't silence or enqueue exempt users" do
- manager = NewPostManager.new(
- admin,
- raw: 'this is emailed content',
- via_email: true,
- raw_email: 'raw email contents',
- email_spam: true,
- first_post_checks: true
- )
+ manager =
+ NewPostManager.new(
+ admin,
+ raw: "this is emailed content",
+ via_email: true,
+ raw_email: "raw email contents",
+ email_spam: true,
+ first_post_checks: true,
+ )
result = manager.perform
expect(result.action).to eq(:create_post)
@@ -725,14 +728,15 @@ RSpec.describe NewPostManager do
let(:admin) { Fabricate(:admin) }
it "doesn't silence users" do
- manager = NewPostManager.new(
- user,
- raw: 'this is emailed content',
- via_email: true,
- raw_email: 'raw email contents',
- email_auth_res_action: :enqueue,
- first_post_checks: true
- )
+ manager =
+ NewPostManager.new(
+ user,
+ raw: "this is emailed content",
+ via_email: true,
+ raw_email: "raw email contents",
+ email_auth_res_action: :enqueue,
+ first_post_checks: true,
+ )
result = manager.perform
expect(result.action).to eq(:enqueued)
@@ -740,13 +744,14 @@ RSpec.describe NewPostManager do
end
it "still enqueues exempt users" do
- manager = NewPostManager.new(
- admin,
- raw: 'this is emailed content',
- via_email: true,
- raw_email: 'raw email contents',
- email_auth_res_action: :enqueue
- )
+ manager =
+ NewPostManager.new(
+ admin,
+ raw: "this is emailed content",
+ via_email: true,
+ raw_email: "raw email contents",
+ email_auth_res_action: :enqueue,
+ )
result = manager.perform
expect(result.action).to eq(:enqueued)
@@ -756,28 +761,30 @@ RSpec.describe NewPostManager do
describe "private message via email" do
it "doesn't enqueue authentication results failure" do
- manager = NewPostManager.new(
- topic.user,
- raw: 'this is emailed content',
- archetype: Archetype.private_message,
- via_email: true,
- raw_email: 'raw email contents',
- email_auth_res_action: :enqueue
- )
+ manager =
+ NewPostManager.new(
+ topic.user,
+ raw: "this is emailed content",
+ archetype: Archetype.private_message,
+ via_email: true,
+ raw_email: "raw email contents",
+ email_auth_res_action: :enqueue,
+ )
result = manager.perform
expect(result.action).to eq(:create_post)
end
it "doesn't enqueue spam failure" do
- manager = NewPostManager.new(
- topic.user,
- raw: 'this is emailed content',
- archetype: Archetype.private_message,
- via_email: true,
- raw_email: 'raw email contents',
- email_spam: true
- )
+ manager =
+ NewPostManager.new(
+ topic.user,
+ raw: "this is emailed content",
+ archetype: Archetype.private_message,
+ via_email: true,
+ raw_email: "raw email contents",
+ email_spam: true,
+ )
result = manager.perform
expect(result.action).to eq(:create_post)
diff --git a/spec/lib/new_post_result_spec.rb b/spec/lib/new_post_result_spec.rb
index 9e8b2335b5f..360300d10fd 100644
--- a/spec/lib/new_post_result_spec.rb
+++ b/spec/lib/new_post_result_spec.rb
@@ -1,13 +1,11 @@
# frozen_string_literal: true
-require 'new_post_result'
+require "new_post_result"
RSpec.describe NewPostResult do
-
it "fails by default" do
result = NewPostResult.new(:eviltrout)
expect(result.failed?).to eq(true)
expect(result.success?).to eq(false)
end
-
end
diff --git a/spec/lib/onebox/domain_checker_spec.rb b/spec/lib/onebox/domain_checker_spec.rb
index de3d71050a4..0b375363ce8 100644
--- a/spec/lib/onebox/domain_checker_spec.rb
+++ b/spec/lib/onebox/domain_checker_spec.rb
@@ -1,10 +1,8 @@
# frozen_string_literal: true
RSpec.describe Onebox::DomainChecker do
- describe '.is_blocked?' do
- before do
- SiteSetting.blocked_onebox_domains = "api.cat.org|kitten.cloud"
- end
+ describe ".is_blocked?" do
+ before { SiteSetting.blocked_onebox_domains = "api.cat.org|kitten.cloud" }
describe "returns true when entirely matched" do
it { expect(described_class.is_blocked?("api.cat.org")).to be(true) }
diff --git a/spec/lib/onebox/engine/allowlisted_generic_onebox_spec.rb b/spec/lib/onebox/engine/allowlisted_generic_onebox_spec.rb
index 4064fde840a..e7ff04589a8 100644
--- a/spec/lib/onebox/engine/allowlisted_generic_onebox_spec.rb
+++ b/spec/lib/onebox/engine/allowlisted_generic_onebox_spec.rb
@@ -3,23 +3,19 @@
RSpec.describe Onebox::Engine::AllowlistedGenericOnebox do
describe ".===" do
it "matches any domain" do
- expect(described_class === URI('http://foo.bar/resource')).to be(true)
+ expect(described_class === URI("http://foo.bar/resource")).to be(true)
end
it "doesn't match an IP address" do
- expect(described_class === URI('http://1.2.3.4/resource')).to be(false)
- expect(described_class === URI('http://1.2.3.4:1234/resource')).to be(false)
+ expect(described_class === URI("http://1.2.3.4/resource")).to be(false)
+ expect(described_class === URI("http://1.2.3.4:1234/resource")).to be(false)
end
end
- describe 'html_providers' do
+ describe "html_providers" do
class HTMLOnebox < Onebox::Engine::AllowlistedGenericOnebox
def data
- {
- html: 'cool html',
- height: 123,
- provider_name: 'CoolSite',
- }
+ { html: "cool html", height: 123, provider_name: "CoolSite" }
end
end
@@ -29,12 +25,12 @@ RSpec.describe Onebox::Engine::AllowlistedGenericOnebox do
end
it "returns the HMTL when in the `html_providers`" do
- Onebox::Engine::AllowlistedGenericOnebox.html_providers = ['CoolSite']
+ Onebox::Engine::AllowlistedGenericOnebox.html_providers = ["CoolSite"]
expect(HTMLOnebox.new("http://coolsite.com").to_html).to eq "cool html"
end
end
- describe 'rewrites' do
+ describe "rewrites" do
class DummyOnebox < Onebox::Engine::AllowlistedGenericOnebox
def generic_html
"VIDEO "
@@ -43,24 +39,31 @@ RSpec.describe Onebox::Engine::AllowlistedGenericOnebox do
it "doesn't rewrite URLs that arent in the list" do
Onebox::Engine::AllowlistedGenericOnebox.rewrites = []
- expect(DummyOnebox.new("http://youtube.com").to_html).to eq "VIDEO "
+ expect(
+ DummyOnebox.new("http://youtube.com").to_html,
+ ).to eq "VIDEO "
end
it "rewrites URLs when allowlisted" do
- Onebox::Engine::AllowlistedGenericOnebox.rewrites = %w(youtube.com)
- expect(DummyOnebox.new("http://youtube.com").to_html).to eq "VIDEO "
+ Onebox::Engine::AllowlistedGenericOnebox.rewrites = %w[youtube.com]
+ expect(
+ DummyOnebox.new("http://youtube.com").to_html,
+ ).to eq "VIDEO "
end
end
- describe 'oembed_providers' do
+ describe "oembed_providers" do
let(:url) { "http://www.meetup.com/Toronto-Ember-JS-Meetup/events/219939537" }
before do
- stub_request(:get, url).to_return(status: 200, body: onebox_response('meetup'))
- stub_request(:get, "http://api.meetup.com/oembed?url=#{url}").to_return(status: 200, body: onebox_response('meetup_oembed'))
+ stub_request(:get, url).to_return(status: 200, body: onebox_response("meetup"))
+ stub_request(:get, "http://api.meetup.com/oembed?url=#{url}").to_return(
+ status: 200,
+ body: onebox_response("meetup_oembed"),
+ )
end
- it 'uses the endpoint for the url' do
+ it "uses the endpoint for the url" do
onebox = described_class.new("http://www.meetup.com/Toronto-Ember-JS-Meetup/events/219939537")
expect(onebox.raw).not_to be_nil
expect(onebox.raw[:title]).to eq "February EmberTO Meet-up"
@@ -68,12 +71,15 @@ RSpec.describe Onebox::Engine::AllowlistedGenericOnebox do
end
describe "cookie support" do
- let(:url) { "http://www.dailymail.co.uk/news/article-479146/Brutality-justice-The-truth-tarred-feathered-drug-dealer.html" }
+ let(:url) do
+ "http://www.dailymail.co.uk/news/article-479146/Brutality-justice-The-truth-tarred-feathered-drug-dealer.html"
+ end
it "sends the cookie with the request" do
- stub_request(:get, url)
- .with(headers: { cookie: 'evil=trout' })
- .to_return(status: 200, body: onebox_response('dailymail'))
+ stub_request(:get, url).with(headers: { cookie: "evil=trout" }).to_return(
+ status: 200,
+ body: onebox_response("dailymail"),
+ )
onebox = described_class.new(url)
onebox.options = { cookie: "evil=trout" }
@@ -82,65 +88,86 @@ RSpec.describe Onebox::Engine::AllowlistedGenericOnebox do
end
it "fetches site_name and article_published_time tags" do
- stub_request(:get, url).to_return(status: 200, body: onebox_response('dailymail'))
+ stub_request(:get, url).to_return(status: 200, body: onebox_response("dailymail"))
onebox = described_class.new(url)
expect(onebox.to_html).to include("Mail Online – 8 Aug 14")
end
end
- describe 'canonical link' do
- context 'when using canonical link if available' do
- let(:mobile_url) { "https://m.etsy.com/in-en/listing/87673424/personalized-word-pillow-case-letter" }
- let(:canonical_url) { "https://www.etsy.com/in-en/listing/87673424/personalized-word-pillow-case-letter" }
+ describe "canonical link" do
+ context "when using canonical link if available" do
+ let(:mobile_url) do
+ "https://m.etsy.com/in-en/listing/87673424/personalized-word-pillow-case-letter"
+ end
+ let(:canonical_url) do
+ "https://www.etsy.com/in-en/listing/87673424/personalized-word-pillow-case-letter"
+ end
before do
- stub_request(:get, mobile_url).to_return(status: 200, body: onebox_response('etsy_mobile'))
- stub_request(:get, canonical_url).to_return(status: 200, body: onebox_response('etsy'))
+ stub_request(:get, mobile_url).to_return(status: 200, body: onebox_response("etsy_mobile"))
+ stub_request(:get, canonical_url).to_return(status: 200, body: onebox_response("etsy"))
stub_request(:head, canonical_url).to_return(status: 200, body: "")
end
- it 'fetches opengraph data and price from canonical link' do
+ it "fetches opengraph data and price from canonical link" do
onebox = described_class.new(mobile_url)
expect(onebox.to_html).not_to be_nil
expect(onebox.to_html).to include("images/favicon.ico")
expect(onebox.to_html).to include("Etsy")
expect(onebox.to_html).to include("Personalized Word Pillow Case")
- expect(onebox.to_html).to include("Allow your personality to shine through your decor; this contemporary and modern accent will help you do just that.")
- expect(onebox.to_html).to include("https://i.etsystatic.com/6088772/r/il/719b4b/1631899982/il_570xN.1631899982_2iay.jpg")
+ expect(onebox.to_html).to include(
+ "Allow your personality to shine through your decor; this contemporary and modern accent will help you do just that.",
+ )
+ expect(onebox.to_html).to include(
+ "https://i.etsystatic.com/6088772/r/il/719b4b/1631899982/il_570xN.1631899982_2iay.jpg",
+ )
expect(onebox.to_html).to include("CAD 52.00")
end
end
- context 'when not using canonical link for Discourse topics' do
- let(:discourse_topic_url) { "https://meta.discourse.org/t/congratulations-most-stars-in-2013-github-octoverse/12483" }
- let(:discourse_topic_reply_url) { "https://meta.discourse.org/t/congratulations-most-stars-in-2013-github-octoverse/12483/2" }
+ context "when not using canonical link for Discourse topics" do
+ let(:discourse_topic_url) do
+ "https://meta.discourse.org/t/congratulations-most-stars-in-2013-github-octoverse/12483"
+ end
+ let(:discourse_topic_reply_url) do
+ "https://meta.discourse.org/t/congratulations-most-stars-in-2013-github-octoverse/12483/2"
+ end
before do
- stub_request(:get, discourse_topic_url).to_return(status: 200, body: onebox_response('discourse_topic'))
- stub_request(:get, discourse_topic_reply_url).to_return(status: 200, body: onebox_response('discourse_topic_reply'))
+ stub_request(:get, discourse_topic_url).to_return(
+ status: 200,
+ body: onebox_response("discourse_topic"),
+ )
+ stub_request(:get, discourse_topic_reply_url).to_return(
+ status: 200,
+ body: onebox_response("discourse_topic_reply"),
+ )
end
- it 'fetches opengraph data from original link' do
+ it "fetches opengraph data from original link" do
onebox = described_class.new(discourse_topic_reply_url)
expect(onebox.to_html).not_to be_nil
expect(onebox.to_html).to include("Congratulations, most stars in 2013 GitHub Octoverse!")
- expect(onebox.to_html).to include("Thanks for that link and thank you – and everyone else who is contributing to the project!")
- expect(onebox.to_html).to include("https://d11a6trkgmumsb.cloudfront.net/optimized/2X/d/d063b3b0807377d98695ee08042a9ba0a8c593bd_2_690x362.png")
+ expect(onebox.to_html).to include(
+ "Thanks for that link and thank you – and everyone else who is contributing to the project!",
+ )
+ expect(onebox.to_html).to include(
+ "https://d11a6trkgmumsb.cloudfront.net/optimized/2X/d/d063b3b0807377d98695ee08042a9ba0a8c593bd_2_690x362.png",
+ )
end
end
end
- describe 'to_html' do
- let(:original_link) { "http://www.dailymail.co.uk/pages/live/articles/news/news.html?in_article_id=479146&in_page_id=1770" }
- let(:redirect_link) { 'http://www.dailymail.co.uk/news/article-479146/Brutality-justice-The-truth-tarred-feathered-drug-dealer.html' }
+ describe "to_html" do
+ let(:original_link) do
+ "http://www.dailymail.co.uk/pages/live/articles/news/news.html?in_article_id=479146&in_page_id=1770"
+ end
+ let(:redirect_link) do
+ "http://www.dailymail.co.uk/news/article-479146/Brutality-justice-The-truth-tarred-feathered-drug-dealer.html"
+ end
before do
- stub_request(:get, original_link).to_return(
- status: 301,
- headers: {
- location: redirect_link,
- }
- )
- stub_request(:get, redirect_link).to_return(status: 200, body: onebox_response('dailymail'))
+ stub_request(:get, original_link).to_return(status: 301, headers: { location: redirect_link })
+ stub_request(:get, redirect_link).to_return(status: 200, body: onebox_response("dailymail"))
stub_request(:head, redirect_link).to_return(status: 200, body: "")
end
@@ -163,67 +190,95 @@ RSpec.describe Onebox::Engine::AllowlistedGenericOnebox do
end
end
- describe 'missing description' do
- context 'when working without description if image is present' do
+ describe "missing description" do
+ context "when working without description if image is present" do
before do
- stub_request(:get, "https://edition.cnn.com/2020/05/15/health/gallery/coronavirus-people-adopting-pets-photos/index.html")
- .to_return(status: 200, body: onebox_response('cnn'))
- stub_request(:get, "https://www.cnn.com/2020/05/15/health/gallery/coronavirus-people-adopting-pets-photos/index.html")
- .to_return(status: 200, body: onebox_response('cnn'))
- stub_request(:head, "https://www.cnn.com/2020/05/15/health/gallery/coronavirus-people-adopting-pets-photos/index.html")
- .to_return(status: 200, body: "")
+ stub_request(
+ :get,
+ "https://edition.cnn.com/2020/05/15/health/gallery/coronavirus-people-adopting-pets-photos/index.html",
+ ).to_return(status: 200, body: onebox_response("cnn"))
+ stub_request(
+ :get,
+ "https://www.cnn.com/2020/05/15/health/gallery/coronavirus-people-adopting-pets-photos/index.html",
+ ).to_return(status: 200, body: onebox_response("cnn"))
+ stub_request(
+ :head,
+ "https://www.cnn.com/2020/05/15/health/gallery/coronavirus-people-adopting-pets-photos/index.html",
+ ).to_return(status: 200, body: "")
end
- it 'shows basic onebox' do
- onebox = described_class.new("https://edition.cnn.com/2020/05/15/health/gallery/coronavirus-people-adopting-pets-photos/index.html")
+ it "shows basic onebox" do
+ onebox =
+ described_class.new(
+ "https://edition.cnn.com/2020/05/15/health/gallery/coronavirus-people-adopting-pets-photos/index.html",
+ )
expect(onebox.to_html).not_to be_nil
- expect(onebox.to_html).to include("https://edition.cnn.com/2020/05/15/health/gallery/coronavirus-people-adopting-pets-photos/index.html")
- expect(onebox.to_html).to include("https://cdn.cnn.com/cnnnext/dam/assets/200427093451-10-coronavirus-people-adopting-pets-super-tease.jpg")
- expect(onebox.to_html).to include("People are fostering and adopting pets during the pandemic")
+ expect(onebox.to_html).to include(
+ "https://edition.cnn.com/2020/05/15/health/gallery/coronavirus-people-adopting-pets-photos/index.html",
+ )
+ expect(onebox.to_html).to include(
+ "https://cdn.cnn.com/cnnnext/dam/assets/200427093451-10-coronavirus-people-adopting-pets-super-tease.jpg",
+ )
+ expect(onebox.to_html).to include(
+ "People are fostering and adopting pets during the pandemic",
+ )
end
end
- context 'when using basic meta description when necessary' do
+ context "when using basic meta description when necessary" do
before do
- stub_request(:get, "https://www.reddit.com/r/colors/comments/b4d5xm/literally_nothing_black_edition/")
- .to_return(status: 200, body: onebox_response('reddit_image'))
- stub_request(:get, "https://www.example.com/content")
- .to_return(status: 200, body: onebox_response('basic_description'))
+ stub_request(
+ :get,
+ "https://www.reddit.com/r/colors/comments/b4d5xm/literally_nothing_black_edition/",
+ ).to_return(status: 200, body: onebox_response("reddit_image"))
+ stub_request(:get, "https://www.example.com/content").to_return(
+ status: 200,
+ body: onebox_response("basic_description"),
+ )
end
- it 'uses opengraph tags when present' do
- onebox = described_class.new("https://www.reddit.com/r/colors/comments/b4d5xm/literally_nothing_black_edition/")
+ it "uses opengraph tags when present" do
+ onebox =
+ described_class.new(
+ "https://www.reddit.com/r/colors/comments/b4d5xm/literally_nothing_black_edition/",
+ )
expect(onebox.to_html).to include("4 votes and 1 comment so far on Reddit")
end
- it 'fallback to basic meta description if other description tags are missing' do
+ it "fallback to basic meta description if other description tags are missing" do
onebox = described_class.new("https://www.example.com/content")
expect(onebox.to_html).to include("basic meta description")
end
end
end
- describe 'article html hosts' do
- context 'when returning article_html for hosts in article_html_hosts' do
+ describe "article html hosts" do
+ context "when returning article_html for hosts in article_html_hosts" do
before do
- stub_request(:get, "https://www.imdb.com/title/tt0108002/")
- .to_return(status: 200, body: onebox_response('imdb'))
+ stub_request(:get, "https://www.imdb.com/title/tt0108002/").to_return(
+ status: 200,
+ body: onebox_response("imdb"),
+ )
end
- it 'shows article onebox' do
+ it "shows article onebox" do
onebox = described_class.new("https://www.imdb.com/title/tt0108002/")
expect(onebox.to_html).to include("https://www.imdb.com/title/tt0108002")
- expect(onebox.to_html).to include("https://m.media-amazon.com/images/M/MV5BZGUzMDU1YmQtMzBkOS00MTNmLTg5ZDQtZjY5Njk4Njk2MmRlXkEyXkFqcGdeQXVyNjc1NTYyMjg@._V1_FMjpg_UX1000_.jpg")
+ expect(onebox.to_html).to include(
+ "https://m.media-amazon.com/images/M/MV5BZGUzMDU1YmQtMzBkOS00MTNmLTg5ZDQtZjY5Njk4Njk2MmRlXkEyXkFqcGdeQXVyNjc1NTYyMjg@._V1_FMjpg_UX1000_.jpg",
+ )
expect(onebox.to_html).to include("Rudy (1993) - IMDb")
- expect(onebox.to_html).to include("Rudy: Directed by David Anspaugh. With Sean Astin, Jon Favreau, Ned Beatty, Greta Lind. Rudy has always been told that he was too small to play college football.")
+ expect(onebox.to_html).to include(
+ "Rudy: Directed by David Anspaugh. With Sean Astin, Jon Favreau, Ned Beatty, Greta Lind. Rudy has always been told that he was too small to play college football.",
+ )
end
- it 'shows rating' do
+ it "shows rating" do
onebox = described_class.new("https://www.imdb.com/title/tt0108002/")
expect(onebox.to_html).to include("7.5")
end
- it 'shows duration' do
+ it "shows duration" do
onebox = described_class.new("https://www.imdb.com/title/tt0108002/")
expect(onebox.to_html).to include("01:54")
end
diff --git a/spec/lib/onebox/engine/amazon_onebox_spec.rb b/spec/lib/onebox/engine/amazon_onebox_spec.rb
index ad624b6c9cd..b0deee8736d 100644
--- a/spec/lib/onebox/engine/amazon_onebox_spec.rb
+++ b/spec/lib/onebox/engine/amazon_onebox_spec.rb
@@ -6,8 +6,10 @@ RSpec.describe Onebox::Engine::AmazonOnebox do
@link = "https://www.amazon.com/Knit-Noro-Accessories-Colorful-Little/dp/193609620X"
@uri = "https://www.amazon.com/dp/193609620X"
- stub_request(:get, "https://www.amazon.com/Seven-Languages-Weeks-Programming-Programmers/dp/193435659X")
- .to_return(status: 200, body: onebox_response("amazon"))
+ stub_request(
+ :get,
+ "https://www.amazon.com/Seven-Languages-Weeks-Programming-Programmers/dp/193435659X",
+ ).to_return(status: 200, body: onebox_response("amazon"))
end
include_context "with engines"
@@ -21,11 +23,17 @@ RSpec.describe Onebox::Engine::AmazonOnebox do
end
it "matches canadian domains" do
- check_link("ca", "https://www.amazon.ca/Too-Much-Happiness-Alice-Munro-ebook/dp/B0031TZ98K/")
+ check_link(
+ "ca",
+ "https://www.amazon.ca/Too-Much-Happiness-Alice-Munro-ebook/dp/B0031TZ98K/",
+ )
end
it "matches german domains" do
- check_link("de", "https://www.amazon.de/Buddenbrooks-Verfall-einer-Familie-Roman/dp/3596294312/")
+ check_link(
+ "de",
+ "https://www.amazon.de/Buddenbrooks-Verfall-einer-Familie-Roman/dp/3596294312/",
+ )
end
it "matches uk domains" do
@@ -33,15 +41,24 @@ RSpec.describe Onebox::Engine::AmazonOnebox do
end
it "matches japanese domains" do
- check_link("co.jp", "https://www.amazon.co.jp/%E9%9B%AA%E5%9B%BD-%E6%96%B0%E6%BD%AE%E6%96%87%E5%BA%AB-%E3%81%8B-1-1-%E5%B7%9D%E7%AB%AF-%E5%BA%B7%E6%88%90/dp/4101001014/")
+ check_link(
+ "co.jp",
+ "https://www.amazon.co.jp/%E9%9B%AA%E5%9B%BD-%E6%96%B0%E6%BD%AE%E6%96%87%E5%BA%AB-%E3%81%8B-1-1-%E5%B7%9D%E7%AB%AF-%E5%BA%B7%E6%88%90/dp/4101001014/",
+ )
end
it "matches chinese domains" do
- check_link("cn", "https://www.amazon.cn/%E5%AD%99%E5%AD%90%E5%85%B5%E6%B3%95-%E5%AD%99%E8%86%91%E5%85%B5%E6%B3%95-%E5%AD%99%E6%AD%A6/dp/B0011C40FC/")
+ check_link(
+ "cn",
+ "https://www.amazon.cn/%E5%AD%99%E5%AD%90%E5%85%B5%E6%B3%95-%E5%AD%99%E8%86%91%E5%85%B5%E6%B3%95-%E5%AD%99%E6%AD%A6/dp/B0011C40FC/",
+ )
end
it "matches french domains" do
- check_link("fr", "https://www.amazon.fr/Les-Mots-autres-%C3%A9crits-autobiographiques/dp/2070114147/")
+ check_link(
+ "fr",
+ "https://www.amazon.fr/Les-Mots-autres-%C3%A9crits-autobiographiques/dp/2070114147/",
+ )
end
it "matches italian domains" do
@@ -49,11 +66,17 @@ RSpec.describe Onebox::Engine::AmazonOnebox do
end
it "matches spanish domains" do
- check_link("es", "https://www.amazon.es/familia-Pascual-Duarte-Camilo-Jos%C3%A9-ebook/dp/B00EJRTKTW/")
+ check_link(
+ "es",
+ "https://www.amazon.es/familia-Pascual-Duarte-Camilo-Jos%C3%A9-ebook/dp/B00EJRTKTW/",
+ )
end
it "matches brazilian domains" do
- check_link("com.br", "https://www.amazon.com.br/A-p%C3%A1tria-chuteiras-Nelson-Rodrigues-ebook/dp/B00J2B414Y/")
+ check_link(
+ "com.br",
+ "https://www.amazon.com.br/A-p%C3%A1tria-chuteiras-Nelson-Rodrigues-ebook/dp/B00J2B414Y/",
+ )
end
it "matches indian domains" do
@@ -61,34 +84,44 @@ RSpec.describe Onebox::Engine::AmazonOnebox do
end
it "matches mexican domains" do
- check_link("com.mx", "https://www.amazon.com.mx/Legend-Zelda-Links-Awakening-Nintendo/dp/B07SG15148/")
+ check_link(
+ "com.mx",
+ "https://www.amazon.com.mx/Legend-Zelda-Links-Awakening-Nintendo/dp/B07SG15148/",
+ )
end
end
describe "#url" do
- let(:long_url) { "https://www.amazon.ca/gp/product/B087Z3N428?pf_rd_r=SXABADD0ZZ3NF9Q5F8TW&pf_rd_p=05378fd5-c43e-4948-99b1-a65b129fdd73&pd_rd_r=0237fb28-7f47-49f4-986a-be0c78e52863&pd_rd_w=FfIoI&pd_rd_wg=Hw4qq&ref_=pd_gw_unk" }
+ let(:long_url) do
+ "https://www.amazon.ca/gp/product/B087Z3N428?pf_rd_r=SXABADD0ZZ3NF9Q5F8TW&pf_rd_p=05378fd5-c43e-4948-99b1-a65b129fdd73&pd_rd_r=0237fb28-7f47-49f4-986a-be0c78e52863&pd_rd_w=FfIoI&pd_rd_wg=Hw4qq&ref_=pd_gw_unk"
+ end
it "maintains the same http/https scheme as the requested URL" do
- expect(described_class.new("https://www.amazon.fr/gp/product/B01BYD0TZM").url)
- .to eq("https://www.amazon.fr/dp/B01BYD0TZM")
+ expect(described_class.new("https://www.amazon.fr/gp/product/B01BYD0TZM").url).to eq(
+ "https://www.amazon.fr/dp/B01BYD0TZM",
+ )
- expect(described_class.new("http://www.amazon.fr/gp/product/B01BYD0TZM").url)
- .to eq("https://www.amazon.fr/dp/B01BYD0TZM")
+ expect(described_class.new("http://www.amazon.fr/gp/product/B01BYD0TZM").url).to eq(
+ "https://www.amazon.fr/dp/B01BYD0TZM",
+ )
end
it "removes parameters from the URL" do
- expect(described_class.new(long_url).url)
- .not_to include("?pf_rd_r")
+ expect(described_class.new(long_url).url).not_to include("?pf_rd_r")
end
end
describe "#to_html" do
it "includes image" do
- expect(html).to include("https://images-na.ssl-images-amazon.com/images/I/51opYcR6kVL._SY400_.jpg")
+ expect(html).to include(
+ "https://images-na.ssl-images-amazon.com/images/I/51opYcR6kVL._SY400_.jpg",
+ )
end
it "includes description" do
- expect(html).to include("You should learn a programming language every year, as recommended by The Pragmatic Programmer.")
+ expect(html).to include(
+ "You should learn a programming language every year, as recommended by The Pragmatic Programmer.",
+ )
end
it "includes price" do
@@ -96,7 +129,9 @@ RSpec.describe Onebox::Engine::AmazonOnebox do
end
it "includes title" do
- expect(html).to include("Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages (Pragmatic Programmers)")
+ expect(html).to include(
+ "Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages (Pragmatic Programmers)",
+ )
end
end
end
@@ -106,20 +141,28 @@ RSpec.describe Onebox::Engine::AmazonOnebox do
let(:html) { described_class.new(link).to_html }
before do
- stub_request(:get, "https://www.amazon.com/dp/B01MFXN4Y2")
- .to_return(status: 200, body: onebox_response("amazon-og"))
+ stub_request(:get, "https://www.amazon.com/dp/B01MFXN4Y2").to_return(
+ status: 200,
+ body: onebox_response("amazon-og"),
+ )
- stub_request(:get, "https://www.amazon.com/Christine-Rebecca-Hall/dp/B01MFXN4Y2")
- .to_return(status: 200, body: onebox_response("amazon-og"))
+ stub_request(:get, "https://www.amazon.com/Christine-Rebecca-Hall/dp/B01MFXN4Y2").to_return(
+ status: 200,
+ body: onebox_response("amazon-og"),
+ )
end
describe "#to_html" do
it "includes image" do
- expect(html).to include("https://images-na.ssl-images-amazon.com/images/I/51nOF2iBa6L._SX940_.jpg")
+ expect(html).to include(
+ "https://images-na.ssl-images-amazon.com/images/I/51nOF2iBa6L._SX940_.jpg",
+ )
end
it "includes description" do
- expect(html).to include("CHRISTINE is the story of an aspiring newswoman caught in the midst of a personal and professional life crisis. Between unrequited love, frustration at work, a tumultuous home, and self-doubt; she begins to spiral down a dark path.")
+ expect(html).to include(
+ "CHRISTINE is the story of an aspiring newswoman caught in the midst of a personal and professional life crisis. Between unrequited love, frustration at work, a tumultuous home, and self-doubt; she begins to spiral down a dark path.",
+ )
end
it "includes title" do
@@ -133,16 +176,22 @@ RSpec.describe Onebox::Engine::AmazonOnebox do
let(:html) { described_class.new(link).to_html }
before do
- stub_request(:get, "https://www.amazon.com/dp/B00AYQNR46")
- .to_return(status: 200, body: onebox_response("amazon"))
+ stub_request(:get, "https://www.amazon.com/dp/B00AYQNR46").to_return(
+ status: 200,
+ body: onebox_response("amazon"),
+ )
- stub_request(:get, "https://www.amazon.com/Seven-Languages-Weeks-Programming-Programmers/dp/193435659X")
- .to_return(status: 200, body: onebox_response("amazon"))
+ stub_request(
+ :get,
+ "https://www.amazon.com/Seven-Languages-Weeks-Programming-Programmers/dp/193435659X",
+ ).to_return(status: 200, body: onebox_response("amazon"))
end
describe "#to_html" do
it "includes title and author" do
- expect(html).to include("Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages (Pragmatic Programmers)")
+ expect(html).to include(
+ "Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages (Pragmatic Programmers)",
+ )
expect(html).to include("Bruce Tate")
end
@@ -161,21 +210,29 @@ RSpec.describe Onebox::Engine::AmazonOnebox do
let(:html) { described_class.new(link).to_html }
before do
- stub_request(:get, "https://www.amazon.com/dp/193435659X")
- .to_return(status: 200, body: onebox_response("amazon-ebook"))
+ stub_request(:get, "https://www.amazon.com/dp/193435659X").to_return(
+ status: 200,
+ body: onebox_response("amazon-ebook"),
+ )
- stub_request(:get, "https://www.amazon.com/Seven-Languages-Weeks-Programming-Programmers-ebook/dp/B00AYQNR46")
- .to_return(status: 200, body: onebox_response("amazon-ebook"))
+ stub_request(
+ :get,
+ "https://www.amazon.com/Seven-Languages-Weeks-Programming-Programmers-ebook/dp/B00AYQNR46",
+ ).to_return(status: 200, body: onebox_response("amazon-ebook"))
end
describe "#to_html" do
it "includes title and author" do
- expect(html).to include("Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages (Pragmatic Programmers)")
+ expect(html).to include(
+ "Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages (Pragmatic Programmers)",
+ )
expect(html).to include("Bruce Tate")
end
it "includes image" do
- expect(html).to include("https://images-na.ssl-images-amazon.com/images/I/51LZT%2BtSrTL._SX133_.jpg")
+ expect(html).to include(
+ "https://images-na.ssl-images-amazon.com/images/I/51LZT%2BtSrTL._SX133_.jpg",
+ )
end
it "includes ASIN" do
@@ -197,8 +254,10 @@ RSpec.describe Onebox::Engine::AmazonOnebox do
let(:onebox) { described_class.new(link) }
before do
- stub_request(:get, "https://www.amazon.com/dp/B0123ABCD3210")
- .to_return(status: 200, body: onebox_response("amazon-error"))
+ stub_request(:get, "https://www.amazon.com/dp/B0123ABCD3210").to_return(
+ status: 200,
+ body: onebox_response("amazon-error"),
+ )
end
it "returns a blank result" do
@@ -206,7 +265,9 @@ RSpec.describe Onebox::Engine::AmazonOnebox do
end
it "produces a placeholder" do
- expect(onebox.placeholder_html).to include('')
+ expect(onebox.placeholder_html).to include(
+ '',
+ )
end
it "returns errors" do
@@ -220,11 +281,15 @@ RSpec.describe Onebox::Engine::AmazonOnebox do
let(:html) { described_class.new(link).to_html }
before do
- stub_request(:get, "https://www.amazon.com/dp/B07FQ7M16H")
- .to_return(status: 200, body: onebox_response("amazon-alternate"))
+ stub_request(:get, "https://www.amazon.com/dp/B07FQ7M16H").to_return(
+ status: 200,
+ body: onebox_response("amazon-alternate"),
+ )
- stub_request(:get, "https://www.amazon.com/Lnchett-Nibbler-Quality-Attachment-Straight/dp/B07FQ7M16H")
- .to_return(status: 200, body: onebox_response("amazon-alternate"))
+ stub_request(
+ :get,
+ "https://www.amazon.com/Lnchett-Nibbler-Quality-Attachment-Straight/dp/B07FQ7M16H",
+ ).to_return(status: 200, body: onebox_response("amazon-alternate"))
end
describe "#to_html" do
@@ -233,7 +298,9 @@ RSpec.describe Onebox::Engine::AmazonOnebox do
end
it "includes description" do
- expect(html).to include("Drill Attachment for Straight Curve and Circle Cutting, Maximum 14 Gauge Steel")
+ expect(html).to include(
+ "Drill Attachment for Straight Curve and Circle Cutting, Maximum 14 Gauge Steel",
+ )
end
it "includes price" do
diff --git a/spec/lib/onebox/engine/animated_image_onebox_spec.rb b/spec/lib/onebox/engine/animated_image_onebox_spec.rb
index 049ce7e793f..85543fcf063 100644
--- a/spec/lib/onebox/engine/animated_image_onebox_spec.rb
+++ b/spec/lib/onebox/engine/animated_image_onebox_spec.rb
@@ -13,9 +13,7 @@ RSpec.describe Onebox::Engine::AnimatedImageOnebox do
stub_request(:get, tenor).to_return(status: 200, body: onebox_response("tenor"))
end
- after do
- Onebox.options = @previous_options
- end
+ after { Onebox.options = @previous_options }
it "works for giphy short URLs" do
html = described_class.new(giphy).to_html
diff --git a/spec/lib/onebox/engine/audio_onebox_spec.rb b/spec/lib/onebox/engine/audio_onebox_spec.rb
index cf3a3a9257e..a66ab849c06 100644
--- a/spec/lib/onebox/engine/audio_onebox_spec.rb
+++ b/spec/lib/onebox/engine/audio_onebox_spec.rb
@@ -2,34 +2,53 @@
RSpec.describe Onebox::Engine::AudioOnebox do
it "supports ogg" do
- expect(Onebox.preview('http://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg').to_s).to match(/main/spec/fixtures')
+ expect(html).to include(
+ 'main/spec/fixtures ',
+ )
end
it "includes repository name" do
@@ -27,29 +32,39 @@ RSpec.describe Onebox::Engine::GithubFolderOnebox do
end
end
- context 'with fragments' do
+ context "with fragments" do
before do
@link = "https://github.com/discourse/discourse#setting-up-discourse"
@uri = "https://github.com/discourse/discourse"
- stub_request(:get, @uri).to_return(status: 200, body: onebox_response("githubfolder-discourse-root"))
+ stub_request(:get, @uri).to_return(
+ status: 200,
+ body: onebox_response("githubfolder-discourse-root"),
+ )
@onebox = described_class.new(@link)
end
it "extracts subtitles when linking to docs" do
- expect(@onebox.to_html).to include("discourse/discourse - Setting up Discourse ")
+ expect(@onebox.to_html).to include(
+ "discourse/discourse - Setting up Discourse ",
+ )
end
end
- context 'with rdoc fragments' do
+ context "with rdoc fragments" do
before do
@link = "https://github.com/ruby/rdoc#description-"
@uri = "https://github.com/ruby/rdoc"
- stub_request(:get, @uri).to_return(status: 200, body: onebox_response("githubfolder-rdoc-root"))
+ stub_request(:get, @uri).to_return(
+ status: 200,
+ body: onebox_response("githubfolder-rdoc-root"),
+ )
@onebox = described_class.new(@link)
end
it "extracts subtitles when linking to docs" do
- expect(@onebox.to_html).to include("GitHub - ruby/rdoc: RDoc produces HTML and online documentation for Ruby... - Description¶ ↑ ")
+ expect(@onebox.to_html).to include(
+ "GitHub - ruby/rdoc: RDoc produces HTML and online documentation for Ruby... - Description¶ ↑ ",
+ )
end
end
end
diff --git a/spec/lib/onebox/engine/github_gist_onebox_spec.rb b/spec/lib/onebox/engine/github_gist_onebox_spec.rb
index 6cbb285e005..7196a046cf1 100644
--- a/spec/lib/onebox/engine/github_gist_onebox_spec.rb
+++ b/spec/lib/onebox/engine/github_gist_onebox_spec.rb
@@ -4,8 +4,10 @@ RSpec.describe Onebox::Engine::GithubGistOnebox do
before do
@link = "https://gist.github.com/karreiro/208fdd59fc4b4c39283b"
- stub_request(:get, "https://api.github.com/gists/208fdd59fc4b4c39283b")
- .to_return(status: 200, body: onebox_response(described_class.onebox_name))
+ stub_request(:get, "https://api.github.com/gists/208fdd59fc4b4c39283b").to_return(
+ status: 200,
+ body: onebox_response(described_class.onebox_name),
+ )
end
include_context "with engines"
@@ -14,7 +16,7 @@ RSpec.describe Onebox::Engine::GithubGistOnebox do
describe "#data" do
let(:gist_files) { data[:gist_files] }
- it 'includes contents with 10 lines at most' do
+ it "includes contents with 10 lines at most" do
gist_files.each do |gist_file|
truncated_lines = gist_file.content.split("\n").size
expect(truncated_lines).to be < 10
@@ -23,7 +25,7 @@ RSpec.describe Onebox::Engine::GithubGistOnebox do
end
describe "#to_html" do
- describe 'when Gist API responds correctly' do
+ describe "when Gist API responds correctly" do
it "includes the link to original page" do
expect(html).to include("https://gist.github.com/karreiro/208fdd59fc4b4c39283b")
end
@@ -49,10 +51,11 @@ RSpec.describe Onebox::Engine::GithubGistOnebox do
end
end
- describe 'when the rate limit has been reached' do
+ describe "when the rate limit has been reached" do
before do
- stub_request(:get, "https://api.github.com/gists/208fdd59fc4b4c39283b")
- .to_return(status: 403)
+ stub_request(:get, "https://api.github.com/gists/208fdd59fc4b4c39283b").to_return(
+ status: 403,
+ )
end
it "includes the link to original page" do
diff --git a/spec/lib/onebox/engine/github_pull_request_onebox_spec.rb b/spec/lib/onebox/engine/github_pull_request_onebox_spec.rb
index 24f62fe08bd..f0fdca0e228 100644
--- a/spec/lib/onebox/engine/github_pull_request_onebox_spec.rb
+++ b/spec/lib/onebox/engine/github_pull_request_onebox_spec.rb
@@ -5,7 +5,10 @@ RSpec.describe Onebox::Engine::GithubPullRequestOnebox do
@link = "https://github.com/discourse/discourse/pull/1253/"
@uri = "https://api.github.com/repos/discourse/discourse/pulls/1253"
- stub_request(:get, @uri).to_return(status: 200, body: onebox_response(described_class.onebox_name))
+ stub_request(:get, @uri).to_return(
+ status: 200,
+ body: onebox_response(described_class.onebox_name),
+ )
end
include_context "with engines"
@@ -52,16 +55,23 @@ RSpec.describe Onebox::Engine::GithubPullRequestOnebox do
context "with commit links" do
before do
- @link = "https://github.com/discourse/discourse/pull/1253/commits/d7d3be1130c665cc7fab9f05dbf32335229137a6"
- @uri = "https://api.github.com/repos/discourse/discourse/commits/d7d3be1130c665cc7fab9f05dbf32335229137a6"
+ @link =
+ "https://github.com/discourse/discourse/pull/1253/commits/d7d3be1130c665cc7fab9f05dbf32335229137a6"
+ @uri =
+ "https://api.github.com/repos/discourse/discourse/commits/d7d3be1130c665cc7fab9f05dbf32335229137a6"
- stub_request(:get, @uri).to_return(status: 200, body: onebox_response(described_class.onebox_name + "_commit"))
+ stub_request(:get, @uri).to_return(
+ status: 200,
+ body: onebox_response(described_class.onebox_name + "_commit"),
+ )
end
it "includes commit name" do
- doc = Nokogiri::HTML5(html)
- expect(doc.css('h4').text.strip).to eq("Add audio onebox")
- expect(doc.css('.github-body-container').text).to include("http://meta.discourse.org/t/audio-html5-tag/8168")
+ doc = Nokogiri.HTML5(html)
+ expect(doc.css("h4").text.strip).to eq("Add audio onebox")
+ expect(doc.css(".github-body-container").text).to include(
+ "http://meta.discourse.org/t/audio-html5-tag/8168",
+ )
end
end
@@ -70,7 +80,10 @@ RSpec.describe Onebox::Engine::GithubPullRequestOnebox do
@link = "https://github.com/discourse/discourse/pull/1253/#issuecomment-21597425"
@uri = "https://api.github.com/repos/discourse/discourse/issues/comments/21597425"
- stub_request(:get, @uri).to_return(status: 200, body: onebox_response(described_class.onebox_name + "_comment"))
+ stub_request(:get, @uri).to_return(
+ status: 200,
+ body: onebox_response(described_class.onebox_name + "_comment"),
+ )
end
it "includes comment" do
diff --git a/spec/lib/onebox/engine/gitlab_blob_onebox_spec.rb b/spec/lib/onebox/engine/gitlab_blob_onebox_spec.rb
index ec812b66bc5..21bcef26ec8 100644
--- a/spec/lib/onebox/engine/gitlab_blob_onebox_spec.rb
+++ b/spec/lib/onebox/engine/gitlab_blob_onebox_spec.rb
@@ -2,10 +2,13 @@
RSpec.describe Onebox::Engine::GitlabBlobOnebox do
before do
- @link = "https://gitlab.com/discourse/onebox/blob/master/lib/onebox/engine/gitlab_blob_onebox.rb"
+ @link =
+ "https://gitlab.com/discourse/onebox/blob/master/lib/onebox/engine/gitlab_blob_onebox.rb"
- stub_request(:get, "https://gitlab.com/discourse/onebox/raw/master/lib/onebox/engine/gitlab_blob_onebox.rb")
- .to_return(status: 200, body: onebox_response(described_class.onebox_name))
+ stub_request(
+ :get,
+ "https://gitlab.com/discourse/onebox/raw/master/lib/onebox/engine/gitlab_blob_onebox.rb",
+ ).to_return(status: 200, body: onebox_response(described_class.onebox_name))
end
include_context "with engines"
diff --git a/spec/lib/onebox/engine/google_docs_onebox_spec.rb b/spec/lib/onebox/engine/google_docs_onebox_spec.rb
index 214fe05dab1..28344b043fe 100644
--- a/spec/lib/onebox/engine/google_docs_onebox_spec.rb
+++ b/spec/lib/onebox/engine/google_docs_onebox_spec.rb
@@ -16,7 +16,9 @@ RSpec.describe Onebox::Engine::GoogleDocsOnebox do
end
it "has description" do
- expect(html).to include("Lorem Ipsum Lorem ipsum dolor sit amet, consectetur adipiscing elit")
+ expect(html).to include(
+ "Lorem Ipsum Lorem ipsum dolor sit amet, consectetur adipiscing elit",
+ )
end
it "has icon" do
diff --git a/spec/lib/onebox/engine/google_drive_onebox_spec.rb b/spec/lib/onebox/engine/google_drive_onebox_spec.rb
index 3224e8b3e1e..58b67748aa5 100644
--- a/spec/lib/onebox/engine/google_drive_onebox_spec.rb
+++ b/spec/lib/onebox/engine/google_drive_onebox_spec.rb
@@ -4,16 +4,18 @@ RSpec.describe Onebox::Engine::GoogleDriveOnebox do
let(:link) { "https://drive.google.com/file/d/1FgMt06wENEUfC6_-1tImXaNCH7vM9QsA/view" }
let(:html) { described_class.new(link).to_html }
- before do
- stub_request(:get, link).to_return(status: 200, body: onebox_response("googledrive"))
- end
+ before { stub_request(:get, link).to_return(status: 200, body: onebox_response("googledrive")) }
it "includes title" do
- expect(html).to include('test.txt ')
+ expect(html).to include(
+ 'test.txt ',
+ )
end
it "includes image" do
- expect(html).to include("https://lh5.googleusercontent.com/wcDbcSFKB3agLf0963iFPqwy96OE2s7of1pAEbEOpg-38yS_m7u8VHKezWQ=w1200-h630-p")
+ expect(html).to include(
+ "https://lh5.googleusercontent.com/wcDbcSFKB3agLf0963iFPqwy96OE2s7of1pAEbEOpg-38yS_m7u8VHKezWQ=w1200-h630-p",
+ )
end
it "includes description" do
diff --git a/spec/lib/onebox/engine/google_maps_onebox_spec.rb b/spec/lib/onebox/engine/google_maps_onebox_spec.rb
index f0eeb542389..498d4289f4c 100644
--- a/spec/lib/onebox/engine/google_maps_onebox_spec.rb
+++ b/spec/lib/onebox/engine/google_maps_onebox_spec.rb
@@ -5,36 +5,51 @@ RSpec.describe Onebox::Engine::GoogleMapsOnebox do
short: {
test: "https://goo.gl/maps/rEG3D",
redirect: [302, :long],
- expect: "https://maps.google.de/maps?sll=40.689249,-74.0445&sspn=0.0062479,0.0109864&cid=4667599994556318251&q=Statue+of+Liberty+National+Monument&output=embed&dg=ntvb&ll=40.689249,-74.0445&spn=0.0062479,0.0109864",
+ expect:
+ "https://maps.google.de/maps?sll=40.689249,-74.0445&sspn=0.0062479,0.0109864&cid=4667599994556318251&q=Statue+of+Liberty+National+Monument&output=embed&dg=ntvb&ll=40.689249,-74.0445&spn=0.0062479,0.0109864",
},
long: {
- test: "https://www.google.de/maps/place/Statue+of+Liberty+National+Monument/@40.689249,-74.0445,17z/data=!3m1!4b1!4m2!3m1!1s0x89c25090129c363d:0x40c6a5770d25022b",
+ test:
+ "https://www.google.de/maps/place/Statue+of+Liberty+National+Monument/@40.689249,-74.0445,17z/data=!3m1!4b1!4m2!3m1!1s0x89c25090129c363d:0x40c6a5770d25022b",
redirect: [301, :canonical],
- expect: "https://maps.google.de/maps?sll=40.689249,-74.0445&sspn=0.0062479,0.0109864&cid=4667599994556318251&q=Statue+of+Liberty+National+Monument&output=embed&dg=ntvb&ll=40.689249,-74.0445&spn=0.0062479,0.0109864",
+ expect:
+ "https://maps.google.de/maps?sll=40.689249,-74.0445&sspn=0.0062479,0.0109864&cid=4667599994556318251&q=Statue+of+Liberty+National+Monument&output=embed&dg=ntvb&ll=40.689249,-74.0445&spn=0.0062479,0.0109864",
},
canonical: {
- test: "https://maps.google.de/maps?sll=40.689249,-74.0445&sspn=0.0062479,0.0109864&cid=4667599994556318251&q=Statue+of+Liberty+National+Monument&output=classic&dg=ntvb",
- expect: "https://maps.google.de/maps?sll=40.689249,-74.0445&sspn=0.0062479,0.0109864&cid=4667599994556318251&q=Statue+of+Liberty+National+Monument&output=embed&dg=ntvb&ll=40.689249,-74.0445&spn=0.0062479,0.0109864",
+ test:
+ "https://maps.google.de/maps?sll=40.689249,-74.0445&sspn=0.0062479,0.0109864&cid=4667599994556318251&q=Statue+of+Liberty+National+Monument&output=classic&dg=ntvb",
+ expect:
+ "https://maps.google.de/maps?sll=40.689249,-74.0445&sspn=0.0062479,0.0109864&cid=4667599994556318251&q=Statue+of+Liberty+National+Monument&output=embed&dg=ntvb&ll=40.689249,-74.0445&spn=0.0062479,0.0109864",
},
custom: {
test: "https://www.google.com/maps/d/edit?mid=zPYyZFrHi1MU.kX85W_Y2y2_E",
expect: "https://www.google.com/maps/d/embed?mid=zPYyZFrHi1MU.kX85W_Y2y2_E",
},
streetview: {
- test: "https://www.google.com/maps/@46.414384,10.013947,3a,75y,232.83h,99.08t/data=!3m5!1e1!3m3!1s9WgYUb5quXDjqqFd3DWI6A!2e0!3e5?hl=de",
- expect: "https://www.google.com/maps/embed?pb=!3m2!2sen!4v0!6m8!1m7!1s9WgYUb5quXDjqqFd3DWI6A!2m2!1d46.414384!2d10.013947!3f232.83!4f9.908!5f0.75",
- streetview: true
+ test:
+ "https://www.google.com/maps/@46.414384,10.013947,3a,75y,232.83h,99.08t/data=!3m5!1e1!3m3!1s9WgYUb5quXDjqqFd3DWI6A!2e0!3e5?hl=de",
+ expect:
+ "https://www.google.com/maps/embed?pb=!3m2!2sen!4v0!6m8!1m7!1s9WgYUb5quXDjqqFd3DWI6A!2m2!1d46.414384!2d10.013947!3f232.83!4f9.908!5f0.75",
+ streetview: true,
},
unresolveable: {
- test: "https://www.google.com/maps/place/Den+Abattoir/@51.2285173,4.4336702,17z/data=!4m7!1m4!3m3!1s0x47c3f7a5ac48e237:0x63d716018f584a33!2zUGnDqXRyYWlu!3b1!3m1!1s0x0000000000000000:0xfbfac0c41c32471a",
- redirect: [302, "https://www.google.com/maps/place/Den+Abattoir/@51.2285173,4.4336702,17z/data=!4m7!1m4!3m3!1s0x47c3f7a5ac48e237:0x63d716018f584a33!2zUGnDqXRyYWlu!3b1!3m1!1s0x0000000000000000:0xfbfac0c41c32471a?dg=dbrw&newdg=1"],
- expect: "https://maps.google.com/maps?ll=51.2285173,4.4336702&z=17&output=embed&dg=ntvb&q=Den+Abattoir&cid=18157036796216755994"
+ test:
+ "https://www.google.com/maps/place/Den+Abattoir/@51.2285173,4.4336702,17z/data=!4m7!1m4!3m3!1s0x47c3f7a5ac48e237:0x63d716018f584a33!2zUGnDqXRyYWlu!3b1!3m1!1s0x0000000000000000:0xfbfac0c41c32471a",
+ redirect: [
+ 302,
+ "https://www.google.com/maps/place/Den+Abattoir/@51.2285173,4.4336702,17z/data=!4m7!1m4!3m3!1s0x47c3f7a5ac48e237:0x63d716018f584a33!2zUGnDqXRyYWlu!3b1!3m1!1s0x0000000000000000:0xfbfac0c41c32471a?dg=dbrw&newdg=1",
+ ],
+ expect:
+ "https://maps.google.com/maps?ll=51.2285173,4.4336702&z=17&output=embed&dg=ntvb&q=Den+Abattoir&cid=18157036796216755994",
},
satellite: {
test: "https://www.google.de/maps/@40.6894264,-74.0449146,758m/data=!3m1!1e3",
- redirect: [302, "https://www.google.de/maps/@40.6894264,-74.0449146,758m/data=!3m1!1e3?dg=dbrw&newdg=1"],
- expect: "https://maps.google.com/maps?ll=40.6894264,-74.0449146&z=16&output=embed&dg=ntvb"
- }
+ redirect: [
+ 302,
+ "https://www.google.de/maps/@40.6894264,-74.0449146,758m/data=!3m1!1e3?dg=dbrw&newdg=1",
+ ],
+ expect: "https://maps.google.com/maps?ll=40.6894264,-74.0449146&z=16&output=embed&dg=ntvb",
+ },
}
# Register URL redirects
@@ -43,17 +58,18 @@ RSpec.describe Onebox::Engine::GoogleMapsOnebox do
status, location = *t[:redirect]
location = URLS[location][:test] if location.is_a? Symbol
- stub_request(:head, t[:test])
- .to_return(status: status, headers: { location: location })
+ stub_request(:head, t[:test]).to_return(status: status, headers: { location: location })
end
end
# Prevent sleep from wasting our time when we test with strange redirects
subject do
- described_class.send(:allocate).tap do |obj|
- obj.stubs(:sleep)
- obj.send(:initialize, link)
- end
+ described_class
+ .send(:allocate)
+ .tap do |obj|
+ obj.stubs(:sleep)
+ obj.send(:initialize, link)
+ end
end
let(:data) { Onebox::Helpers.symbolize_keys(subject.send(:data)) }
diff --git a/spec/lib/onebox/engine/google_photos_onebox_spec.rb b/spec/lib/onebox/engine/google_photos_onebox_spec.rb
index 90d6436667c..505fff77f60 100644
--- a/spec/lib/onebox/engine/google_photos_onebox_spec.rb
+++ b/spec/lib/onebox/engine/google_photos_onebox_spec.rb
@@ -6,10 +6,14 @@ RSpec.describe Onebox::Engine::GooglePhotosOnebox do
before do
stub_request(:get, link).to_return(status: 200, body: onebox_response("googlephotos"))
- stub_request(:get, "https://photos.google.com/share/AF1QipOV3gcu_edA8lyjJEpS9sC1g3AeCUtaZox11ylYZId7wJ7cthZ8M1kZXeAp5vhEPg?key=QktmUFNvdWpNVktERU5zWmVRZlZubzRRc0ttWWN3")
- .to_return(status: 200, body: onebox_response("googlephotos"))
- stub_request(:head, "https://photos.google.com/share/AF1QipOV3gcu_edA8lyjJEpS9sC1g3AeCUtaZox11ylYZId7wJ7cthZ8M1kZXeAp5vhEPg?key=QktmUFNvdWpNVktERU5zWmVRZlZubzRRc0ttWWN3")
- .to_return(status: 200, body: "")
+ stub_request(
+ :get,
+ "https://photos.google.com/share/AF1QipOV3gcu_edA8lyjJEpS9sC1g3AeCUtaZox11ylYZId7wJ7cthZ8M1kZXeAp5vhEPg?key=QktmUFNvdWpNVktERU5zWmVRZlZubzRRc0ttWWN3",
+ ).to_return(status: 200, body: onebox_response("googlephotos"))
+ stub_request(
+ :head,
+ "https://photos.google.com/share/AF1QipOV3gcu_edA8lyjJEpS9sC1g3AeCUtaZox11ylYZId7wJ7cthZ8M1kZXeAp5vhEPg?key=QktmUFNvdWpNVktERU5zWmVRZlZubzRRc0ttWWN3",
+ ).to_return(status: 200, body: "")
end
it "includes album title" do
@@ -17,6 +21,8 @@ RSpec.describe Onebox::Engine::GooglePhotosOnebox do
end
it "includes album poster image" do
- expect(html).to include("https://lh3.googleusercontent.com/ZlYoleNnrVo8qdx0qEjKi_-_VXY7pqqCqIW-B88EMqJ0etibFw1kEu4bzo-T4jyOQ9Ey2ekADim_L3re4lT3aBmYJUwhjkEUb5Yk59YaCSy2R8AoME5Rx4wviDRgICllF8g6lsZnS8c=w600-h315-p-k")
+ expect(html).to include(
+ "https://lh3.googleusercontent.com/ZlYoleNnrVo8qdx0qEjKi_-_VXY7pqqCqIW-B88EMqJ0etibFw1kEu4bzo-T4jyOQ9Ey2ekADim_L3re4lT3aBmYJUwhjkEUb5Yk59YaCSy2R8AoME5Rx4wviDRgICllF8g6lsZnS8c=w600-h315-p-k",
+ )
end
end
diff --git a/spec/lib/onebox/engine/google_play_app_onebox_spec.rb b/spec/lib/onebox/engine/google_play_app_onebox_spec.rb
index 43bf0437e18..25ee7336e46 100644
--- a/spec/lib/onebox/engine/google_play_app_onebox_spec.rb
+++ b/spec/lib/onebox/engine/google_play_app_onebox_spec.rb
@@ -4,8 +4,10 @@ RSpec.describe Onebox::Engine::GooglePlayAppOnebox do
before do
@link = "https://play.google.com/store/apps/details?id=com.hulu.plus&hl=en"
- stub_request(:get, "https://play.google.com/store/apps/details?id=com.hulu.plus&hl=en")
- .to_return(status: 200, body: onebox_response("googleplayapp"))
+ stub_request(
+ :get,
+ "https://play.google.com/store/apps/details?id=com.hulu.plus&hl=en",
+ ).to_return(status: 200, body: onebox_response("googleplayapp"))
end
include_context "with engines"
diff --git a/spec/lib/onebox/engine/hackernews_spec.rb b/spec/lib/onebox/engine/hackernews_spec.rb
index 152ec7adc4d..8e5a72bc672 100644
--- a/spec/lib/onebox/engine/hackernews_spec.rb
+++ b/spec/lib/onebox/engine/hackernews_spec.rb
@@ -7,11 +7,16 @@ RSpec.describe Onebox::Engine::HackernewsOnebox do
let(:html) { described_class.new(link).to_html }
before do
- stub_request(:get, api_link).to_return(status: 200, body: onebox_response("hackernews_comment"))
+ stub_request(:get, api_link).to_return(
+ status: 200,
+ body: onebox_response("hackernews_comment"),
+ )
end
it "has the comments first words" do
- expect(html).to include("Completely, forums are about basic human expression in paragraph form.")
+ expect(html).to include(
+ "Completely, forums are about basic human expression in paragraph form.",
+ )
end
it "has author username" do
diff --git a/spec/lib/onebox/engine/html_spec.rb b/spec/lib/onebox/engine/html_spec.rb
index 7fcc298c57e..9af34b04364 100644
--- a/spec/lib/onebox/engine/html_spec.rb
+++ b/spec/lib/onebox/engine/html_spec.rb
@@ -5,8 +5,10 @@ RSpec.describe Onebox::Engine::HTML do
@link = "http://amazon.com"
stub_request(:get, @link).to_return(status: 200, body: onebox_response("amazon"))
- stub_request(:get, "https://www.amazon.com/Seven-Languages-Weeks-Programming-Programmers/dp/193435659X")
- .to_return(status: 200, body: onebox_response("amazon"))
+ stub_request(
+ :get,
+ "https://www.amazon.com/Seven-Languages-Weeks-Programming-Programmers/dp/193435659X",
+ ).to_return(status: 200, body: onebox_response("amazon"))
end
describe "#raw" do
diff --git a/spec/lib/onebox/engine/image_onebox_spec.rb b/spec/lib/onebox/engine/image_onebox_spec.rb
index de3a40e961b..b3889bd528f 100644
--- a/spec/lib/onebox/engine/image_onebox_spec.rb
+++ b/spec/lib/onebox/engine/image_onebox_spec.rb
@@ -2,42 +2,66 @@
RSpec.describe Onebox::Engine::ImageOnebox do
it "supports png" do
- expect(Onebox.preview('http://www.discourse.org/images/logo.png').to_s).to match(/ "}'
- stub_request(:get, "https://embed.smartcontracts.org/api/onebox?url=https://embed.smartcontracts.org")
- .to_return(status: 200, body: body, headers: {})
+ stub_request(
+ :get,
+ "https://embed.smartcontracts.org/api/onebox?url=https://embed.smartcontracts.org",
+ ).to_return(status: 200, body: body, headers: {})
end
it "returns the expected iframe markup" do
- expect(Onebox.preview('https://embed.smartcontracts.org').to_s.chomp).to include(
- '