1   
2   
3   
4   
5   
6   
7   
8   
9   
10  
11  
12  
13  
14  
15  
16  package org.supercsv.cellprocessor.constraint;
17  
18  import static org.junit.Assert.assertEquals;
19  import static org.junit.Assert.assertFalse;
20  import static org.junit.Assert.assertTrue;
21  import static org.junit.Assert.fail;
22  import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT;
23  
24  import java.util.regex.PatternSyntaxException;
25  
26  import org.junit.Before;
27  import org.junit.Test;
28  import org.supercsv.cellprocessor.ift.CellProcessor;
29  import org.supercsv.exception.SuperCsvCellProcessorException;
30  import org.supercsv.exception.SuperCsvConstraintViolationException;
31  import org.supercsv.mock.IdentityTransform;
32  
33  
34  
35  
36  
37  
38  public class StrRegExTest {
39  	
40  	private static final String REGEX = "\\$[0-9]+\\.[0-9]{2}";
41  	private static final String MSG = "Must be a valid dollar amount, e.g. $123.45";
42  	
43  	private CellProcessor processor;
44  	private CellProcessor processorChain;
45  	
46  	
47  
48  
49  	@Before
50  	public void setUp() {
51  		processor = new StrRegEx(REGEX);
52  		processorChain = new StrRegEx(REGEX, new IdentityTransform());
53  		StrRegEx.registerMessage(REGEX, MSG);
54  	}
55  	
56  	
57  
58  
59  	@Test
60  	public void testValidInput() {
61  		String input = "$123.45";
62  		assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT));
63  		assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT));
64  	}
65  	
66  	
67  
68  
69  	@Test
70  	public void testInvalidInput() {
71  		String input = "12345";
72  		try {
73  			processor.execute(input, ANONYMOUS_CSVCONTEXT);
74  			fail("should have thrown SuperCsvConstraintViolationException");
75  		}
76  		catch(SuperCsvConstraintViolationException e) {
77  			
78  			assertTrue(e.getMessage().contains(MSG));
79  		}
80  	}
81  	
82  	
83  
84  
85  	@Test
86  	public void testInvalidInputWithNoMessage() {
87  		processor = new StrRegEx("\\s"); 
88  		String input = "12345";
89  		try {
90  			processor.execute(input, ANONYMOUS_CSVCONTEXT);
91  			fail("should have thrown SuperCsvConstraintViolationException");
92  		}
93  		catch(SuperCsvConstraintViolationException e) {
94  			
95  			assertFalse(e.getMessage().contains(MSG));
96  		}
97  	}
98  	
99  	
100 
101 
102 	@Test(expected = NullPointerException.class)
103 	public void testWithNullRegex() {
104 		new StrRegEx(null);
105 	}
106 	
107 	
108 
109 
110 	@Test(expected = IllegalArgumentException.class)
111 	public void testWithEmptyRegex() {
112 		new StrRegEx("");
113 	}
114 	
115 	
116 
117 
118 	@Test(expected = PatternSyntaxException.class)
119 	public void testWithInvalidRegex() {
120 		new StrRegEx("*****");
121 	}
122 	
123 	
124 
125 
126 	@Test(expected = SuperCsvCellProcessorException.class)
127 	public void testWithNull() {
128 		processor.execute(null, ANONYMOUS_CSVCONTEXT);
129 	}
130 	
131 }