forked from GoogleCloudPlatform/java-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestIndexServletPostgres.java
More file actions
133 lines (111 loc) · 4.54 KB
/
Copy pathTestIndexServletPostgres.java
File metadata and controls
133 lines (111 loc) · 4.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.cloudsql;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.example.cloudsql.IndexServlet.TemplateData;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class TestIndexServletPostgres {
private static List<String> requiredEnvVars =
Arrays.asList("PG_USER", "PG_PASS", "PG_DB", "PG_CONNECTION_NAME");
private static DataSource pool;
private static String tableName;
public static void checkEnvVars() {
// Check that required env vars are set
requiredEnvVars.forEach((varName) -> {
assertWithMessage(
String.format("Environment variable '%s' must be set to perform these tests.", varName))
.that(System.getenv(varName)).isNotEmpty();
});
}
private static void createTable(DataSource pool) throws SQLException {
// Safely attempt to create the table schema.
tableName = String.format("votes_%s", UUID.randomUUID().toString().replace("-", ""));
try (Connection conn = pool.getConnection()) {
String stmt =
"CREATE TABLE IF NOT EXISTS "
+ tableName
+ " ( vote_id SERIAL NOT NULL, time_cast timestamp NOT NULL,"
+ " candidate CHAR(6) NOT NULL,"
+ " PRIMARY KEY (vote_id) );";
try (PreparedStatement createTableStatement = conn.prepareStatement(stmt);) {
createTableStatement.execute();
}
}
}
@BeforeClass
public static void createPool() throws SQLException {
checkEnvVars();
HikariConfig config = new HikariConfig();
config.setJdbcUrl(String.format("jdbc:postgresql:///%s", System.getenv("PG_DB")));
config.setUsername(System.getenv("PG_USER")); // e.g. "root", "mysql"
config.setPassword(System.getenv("PG_PASS")); // e.g. "my-password"
config.addDataSourceProperty("socketFactory", "com.google.cloud.sql.postgres.SocketFactory");
config.addDataSourceProperty("cloudSqlInstance", System.getenv("PG_CONNECTION_NAME"));
pool = new HikariDataSource(config);
createTable(pool);
}
@AfterClass
public static void dropTable() throws SQLException {
try (Connection conn = pool.getConnection()) {
String stmt = String.format("DROP TABLE %s;", tableName);
try (PreparedStatement createTableStatement = conn.prepareStatement(stmt);) {
createTableStatement.execute();
}
}
}
@Test
public void testGetTemplateData() throws Exception {
TemplateData templateData = new IndexServlet().getTemplateData(pool);
assertNotNull(templateData.tabCount);
assertNotNull(templateData.spaceCount);
assertNotNull(templateData.recentVotes);
}
@Test
public void testServletPost() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
ServletContext context = mock(ServletContext.class);
when(request.getServletContext()).thenReturn(context);
when(context.getAttribute("my-pool")).thenReturn(pool);
when(request.getParameter("team")).thenReturn("TABS");
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
when(response.getWriter()).thenReturn(writer);
new IndexServlet().doPost(request, response);
writer.flush();
assertTrue(stringWriter.toString().contains("Vote successfully cast for"));
}
}