forked from killbill/killbill
/
TestIntegrationBase.java
402 lines (334 loc) · 16 KB
/
TestIntegrationBase.java
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you 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.ning.billing.beatrix.integration;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.annotation.Nullable;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
import org.skife.jdbi.v2.IDBI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import com.ning.billing.account.api.Account;
import com.ning.billing.account.api.AccountData;
import com.ning.billing.account.api.AccountService;
import com.ning.billing.account.api.AccountUserApi;
import com.ning.billing.analytics.AnalyticsListener;
import com.ning.billing.analytics.api.user.DefaultAnalyticsUserApi;
import com.ning.billing.api.TestApiListener;
import com.ning.billing.api.TestApiListener.NextEvent;
import com.ning.billing.api.TestListenerStatus;
import com.ning.billing.beatrix.BeatrixTestSuiteWithEmbeddedDB;
import com.ning.billing.beatrix.lifecycle.Lifecycle;
import com.ning.billing.beatrix.util.InvoiceChecker;
import com.ning.billing.catalog.api.BillingPeriod;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.catalog.api.PlanPhaseSpecifier;
import com.ning.billing.catalog.api.PriceListSet;
import com.ning.billing.catalog.api.ProductCategory;
import com.ning.billing.dbi.MysqlTestingHelper;
import com.ning.billing.entitlement.api.EntitlementService;
import com.ning.billing.entitlement.api.timeline.EntitlementTimelineApi;
import com.ning.billing.entitlement.api.transfer.EntitlementTransferApi;
import com.ning.billing.entitlement.api.user.EntitlementUserApi;
import com.ning.billing.entitlement.api.user.EntitlementUserApiException;
import com.ning.billing.entitlement.api.user.Subscription;
import com.ning.billing.entitlement.api.user.SubscriptionData;
import com.ning.billing.invoice.api.Invoice;
import com.ning.billing.invoice.api.InvoiceItem;
import com.ning.billing.invoice.api.InvoiceService;
import com.ning.billing.invoice.api.InvoiceUserApi;
import com.ning.billing.invoice.model.InvoicingConfiguration;
import com.ning.billing.junction.plumbing.api.BlockingSubscription;
import com.ning.billing.mock.MockAccountBuilder;
import com.ning.billing.mock.api.MockBillCycleDay;
import com.ning.billing.overdue.wrapper.OverdueWrapperFactory;
import com.ning.billing.payment.api.PaymentApi;
import com.ning.billing.payment.api.PaymentApiException;
import com.ning.billing.payment.api.PaymentMethodPlugin;
import com.ning.billing.payment.provider.MockPaymentProviderPlugin;
import com.ning.billing.util.api.TagUserApi;
import com.ning.billing.util.bus.BusService;
import com.ning.billing.util.callcontext.CallContext;
import com.ning.billing.util.callcontext.CallOrigin;
import com.ning.billing.util.callcontext.DefaultCallContext;
import com.ning.billing.util.callcontext.DefaultCallContextFactory;
import com.ning.billing.util.callcontext.UserType;
import com.ning.billing.util.clock.ClockMock;
import com.google.common.base.Function;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
public class TestIntegrationBase extends BeatrixTestSuiteWithEmbeddedDB implements TestListenerStatus {
protected static final DateTimeZone testTimeZone = DateTimeZone.UTC;
protected static final int NUMBER_OF_DECIMALS = InvoicingConfiguration.getNumberOfDecimals();
protected static final int ROUNDING_METHOD = InvoicingConfiguration.getRoundingMode();
protected static final BigDecimal ONE = new BigDecimal("1.0000").setScale(NUMBER_OF_DECIMALS);
protected static final BigDecimal TWENTY_NINE = new BigDecimal("29.0000").setScale(NUMBER_OF_DECIMALS);
protected static final BigDecimal THIRTY = new BigDecimal("30.0000").setScale(NUMBER_OF_DECIMALS);
protected static final BigDecimal THIRTY_ONE = new BigDecimal("31.0000").setScale(NUMBER_OF_DECIMALS);
protected static final Logger log = LoggerFactory.getLogger(TestIntegration.class);
protected static long AT_LEAST_ONE_MONTH_MS = 32L * 24L * 3600L * 1000L;
protected static final long DELAY = 5000;
@Inject
protected IDBI dbi;
@Inject
protected ClockMock clock;
protected CallContext context;
@Inject
protected Lifecycle lifecycle;
@Inject
protected BusService busService;
@Inject
protected EntitlementService entitlementService;
@Inject
protected InvoiceService invoiceService;
@Inject
protected AccountService accountService;
@Inject
protected MysqlTestingHelper helper;
@Inject
protected EntitlementUserApi entitlementUserApi;
@Inject
protected EntitlementTransferApi transferApi;
@Inject
protected EntitlementTimelineApi repairApi;
@Inject
protected InvoiceUserApi invoiceUserApi;
@Inject
protected PaymentApi paymentApi;
@Named(BeatrixModule.PLUGIN_NAME)
@Inject
protected MockPaymentProviderPlugin paymentPlugin;
@Inject
protected OverdueWrapperFactory overdueWrapperFactory;
@Inject
protected AccountUserApi accountUserApi;
@Inject
protected DefaultAnalyticsUserApi analyticsUserApi;
@Inject
protected TagUserApi tagUserApi;
@Inject
protected AnalyticsListener analyticsListener;
@Inject
protected InvoiceChecker invoiceChecker;
protected TestApiListener busHandler;
private boolean isListenerFailed;
private String listenerFailedMsg;
@Override
public void failed(final String msg) {
isListenerFailed = true;
listenerFailedMsg = msg;
}
@Override
public void resetTestListenerStatus() {
isListenerFailed = false;
listenerFailedMsg = null;
}
protected void assertListenerStatus() {
if (isListenerFailed) {
log.error(listenerFailedMsg);
Assert.fail(listenerFailedMsg);
}
}
@BeforeClass(groups = "slow")
public void setup() throws Exception {
context = new DefaultCallContextFactory(clock).createCallContext("Integration Test", CallOrigin.TEST, UserType.TEST);
busHandler = new TestApiListener(this);
}
@BeforeMethod(groups = "slow")
public void setupTest() throws Exception {
log.warn("\n");
log.warn("RESET TEST FRAMEWORK\n\n");
clock.resetDeltaFromReality();
resetTestListenerStatus();
busHandler.reset();
// Start services
lifecycle.fireStartupSequencePriorEventRegistration();
busService.getBus().register(busHandler);
lifecycle.fireStartupSequencePostEventRegistration();
}
@AfterMethod(groups = "slow")
public void cleanupTest() throws Exception {
lifecycle.fireShutdownSequencePriorEventUnRegistration();
busService.getBus().unregister(busHandler);
lifecycle.fireShutdownSequencePostEventUnRegistration();
log.warn("DONE WITH TEST\n");
}
protected void verifyTestResult(final UUID accountId, final UUID subscriptionId,
final DateTime startDate, @Nullable final DateTime endDate,
final BigDecimal amount, final DateTime chargeThroughDate,
final int totalInvoiceItemCount) throws EntitlementUserApiException {
final SubscriptionData subscription = subscriptionDataFromSubscription(entitlementUserApi.getSubscriptionFromId(subscriptionId));
final List<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(accountId);
final List<InvoiceItem> invoiceItems = new ArrayList<InvoiceItem>();
for (final Invoice invoice : invoices) {
invoiceItems.addAll(invoice.getInvoiceItems());
}
assertEquals(invoiceItems.size(), totalInvoiceItemCount);
boolean wasFound = false;
// We implicitly assume here that the account timezone is the same as the one for startDate/endDate
for (final InvoiceItem item : invoiceItems) {
if (item.getStartDate().compareTo(new LocalDate(startDate)) == 0) {
if ((item.getEndDate() == null && endDate == null) || (item.getEndDate() != null && new LocalDate(endDate).compareTo(item.getEndDate()) == 0)) {
if (item.getAmount().compareTo(amount) == 0) {
wasFound = true;
break;
}
}
}
}
if (!wasFound) {
fail();
}
final DateTime ctd = subscription.getChargedThroughDate();
assertNotNull(ctd);
log.info("Checking CTD: " + ctd.toString() + "; clock is " + clock.getUTCNow().toString());
// Either the ctd is today (start of the trial) or the clock is strictly before the CTD
assertTrue(clock.getUTCToday().compareTo(new LocalDate(ctd)) == 0 || clock.getUTCNow().isBefore(ctd));
assertTrue(ctd.toDateTime(testTimeZone).toLocalDate().compareTo(new LocalDate(chargeThroughDate.getYear(), chargeThroughDate.getMonthOfYear(), chargeThroughDate.getDayOfMonth())) == 0);
}
protected SubscriptionData subscriptionDataFromSubscription(final Subscription sub) {
return (SubscriptionData) ((BlockingSubscription) sub).getDelegateSubscription();
}
protected Account createAccountWithPaymentMethod(final AccountData accountData) throws Exception {
final Account account = accountUserApi.createAccount(accountData, context);
assertNotNull(account);
final PaymentMethodPlugin info = new PaymentMethodPlugin() {
@Override
public boolean isDefaultPaymentMethod() {
return false;
}
@Override
public String getValueString(final String key) {
return null;
}
@Override
public List<PaymentMethodKVInfo> getProperties() {
return null;
}
@Override
public String getExternalPaymentMethodId() {
return UUID.randomUUID().toString();
}
};
paymentApi.addPaymentMethod(BeatrixModule.PLUGIN_NAME, account, true, info, context);
return accountUserApi.getAccountById(account.getId());
}
protected AccountData getAccountData(final int billingDay) {
return new MockAccountBuilder().name(UUID.randomUUID().toString().substring(1, 8))
.firstNameLength(6)
.email(UUID.randomUUID().toString().substring(1, 8))
.phone(UUID.randomUUID().toString().substring(1, 8))
.migrated(false)
.isNotifiedForInvoices(false)
.externalKey(UUID.randomUUID().toString().substring(1, 8))
.billingCycleDay(new MockBillCycleDay(billingDay))
.currency(Currency.USD)
.paymentMethodId(UUID.randomUUID())
.timeZone(DateTimeZone.UTC)
.build();
}
protected void addMonthsAndCheckForCompletion(final int nbMonth, final NextEvent... events) {
doCallAndCheckForCompletion(new Function<Void, Void>() {
@Override
public Void apply(@Nullable final Void dontcare) {
clock.addMonths(nbMonth);
return null;
}
}, events);
}
protected void addDaysAndCheckForCompletion(final int nbDays, final NextEvent... events) {
doCallAndCheckForCompletion(new Function<Void, Void>() {
@Override
public Void apply(@Nullable final Void dontcare) {
clock.addDays(nbDays);
return null;
}
}, events);
}
protected void createPaymentAndCheckForCompletion(final Account account, final Invoice invoice, final NextEvent... events) {
doCallAndCheckForCompletion(new Function<Void, Void>() {
@Override
public Void apply(@Nullable final Void input) {
try {
paymentApi.createPayment(account, invoice.getId(), invoice.getBalance(), new DefaultCallContext("test", null, null, clock));
} catch (PaymentApiException e) {
fail(e.toString());
}
return null;
}
}, events);
}
protected Subscription createSubscriptionAndCheckForCompletion(final UUID bundleId,
final String productName,
final ProductCategory productCategory,
final BillingPeriod billingPeriod,
final NextEvent... events) {
return doCallAndCheckForCompletion(new Function<Void, Subscription>() {
@Override
public Subscription apply(@Nullable final Void dontcare) {
try {
final Subscription subscription = entitlementUserApi.createSubscription(bundleId,
new PlanPhaseSpecifier(productName, productCategory, billingPeriod, PriceListSet.DEFAULT_PRICELIST_NAME, null),
null,
context);
assertNotNull(subscription);
return subscription;
} catch (EntitlementUserApiException e) {
fail();
return null;
}
}
}, events);
}
protected Subscription changeSubscriptionAndCheckForCompletion(final Subscription subscription,
final String productName,
final BillingPeriod billingPeriod,
final NextEvent... events) {
return doCallAndCheckForCompletion(new Function<Void, Subscription>() {
@Override
public Subscription apply(@Nullable final Void dontcare) {
try {
subscription.changePlan(productName, billingPeriod, PriceListSet.DEFAULT_PRICELIST_NAME, clock.getUTCNow(), context);
return subscription;
} catch (EntitlementUserApiException e) {
fail();
return null;
}
}
}, events);
}
private <T> T doCallAndCheckForCompletion(Function<Void, T> f, final NextEvent... events) {
log.info(" ************ STARTING BUS HANDLER CHECK ********************");
busHandler.pushExpectedEvents(events);
final T result = f.apply(null);
assertTrue(busHandler.isCompleted(DELAY));
assertListenerStatus();
log.info(" ************ DONE WITH BUS HANDLER CHECK ********************");
return result;
}
}