]> WPIA git - gigi.git/blob - tests/org/cacert/gigi/testUtils/ManagedTest.java
ce60a295832584c5c6b282af91bee8ae1de52838
[gigi.git] / tests / org / cacert / gigi / testUtils / ManagedTest.java
1 package org.cacert.gigi.testUtils;
2
3 import static org.junit.Assert.assertNotEquals;
4 import static org.junit.Assert.assertTrue;
5
6 import java.io.BufferedReader;
7 import java.io.DataOutputStream;
8 import java.io.FileInputStream;
9 import java.io.IOException;
10 import java.io.InputStreamReader;
11 import java.io.OutputStream;
12 import java.io.UnsupportedEncodingException;
13 import java.net.HttpURLConnection;
14 import java.net.InetSocketAddress;
15 import java.net.URL;
16 import java.net.URLEncoder;
17 import java.nio.file.Files;
18 import java.nio.file.Paths;
19 import java.sql.PreparedStatement;
20 import java.sql.ResultSet;
21 import java.sql.SQLException;
22 import java.util.Properties;
23
24 import org.cacert.gigi.DevelLauncher;
25 import org.cacert.gigi.database.DatabaseConnection;
26 import org.cacert.gigi.testUtils.TestEmailReciever.TestMail;
27 import org.cacert.gigi.util.DatabaseManager;
28 import org.junit.After;
29 import org.junit.AfterClass;
30 import org.junit.BeforeClass;
31
32 public class ManagedTest {
33         private final String registerService = "/register";
34
35         private static TestEmailReciever ter;
36         private static Process gigi;
37         private static String url = "localhost:4443";
38
39         public static String getServerName() {
40                 return url;
41         }
42         static Properties testProps = new Properties();
43         static {
44                 InitTruststore.run();
45                 HttpURLConnection.setFollowRedirects(false);
46         }
47
48         @BeforeClass
49         public static void connectToServer() {
50                 try {
51                         testProps.load(new FileInputStream("config/test.properties"));
52                         if (!DatabaseConnection.isInited()) {
53                                 DatabaseConnection.init(testProps);
54                         }
55                         System.out.println("... purging Database");
56                         DatabaseManager.run(new String[]{
57                                         testProps.getProperty("sql.driver"),
58                                         testProps.getProperty("sql.url"),
59                                         testProps.getProperty("sql.user"),
60                                         testProps.getProperty("sql.password")});
61
62                         String type = testProps.getProperty("type");
63                         if (type.equals("local")) {
64                                 url = testProps.getProperty("server");
65                                 String[] parts = testProps.getProperty("mail").split(":", 2);
66                                 ter = new TestEmailReciever(new InetSocketAddress(parts[0],
67                                                 Integer.parseInt(parts[1])));
68                                 return;
69                         }
70                         url = "localhost:" + testProps.getProperty("serverPort");
71                         gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
72                         DataOutputStream toGigi = new DataOutputStream(
73                                         gigi.getOutputStream());
74                         System.out.println("... starting server");
75                         Properties mainProps = new Properties();
76                         mainProps.setProperty("host", "127.0.0.1");
77                         mainProps.setProperty("port", testProps.getProperty("serverPort"));
78                         mainProps.setProperty("emailProvider",
79                                         "org.cacert.gigi.email.TestEmailProvider");
80                         mainProps.setProperty("emailProvider.port", "8473");
81                         mainProps.setProperty("sql.driver",
82                                         testProps.getProperty("sql.driver"));
83                         mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
84                         mainProps
85                                         .setProperty("sql.user", testProps.getProperty("sql.user"));
86                         mainProps.setProperty("sql.password",
87                                         testProps.getProperty("sql.password"));
88
89                         byte[] cacerts = Files
90                                         .readAllBytes(Paths.get("config/cacerts.jks"));
91                         byte[] keystore = Files.readAllBytes(Paths
92                                         .get("config/keystore.pkcs12"));
93
94                         DevelLauncher.writeGigiConfig(toGigi, new byte[]{},
95                                         "changeit".getBytes(), mainProps, cacerts, keystore);
96                         toGigi.flush();
97                         // TODO wait for ready
98                         try {
99                                 Thread.sleep(3000);
100                         } catch (InterruptedException e) {
101                                 e.printStackTrace();
102                         }
103                         final BufferedReader br = new BufferedReader(new InputStreamReader(
104                                         gigi.getErrorStream()));
105                         String line;
106                         while ((line = br.readLine()) != null
107                                         && !line.contains("Server:main: Started")) {
108                                 System.err.println(line);
109                         }
110                         new Thread() {
111                                 @Override
112                                 public void run() {
113                                         String line;
114                                         try {
115                                                 while ((line = br.readLine()) != null) {
116                                                         System.err.println(line);
117                                                 }
118                                         } catch (IOException e) {
119                                                 e.printStackTrace();
120                                         }
121                                 }
122                         }.start();
123                         System.err.println(line);
124                         if (line == null) {
125                                 throw new Error("Server startup failed");
126                         }
127                         ter = new TestEmailReciever(
128                                         new InetSocketAddress("localhost", 8473));
129                 } catch (IOException e) {
130                         throw new Error(e);
131                 } catch (ClassNotFoundException e1) {
132                         e1.printStackTrace();
133                 } catch (SQLException e1) {
134                         e1.printStackTrace();
135                 }
136
137         }
138         @AfterClass
139         public static void tearDownServer() {
140                 String type = testProps.getProperty("type");
141                 if (type.equals("local")) {
142                         return;
143                 }
144                 gigi.destroy();
145         }
146
147         @After
148         public void removeMails() {
149                 ter.reset();
150         }
151
152         public TestMail waitForMail() {
153                 try {
154                         return ter.recieve();
155                 } catch (InterruptedException e) {
156                         throw new Error(e);
157                 }
158         }
159         public static TestEmailReciever getMailReciever() {
160                 return ter;
161         }
162         public String runRegister(String param) throws IOException {
163                 HttpURLConnection uc = (HttpURLConnection) new URL("https://"
164                                 + getServerName() + registerService).openConnection();
165                 uc.setDoOutput(true);
166                 uc.getOutputStream().write(param.getBytes());
167                 String d = IOUtils.readURL(uc);
168                 return d;
169         }
170         public String fetchStartErrorMessage(String d) throws IOException {
171                 String formFail = "<div class='formError'>";
172                 int idx = d.indexOf(formFail);
173                 assertNotEquals(-1, idx);
174                 String startError = d.substring(idx + formFail.length(), idx + 100)
175                                 .trim();
176                 return startError;
177         }
178
179         public void registerUser(String firstName, String lastName, String email,
180                         String password) {
181                 try {
182                         String query = "fname=" + URLEncoder.encode(firstName, "UTF-8")
183                                         + "&lname=" + URLEncoder.encode(lastName, "UTF-8")
184                                         + "&email=" + URLEncoder.encode(email, "UTF-8")
185                                         + "&pword1=" + URLEncoder.encode(password, "UTF-8")
186                                         + "&pword2=" + URLEncoder.encode(password, "UTF-8")
187                                         + "&day=1&month=1&year=1910&cca_agree=1";
188                         String data = fetchStartErrorMessage(runRegister(query));
189                         assertTrue(data, data.startsWith("</div>"));
190                 } catch (UnsupportedEncodingException e) {
191                         throw new Error(e);
192                 } catch (IOException e) {
193                         throw new Error(e);
194                 }
195         }
196         public int createVerifiedUser(String firstName, String lastName,
197                         String email, String password) {
198                 registerUser(firstName, lastName, email, password);
199                 try {
200                         TestMail tm = ter.recieve();
201                         String verifyLink = tm.extractLink();
202                         String[] parts = verifyLink.split("\\?");
203                         URL u = new URL("https://" + getServerName() + "/verify?"
204                                         + parts[1]);
205                         u.openStream().close();;
206                         PreparedStatement ps = DatabaseConnection.getInstance().prepare(
207                                         "SELECT id FROM users where email=?");
208                         ps.setString(1, email);
209                         ResultSet rs = ps.executeQuery();
210                         if (rs.next()) {
211                                 return rs.getInt(1);
212                         }
213                         throw new Error();
214                 } catch (InterruptedException e) {
215                         throw new Error(e);
216                 } catch (IOException e) {
217                         throw new Error(e);
218                 } catch (SQLException e) {
219                         throw new Error(e);
220                 }
221         }
222         public int createAssuranceUser(String firstName, String lastName,
223                         String email, String password) {
224                 int uid = createVerifiedUser(firstName, lastName, email, password);
225                 try {
226                         PreparedStatement ps = DatabaseConnection
227                                         .getInstance()
228                                         .prepare(
229                                                         "INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
230                         ps.setInt(1, uid);
231                         ps.setInt(2, 0);
232                         ps.execute();
233                         ps = DatabaseConnection.getInstance().prepare(
234                                         "INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
235                         ps.setInt(1, uid);
236                         ps.setInt(2, uid);
237                         ps.execute();
238
239                 } catch (SQLException e) {
240                         throw new Error(e);
241                 }
242                 return uid;
243         }
244         static int count = 0;
245         public String createUniqueName() {
246                 return "test" + System.currentTimeMillis() + "a" + (count++);
247         }
248         public String login(String email, String pw) throws IOException {
249                 URL u = new URL("https://" + getServerName() + "/login");
250                 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
251                 huc.setDoOutput(true);
252                 OutputStream os = huc.getOutputStream();
253                 String data = "username=" + URLEncoder.encode(email, "UTF-8")
254                                 + "&password=" + URLEncoder.encode(pw, "UTF-8");
255                 os.write(data.getBytes());
256                 os.flush();
257                 String headerField = huc.getHeaderField("Set-Cookie");
258                 headerField = headerField.substring(0, headerField.indexOf(';'));
259                 return headerField;
260         }
261 }