|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# Released under the MIT License. |
| 4 | +# Copyright, 2016-2024, by Samuel Williams. |
| 5 | + |
| 6 | +require "protocol/http/accept/media_types" |
| 7 | +require "protocol/http/accept/media_types/map" |
| 8 | +require "protocol/http/accept/content_type" |
| 9 | + |
| 10 | +describe Protocol::HTTP::MediaTypes do |
| 11 | + let(:converter) do |
| 12 | + Struct.new(:content_type) do |
| 13 | + def split(*args) |
| 14 | + self.content_type.split(*args) |
| 15 | + end |
| 16 | + end |
| 17 | + end |
| 18 | + |
| 19 | + let(:text_html_converter) {converter.new("text/html")} |
| 20 | + |
| 21 | + let(:text_plain_content_type) {Protocol::HTTP::Accept::ContentType.new("text", "plain", charset: "utf-8")} |
| 22 | + let(:text_plain_converter) {converter.new(text_plain_content_type)} |
| 23 | + |
| 24 | + let(:map) {subject.new} |
| 25 | + |
| 26 | + it "should give the correct converter when specified completely" do |
| 27 | + map << text_html_converter |
| 28 | + map << text_plain_converter |
| 29 | + |
| 30 | + media_types = Protocol::HTTP::Accept::MediaTypes.parse("text/plain, text/*, */*") |
| 31 | + expect(map.for(media_types).first).to be == text_plain_converter |
| 32 | + |
| 33 | + media_types = Protocol::HTTP::Accept::MediaTypes.parse("text/html, text/*, */*") |
| 34 | + expect(map.for(media_types).first).to be == text_html_converter |
| 35 | + end |
| 36 | + |
| 37 | + it "should match the wildcard subtype converter" do |
| 38 | + map << text_html_converter |
| 39 | + map << text_plain_converter |
| 40 | + |
| 41 | + media_types = Protocol::HTTP::Accept::MediaTypes.parse("text/*, */*") |
| 42 | + expect(map.for(media_types).first).to be == text_html_converter |
| 43 | + |
| 44 | + media_types = Protocol::HTTP::Accept::MediaTypes.parse("*/*") |
| 45 | + expect(map.for(media_types).first).to be == text_html_converter |
| 46 | + end |
| 47 | + |
| 48 | + it "should fail to match if no media types match" do |
| 49 | + map << text_plain_converter |
| 50 | + |
| 51 | + expect(map.for(["application/json"])).to be_nil |
| 52 | + end |
| 53 | + |
| 54 | + it "should fail to match if no media types specified" do |
| 55 | + expect(map.for(["text/*", "*/*"])).to be_nil |
| 56 | + end |
| 57 | + |
| 58 | + it "should freeze converters" do |
| 59 | + map << text_html_converter |
| 60 | + |
| 61 | + map.freeze |
| 62 | + |
| 63 | + expect(text_html_converter).to be(:frozen?) |
| 64 | + end |
| 65 | + |
| 66 | + it "should assign and retrive media ranges" do |
| 67 | + map["*/*"] = :test |
| 68 | + |
| 69 | + expect(map["*/*"]).to be == :test |
| 70 | + end |
| 71 | +end |
0 commit comments