1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.tika.detect;
18  
19  import java.io.IOException;
20  import java.util.Map;
21  import java.util.TreeMap;
22  
23  import junit.framework.TestCase;
24  
25  import org.apache.tika.metadata.Metadata;
26  import org.apache.tika.mime.MediaType;
27  
28  /**
29   * Test cases for the {@link TypeDetector} class.
30   */
31  public class TypeDetectorTest extends TestCase {
32  
33      private Detector detector = new TypeDetector();
34      
35      private static final Map<String, String> params = new
36          TreeMap<String, String>();
37      static{
38          params.put("a", "b");
39      }
40      
41      private static final MediaType TEXT_PLAIN_A_EQ_B = 
42            new MediaType("text", "plain", params);
43  
44      public void testDetect() {
45          assertDetect(MediaType.TEXT_PLAIN, "text/plain");
46          assertDetect(MediaType.TEXT_PLAIN, "TEXT/PLAIN");
47          assertDetect(MediaType.TEXT_PLAIN, " text/\tplain\n");
48          assertDetect(TEXT_PLAIN_A_EQ_B, "text/plain; a=b");
49          assertDetect(TEXT_PLAIN_A_EQ_B, "\ttext/plain; a=b\n");
50  
51          assertDetect(MediaType.OCTET_STREAM, "text\\plain");
52  
53          // test also the zero input cases
54          assertDetect(MediaType.OCTET_STREAM, "");
55          assertDetect(MediaType.OCTET_STREAM, null);
56          try {
57              assertEquals(
58                      MediaType.OCTET_STREAM,
59                      detector.detect(null, new Metadata()));
60          } catch (IOException e) {
61              fail("TypeDetector should never throw an IOException");
62          }
63      }
64  
65      private void assertDetect(MediaType type, String name){
66          Metadata metadata = new Metadata();
67          metadata.set(Metadata.CONTENT_TYPE, name);
68          try {
69              assertEquals(type, detector.detect(null, metadata));
70          } catch (IOException e) {
71              fail("TypeDetector should never throw an IOException");
72          }
73      }
74  
75  }