This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 57
/
TranslationResourceRestTest.java
1376 lines (1175 loc) · 51.7 KB
/
TranslationResourceRestTest.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.zanata.rest.service;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.httpclient.URIException;
import org.dbunit.operation.DatabaseOperation;
import org.fedorahosted.tennera.jgettext.HeaderFields;
import org.hamcrest.Matchers;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.seam.security.Identity;
import org.jboss.seam.security.management.JpaIdentityStore;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.zanata.ZanataRestTest;
import org.zanata.common.ContentState;
import org.zanata.common.ContentType;
import org.zanata.common.LocaleId;
import org.zanata.common.MergeType;
import org.zanata.common.ProjectType;
import org.zanata.common.ResourceType;
import org.zanata.dao.AccountDAO;
import org.zanata.dao.ProjectIterationDAO;
import org.zanata.model.HAccount;
import org.zanata.model.HDocument;
import org.zanata.model.HLocale;
import org.zanata.model.HProject;
import org.zanata.model.HProjectIteration;
import org.zanata.model.HTextFlow;
import org.zanata.rest.RestUtil;
import org.zanata.rest.StringSet;
import org.zanata.rest.client.ISourceDocResource;
import org.zanata.rest.client.ITranslatedDocResource;
import org.zanata.rest.dto.Person;
import org.zanata.rest.dto.extensions.comment.SimpleComment;
import org.zanata.rest.dto.extensions.gettext.HeaderEntry;
import org.zanata.rest.dto.extensions.gettext.PoHeader;
import org.zanata.rest.dto.extensions.gettext.PoTargetHeader;
import org.zanata.rest.dto.extensions.gettext.PotEntryHeader;
import org.zanata.rest.dto.resource.AbstractResourceMeta;
import org.zanata.rest.dto.resource.Resource;
import org.zanata.rest.dto.resource.ResourceMeta;
import org.zanata.rest.dto.resource.TextFlow;
import org.zanata.rest.dto.resource.TextFlowTarget;
import org.zanata.rest.dto.resource.TranslationsResource;
import org.zanata.seam.SeamAutowire;
import org.zanata.security.ZanataIdentity;
import org.zanata.service.TranslationService;
import org.zanata.service.impl.CopyTransServiceImpl;
import org.zanata.service.impl.DocumentServiceImpl;
import org.zanata.service.impl.LocaleServiceImpl;
import org.zanata.service.impl.SecurityServiceImpl;
import org.zanata.service.impl.TranslationMergeServiceFactory;
import org.zanata.service.impl.TranslationServiceImpl;
import org.zanata.util.HashUtil;
import org.zanata.webtrans.server.TranslationWorkspace;
import org.zanata.webtrans.server.TranslationWorkspaceManager;
import org.zanata.webtrans.server.rpc.UpdateTransUnitHandler;
import org.zanata.webtrans.shared.model.ProjectIterationId;
import org.zanata.webtrans.shared.model.TransUnitId;
import org.zanata.webtrans.shared.model.TransUnitUpdateRequest;
import org.zanata.webtrans.shared.model.WorkspaceId;
import org.zanata.webtrans.shared.rpc.SessionEventData;
import org.zanata.webtrans.shared.rpc.TransUnitUpdated.UpdateType;
import org.zanata.webtrans.shared.rpc.UpdateTransUnit;
import org.zanata.webtrans.shared.rpc.UpdateTransUnitResult;
import com.google.common.collect.Lists;
import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isOneOf;
import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@Test(singleThreaded = true)
public class TranslationResourceRestTest extends ZanataRestTest
{
private static final Logger log = LoggerFactory.getLogger(TranslationResourceRestTest.class);
private static final String projectSlug = "sample-project";
private static final String iter = "1.1";
private static final String RESOURCE_PATH = "/projects/p/sample-project/iterations/i/1.0/r/";
private static final String BAD_RESOURCE_PATH = "/projects/p/nonexistentProject/iterations/i/99.9/r/";
private static final LocaleId DE = LocaleId.fromJavaName("de");
private static final LocaleId FR = LocaleId.fromJavaName("fr");
private static final String DOC2_NAME = "test.properties";
private static final String DOC1_NAME = "foo.properties";
StringSet extGettextComment = new StringSet("gettext;comment");
StringSet extComment = new StringSet("comment");
@Mock
private ZanataIdentity mockIdentity;
@Mock
private TranslationWorkspaceManager transWorspaceManager;
ISourceDocResource sourceDocResource;
ITranslatedDocResource transResource;
@BeforeClass
void beforeClass()
{
MockitoAnnotations.initMocks(this);
Identity.setSecurityEnabled(false);
}
@Override
protected void prepareDBUnitOperations()
{
beforeTestOperations.add(new DataSetOperation("org/zanata/test/model/ClearAllTables.dbunit.xml", DatabaseOperation.DELETE_ALL));
beforeTestOperations.add(new DataSetOperation("org/zanata/test/model/ProjectsData.dbunit.xml", DatabaseOperation.CLEAN_INSERT));
beforeTestOperations.add(new DataSetOperation("org/zanata/test/model/LocalesData.dbunit.xml", DatabaseOperation.CLEAN_INSERT));
beforeTestOperations.add(new DataSetOperation("org/zanata/test/model/AccountData.dbunit.xml", DatabaseOperation.CLEAN_INSERT));
}
@SuppressWarnings("serial")
@Override
protected void prepareResources()
{
SeamAutowire seamAutowire = getSeamAutowire();
seamAutowire
.use("session", getSession())
.use("identity", mockIdentity)
.use("translationWorkspaceManager", transWorspaceManager)
.use("entityManager", super.getEm())
.useImpl(CopyTransServiceImpl.class)
.useImpl(TranslationServiceImpl.class)
.useImpl(LocaleServiceImpl.class)
.useImpl(DocumentServiceImpl.class)
.useImpl(ResourceUtils.class)
.useImpl(SecurityServiceImpl.class);
TranslatedDocResourceService translatedDocResourceService = seamAutowire.autowire(TranslatedDocResourceService.class);
SourceDocResourceService sourceDocResourceService = seamAutowire.autowire(SourceDocResourceService.class);
resources.add(sourceDocResourceService);
resources.add(translatedDocResourceService);
}
@BeforeMethod(dependsOnMethods = "prepareRestEasyFramework")
public void createClient()
{
this.sourceDocResource = getClientRequestFactory().createProxy(ISourceDocResource.class, createBaseURI(RESOURCE_PATH));
this.transResource = getClientRequestFactory().createProxy(ITranslatedDocResource.class, createBaseURI(RESOURCE_PATH));
}
@Test
public void fetchEmptyListOfResources()
{
doGetandAssertThatResourceListContainsNItems(0);
}
@Test
public void createEmptyResource()
{
Resource sr = createSourceResource("my.txt");
ClientResponse<String> response = sourceDocResource.post(sr, null, true);
assertThat(response.getResponseStatus(), is(Status.CREATED));
List<String> locationHeader = response.getHeaders().get("Location");
assertThat(locationHeader.size(), is(1));
assertThat(locationHeader.get(0), endsWith("r/my.txt"));
doGetandAssertThatResourceListContainsNItems(1);
}
@Test
public void createResourceWithContentUsingPost()
{
Resource sr = createSourceResource("my.txt");
TextFlow stf = new TextFlow("tf1", LocaleId.EN, "tf1");
sr.getTextFlows().add(stf);
ClientResponse<String> postResponse = sourceDocResource.post(sr, null, true);
assertThat(postResponse.getResponseStatus(), is(Status.CREATED));
postResponse = sourceDocResource.post(sr, null, true);
ClientResponse<Resource> resourceGetResponse = sourceDocResource.getResource("my.txt", null);
assertThat(resourceGetResponse.getResponseStatus(), is(Status.OK));
Resource gotSr = resourceGetResponse.getEntity();
assertThat(gotSr.getTextFlows().size(), is(1));
assertThat(gotSr.getTextFlows().get(0).getContents(), is(asList("tf1")));
}
@Test
public void createResourceWithContentUsingPut()
{
Resource sr = createSourceResource("my.txt");
TextFlow stf = new TextFlow("tf1", LocaleId.EN, "tf1");
sr.getTextFlows().add(stf);
ClientResponse<String> response = sourceDocResource.putResource("my.txt", sr, null);
assertThat(response.getResponseStatus(), is(Status.CREATED));
assertThat(response.getLocation().getHref(), endsWith("/r/my.txt"));
ClientResponse<Resource> resourceGetResponse = sourceDocResource.getResource("my.txt", null);
assertThat(resourceGetResponse.getResponseStatus(), is(Status.OK));
Resource gotSr = resourceGetResponse.getEntity();
assertThat(gotSr.getTextFlows().size(), is(1));
assertThat(gotSr.getTextFlows().get(0).getContents(), is(asList("tf1")));
}
@Test
public void createPoResourceWithPoHeader()
{
String docName = "my.txt";
String docUri = RestUtil.convertToDocumentURIId(docName);
Resource sr = createSourceResource(docName);
TextFlow stf = new TextFlow("tf1", LocaleId.EN, "tf1");
sr.getTextFlows().add(stf);
// @formatter:off
/*
TODO: move this into an AbstractResourceMeta test (PoHeader is valid for source documents, not target)
PoHeader poHeaderExt = new PoHeader("comment", new HeaderEntry("h1", "v1"), new HeaderEntry("h2", "v2"));
sr.getExtensions(true).add(poHeaderExt);
*/
// @formatter:on
ClientResponse<String> postResponse = sourceDocResource.post(sr, null, true); // new
// StringSet(PoHeader.ID));
assertThat(postResponse.getResponseStatus(), is(Status.CREATED));
doGetandAssertThatResourceListContainsNItems(1);
ClientResponse<Resource> resourceGetResponse = sourceDocResource.getResource(docUri, null);// new
// StringSet(PoHeader.ID));
assertThat(resourceGetResponse.getResponseStatus(), is(Status.OK));
Resource gotSr = resourceGetResponse.getEntity();
assertThat(gotSr.getTextFlows().size(), is(1));
assertThat(gotSr.getTextFlows().get(0).getContents(), is(asList("tf1")));
// @formatter:off
/*
TODO: move this into an AbstractResourceMeta test
assertThat(gotSr.getExtensions().size(), is(1));
PoHeader gotPoHeader = gotSr.getExtensions().findByType(PoHeader.class);
assertThat(gotPoHeader, notNullValue());
assertThat(poHeaderExt.getComment(), is(gotPoHeader.getComment()));
assertThat(poHeaderExt.getEntries(), is(gotPoHeader.getEntries()));
*/
// @formatter:on
}
// NB this test breaks in Maven if the dev profile is active (because of the
// imported testdata)
@Test
public void publishTranslations()
{
createResourceWithContentUsingPut();
TranslationsResource entity = new TranslationsResource();
TextFlowTarget target = new TextFlowTarget();
target.setResId("tf1");
target.setContents("hello world");
target.setState(ContentState.Approved);
target.setTranslator(new Person("root@localhost", "Admin user"));
entity.getTextFlowTargets().add(target);
LocaleId de_DE = new LocaleId("de");
ClientResponse<String> response = transResource.putTranslations("my.txt", de_DE, entity, null);
assertThat(response.getResponseStatus(), is(Status.OK));
ClientResponse<TranslationsResource> getResponse = transResource.getTranslations("my.txt", de_DE, null);
assertThat(getResponse.getResponseStatus(), is(Status.OK));
TranslationsResource entity2 = getResponse.getEntity();
assertThat(entity2.getTextFlowTargets().size(), is(entity.getTextFlowTargets().size()));
entity.getTextFlowTargets().clear();
// push an empty document
response = transResource.putTranslations("my.txt", de_DE, entity, null, MergeType.IMPORT.toString());
assertThat(response.getResponseStatus(), is(Status.OK));
getResponse = transResource.getTranslations("my.txt", de_DE, null, false, null);
assertThat(getResponse.getResponseStatus(), is(Status.OK));
}
@Test
public void getDocumentThatDoesntExist()
{
ClientResponse<Resource> clientResponse = sourceDocResource.getResource("my,doc,does,not,exist.txt", null);
assertThat(clientResponse.getResponseStatus(), is(Status.NOT_FOUND));
}
@Test
public void getDocument() throws URIException
{
String docName = "my/path/document.txt";
String docUri = RestUtil.convertToDocumentURIId(docName);
Resource resource = createSourceDoc(docName, false);
sourceDocResource.putResource(docUri, resource, null);
ClientResponse<ResourceMeta> response = sourceDocResource.getResourceMeta(docUri, null);
assertThat(response.getResponseStatus(), is(Status.OK));
ResourceMeta doc = response.getEntity();
assertThat(doc.getName(), is(docName));
assertThat(doc.getContentType(), is(ContentType.TextPlain));
assertThat(doc.getLang(), is(LocaleId.EN_US));
assertThat(doc.getRevision(), is(1));
/*
* Link link = doc.getLinks().findLinkByRel(Relationships.SELF);
* assertThat( link, notNullValue() ); assertThat(
* URIUtil.decode(link.getHref().toString()), endsWith(url+docUri) );
*
* link = doc.getLinks().findLinkByRel(Relationships.DOCUMENT_CONTAINER);
* assertThat( link, notNullValue() ); assertThat(
* link.getHref().toString(), endsWith("iterations/i/1.0") );
*/
}
@Test
public void getDocumentWithResources() throws URIException
{
LocaleId nbLocale = new LocaleId("de");
String docName = "my/path/document.txt";
String docUri = RestUtil.convertToDocumentURIId(docName);
Resource resource = createSourceDoc(docName, true);
sourceDocResource.putResource(docUri, resource, null);
TranslationsResource trans = createTargetDoc();
transResource.putTranslations(docUri, nbLocale, trans, null);
{
ClientResponse<Resource> response = sourceDocResource.getResource(docUri, null);
assertThat(response.getResponseStatus(), is(Status.OK));
Resource doc = response.getEntity();
assertThat(doc.getTextFlows().size(), is(1));
}
ClientResponse<TranslationsResource> response = transResource.getTranslations(docUri, nbLocale, null);
assertThat(response.getResponseStatus(), is(Status.OK));
TranslationsResource doc = response.getEntity();
assertThat("should have one textFlow", doc.getTextFlowTargets().size(), is(1));
TextFlowTarget tft = doc.getTextFlowTargets().get(0);
assertThat(tft, notNullValue());
assertThat("should have a textflow with this id", tft.getResId(), is("tf1"));
assertThat("expected de target", tft, notNullValue());
assertThat("expected translation for de", tft.getContents(), is(asList("hei verden")));
}
@Test
public void putNewDocument()
{
String docName = "my/fancy/document.txt";
String docUrl = RestUtil.convertToDocumentURIId(docName);
Resource doc = createSourceDoc(docName, false);
Response response = sourceDocResource.putResource(docUrl, doc, null);
assertThat(response.getStatus(), is(Status.CREATED.getStatusCode()));
assertThat(response.getMetadata().getFirst("Location").toString(), endsWith(RESOURCE_PATH + docUrl));
ClientResponse<Resource> documentResponse = sourceDocResource.getResource(docUrl, null);
assertThat(documentResponse.getResponseStatus(), is(Status.OK));
doc = documentResponse.getEntity();
assertThat(doc.getRevision(), is(1));
/*
* Link link = doc.getLinks().findLinkByRel(Relationships.SELF);
* assertThat(link, notNullValue()); assertThat(link.getHref().toString(),
* endsWith(url + docUrl));
*
* link = doc.getLinks().findLinkByRel(Relationships.DOCUMENT_CONTAINER);
* assertThat(link, notNullValue()); assertThat(link.getType(),
* is(MediaTypes.APPLICATION_ZANATA_PROJECT_ITERATION_XML));
*/
}
@Test
public void putDocWithDuplicateTextFlowIds() throws Exception
{
String docName = "testDoc";
String docUrl = RestUtil.convertToDocumentURIId(docName);
Resource doc = createSourceDoc(docName, false);
List<TextFlow> textFlows = doc.getTextFlows();
for (int i = 0; i < 2; i++)
{
TextFlow textFlow = new TextFlow("tf1");
textFlow.setContents("hello world!");
textFlows.add(textFlow);
}
ClientResponse<?> response = sourceDocResource.putResource(docUrl, doc, null);
assertThat(response.getStatus(), is(Status.BAD_REQUEST.getStatusCode()));
String message = (String) response.getEntity();
assertThat(message, containsString("tf1"));
}
@Test
public void putNewDocumentWithResources() throws Exception
{
String docName = "my/fancy/document.txt";
String docUrl = RestUtil.convertToDocumentURIId(docName);
Resource doc = createSourceDoc(docName, false);
List<TextFlow> textFlows = doc.getTextFlows();
textFlows.clear();
TextFlow textFlow = new TextFlow("tf1");
textFlow.setContents("hello world!");
textFlows.add(textFlow);
TextFlow tf3 = new TextFlow("tf3");
tf3.setContents("more text");
textFlows.add(tf3);
// Marshaller m = null;
// JAXBContext jc = JAXBContext.newInstance(Resource.class);
// m = jc.createMarshaller();
// m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// m.marshal(doc, System.out);
Response response = sourceDocResource.putResource(docUrl, doc, null);
assertThat(response.getStatus(), is(Status.CREATED.getStatusCode()));
assertThat(response.getMetadata().getFirst("Location").toString(), endsWith(RESOURCE_PATH + docUrl));
ClientResponse<Resource> documentResponse = sourceDocResource.getResource(docUrl, null);
assertThat(documentResponse.getResponseStatus(), is(Status.OK));
doc = documentResponse.getEntity();
assertThat(doc.getRevision(), is(1));
assertThat("Should have textFlows", doc.getTextFlows(), notNullValue());
assertThat("Should have 2 textFlows", doc.getTextFlows().size(), is(2));
assertThat("Should have tf1 textFlow", doc.getTextFlows().get(0).getId(), is("tf1"));
assertThat("Container1 should have tf3 textFlow", doc.getTextFlows().get(1).getId(), is(tf3.getId()));
textFlow = doc.getTextFlows().get(0);
textFlow.setId("tf2");
response = sourceDocResource.putResource(docUrl, doc, null);
// this WAS testing for status 205
assertThat(response.getStatus(), is(200));
documentResponse = sourceDocResource.getResource(docUrl, null);
assertThat(documentResponse.getResponseStatus(), is(Status.OK));
doc = documentResponse.getEntity();
assertThat(doc.getRevision(), is(2));
assertThat("Should have textFlows", doc.getTextFlows(), notNullValue());
assertThat("Should have two textFlows", doc.getTextFlows().size(), is(2));
assertThat("should have same id", doc.getTextFlows().get(0).getId(), is("tf2"));
}
@Test
public void getZero() throws Exception
{
expectDocs(true, false);
}
@Test
public void put1Get() throws Exception
{
getZero();
Resource doc1 = putDoc1(false);
doc1.setRevision(1);
TextFlow tf1 = doc1.getTextFlows().get(0);
tf1.setRevision(1);
TranslationsResource target1 = putTarget1();
TextFlowTarget tft1 = target1.getTextFlowTargets().get(0);
tft1.setTextFlowRevision(1);
tft1.setRevision(1);
expectDocs(true, false, doc1);
expectTarget1(target1);
}
@Test
public void put1Post2Get() throws Exception
{
getZero();
Resource doc1 = putDoc1(false);
doc1.setRevision(1);
TextFlow tf1 = doc1.getTextFlows().get(0);
tf1.setRevision(1);
TranslationsResource target1 = putTarget1();
TextFlowTarget tft1 = target1.getTextFlowTargets().get(0);
tft1.setTextFlowRevision(1);
tft1.setRevision(1);
expectDocs(true, false, doc1);
expectTarget1(target1);
Resource doc2 = postDoc2(false);
doc2.setRevision(1);
TextFlow tf2 = doc2.getTextFlows().get(0);
tf2.setRevision(1);
TranslationsResource target2 = putTarget2();
TextFlowTarget tft2 = target2.getTextFlowTargets().get(0);
tft2.setTextFlowRevision(1);
tft2.setRevision(1);
expectDocs(true, false, doc1, doc2);
expectTarget1(target1);
expectTarget2(target2);
}
@Test
public void put1Post2Put1() throws Exception
{
getZero();
Resource doc1 = putDoc1(false);
doc1.setRevision(1);
TextFlow tf1 = doc1.getTextFlows().get(0);
tf1.setRevision(1);
TranslationsResource target1 = putTarget1();
TextFlowTarget tft1 = target1.getTextFlowTargets().get(0);
tft1.setTextFlowRevision(1);
Resource doc2 = postDoc2(false);
doc2.setRevision(1);
TextFlow tf2 = doc2.getTextFlows().get(0);
tf2.setRevision(1);
TranslationsResource target2 = putTarget2();
TextFlowTarget tft2 = target2.getTextFlowTargets().get(0);
tft2.setTextFlowRevision(1);
expectDocs(true, false, doc1, doc2);
tft1.setRevision(1);
tft2.setRevision(1);
expectTarget1(target1);
expectTarget2(target2);
// this put should have the effect of deleting doc2
putDoc1(false);
deleteDoc2();
// should be identical to doc1 from before, including revisions
expectDocs(true, false, doc1);
expectTarget1(target1);
dontExpectTarget2();
// expectTargets(true, FR, target2);
// use dao to check that doc2 is marked obsolete
verifyObsoleteDocument(doc2.getName());
}
@Test
public void put1Delete1Put1() throws Exception
{
getZero();
Resource doc1 = putDoc1(false);
doc1.setRevision(1);
TextFlow tf1 = doc1.getTextFlows().get(0);
tf1.setRevision(1);
TranslationsResource target1 = putTarget1();
TextFlowTarget tft1 = target1.getTextFlowTargets().get(0);
tft1.setTextFlowRevision(1);
expectDocs(true, false, doc1);
tft1.setRevision(1);
expectTarget1(target1);
deleteDoc1(); // doc1 becomes obsolete
getZero();
dontExpectTarget1();
putDoc1(false); // doc1 resurrected, rev 1
doc1.setRevision(1);
tf1.setRevision(1);
tft1.setTextFlowRevision(1);
expectDocs(true, false, doc1);
expectTarget1(target1);
}
@Test
public void put1Put1Again() throws Exception
{
getZero();
Resource doc1 = putDoc1(false);
doc1.setRevision(1);
TextFlow tf1 = doc1.getTextFlows().get(0);
tf1.setRevision(1);
TranslationsResource target1 = putTarget1();
TextFlowTarget tft1 = target1.getTextFlowTargets().get(0);
tft1.setTextFlowRevision(1);
tft1.setRevision(1);
expectDocs(true, false, doc1);
expectTarget1(target1);
putDoc1(false); // docRev still 1
doc1.setRevision(1);
tf1.setRevision(1);
tft1.setTextFlowRevision(1);
expectDocs(true, false, doc1);
expectTarget1(target1);
}
public void put1Put1WithAnotherTextFlow()
{
// TODO make sure tft1 is still there even though the doc rev goes up
}
@Test
public void put1Delete1Put1a() throws Exception
{
getZero();
Resource doc1 = putDoc1(false);
doc1.setRevision(1);
TextFlow tf1 = doc1.getTextFlows().get(0);
tf1.setRevision(1);
TranslationsResource target1 = putTarget1();
TextFlowTarget tft1 = target1.getTextFlowTargets().get(0);
tft1.setTextFlowRevision(1);
expectDocs(true, false, doc1);
tft1.setRevision(1);
expectTarget1(target1);
deleteDoc1(); // doc1 becomes obsolete
getZero();
dontExpectTarget1();
Resource doc1a = putDoc1a(false); // doc1 resurrected, rev 2
doc1a.setRevision(2);
TextFlow tf1a = doc1a.getTextFlows().get(0);
tf1a.setRevision(doc1a.getRevision());
TranslationsResource target1a = putTarget1a();
TextFlowTarget tft1a = target1a.getTextFlowTargets().get(0);
tft1a.setTextFlowRevision(tf1a.getRevision());
tft1a.setRevision(1);
expectDocs(true, false, doc1a);
dontExpectTarget1();
expectTarget1a(target1a);
}
@Test
public void putPoPotGet() throws Exception
{
getZero();
Resource po1 = putPo1();
expectDocs(false, false, po1);
TranslationsResource poTarget1 = putPoTarget1();
expectTarget(false, po1.getName(), DE, poTarget1);
}
@Test
public void put1Put1aPut1() throws Exception
{
getZero();
Resource doc1 = putDoc1(false);
doc1.setRevision(1);
TextFlow tf1 = doc1.getTextFlows().get(0);
tf1.setRevision(1);
TranslationsResource target1 = putTarget1();
TextFlowTarget tft1 = target1.getTextFlowTargets().get(0);
tft1.setTextFlowRevision(1);
tft1.setRevision(1);
expectDocs(true, false, doc1);
expectTarget1(target1);
// this should completely replace doc1's textflow FOOD with HELLO
Resource doc1a = putDoc1a(false);
doc1a.setRevision(2);
TextFlow tf1a = doc1a.getTextFlows().get(0);
tf1a.setRevision(2);
TranslationsResource target1a = putTarget1a();
TextFlowTarget tft1a = target1a.getTextFlowTargets().get(0);
tft1a.setTextFlowRevision(2);
tft1a.setRevision(1);
expectDocs(true, false, doc1a);
dontExpectTarget1();
expectTarget1a(target1a);
// use dao to check that the HTextFlow FOOD (from doc1) is marked obsolete
verifyObsoleteResource(doc1.getName(), "FOOD");
putDoc1(false); // same as original doc1, but different doc rev
doc1.setRevision(3);
expectDocs(true, false, doc1);
// target 1 should be resurrected
expectTarget1(target1);
dontExpectTarget1a();
}
@Test
public void generatedPoHeaders() throws Exception
{
LocaleId de_DE = new LocaleId("de");
getZero();
publishTranslations(); // push some translations (with no headers)
// Get the translations with PO headers
ClientResponse<TranslationsResource> response = transResource.getTranslations(
"my.txt", de_DE, new StringSet("gettext"), true, null);
TranslationsResource translations = response.getEntity();
assertThat(translations.getExtensions().size(), greaterThan(0));
// List of custom Zanata headers that should be present
final String[] requiredHeaders = new String[]{HeaderFields.KEY_LastTranslator, HeaderFields.KEY_PoRevisionDate,
HeaderFields.KEY_LanguageTeam, "X-Generator", HeaderFields.KEY_Language};
for( String reqHeader : requiredHeaders )
{
boolean headerFound = false;
for( HeaderEntry entry : translations.getExtensions().findByType(PoTargetHeader.class).getEntries() )
{
if( entry.getKey().equals(reqHeader) )
{
headerFound = true;
}
}
assertThat("PO Target Header '" + reqHeader + "' was not present when pulling translations.", headerFound, is(true));
}
// Since it is a first push with no headers, the Last Translator and Last Revision Date header should be empty
for( HeaderEntry entry : translations.getExtensions().findByType(PoTargetHeader.class).getEntries() )
{
if( entry.getKey().equals(HeaderFields.KEY_LastTranslator) || entry.getKey().equals(HeaderFields.KEY_PoRevisionDate) )
{
assertThat( entry.getValue().trim(), is("") );
}
}
}
@Test
public void headersBeforeTranslating() throws Exception
{
LocaleId de_DE = new LocaleId("de");
getZero();
// Push a document with no translations
createResourceWithContentUsingPut();
// Get the translations with PO headers
ClientResponse<TranslationsResource> response = transResource.getTranslations(
"my.txt", de_DE, new StringSet("gettext"), true, null);
TranslationsResource translations = response.getEntity();
assertThat( translations.getTextFlowTargets().size(), is(0) ); // Expecting no translations
// Make sure the headers are populated
PoTargetHeader header = translations.getExtensions(true).findByType(PoTargetHeader.class);
assertThat(header, notNullValue());
assertThat(header.getEntries().size(), greaterThan(0));
// Make sure the header values are empty since the system does not have any information for them
for( HeaderEntry entry : header.getEntries() )
{
if( entry.getKey().equals(HeaderFields.KEY_LastTranslator) )
{
assertThat( entry.getValue().trim(), is("") );
}
else if( entry.getKey().equals(HeaderFields.KEY_PoRevisionDate) )
{
assertThat( entry.getValue().trim(), is("") );
}
}
}
@Test
public void headersFromOriginalPush() throws Exception
{
LocaleId de_DE = new LocaleId("de");
getZero();
// Push a document and its translations
createResourceWithContentUsingPut();
TranslationsResource entity = new TranslationsResource();
TextFlowTarget target = new TextFlowTarget();
target.setResId("tf1");
target.setContents("hello world");
target.setState(ContentState.Approved);
target.setTranslator(new Person("root@localhost", "Admin user"));
entity.getTextFlowTargets().add(target);
// Future Date for the PO Revision Date Header
Calendar poRevDate = Calendar.getInstance();
poRevDate.add(Calendar.YEAR, 1); // 1 year in the future
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mmZ");
// Add initial headers to the translations
PoTargetHeader transHeader = new PoTargetHeader();
transHeader.getEntries().add( new HeaderEntry(HeaderFields.KEY_LastTranslator, "Test User <test@zanata.org>") );
transHeader.getEntries().add( new HeaderEntry(HeaderFields.KEY_PoRevisionDate, dateFormat.format(poRevDate.getTime())) ); // Date in the future
entity.getExtensions(true).add( transHeader );
// Push the translations
ClientResponse<String> putResponse = transResource.putTranslations("my.txt", de_DE, entity, new StringSet("gettext"));
assertThat(putResponse.getResponseStatus(), is(Status.OK));
// Get the translations with PO headers
ClientResponse<TranslationsResource> transResponse = transResource.getTranslations("my.txt", de_DE, new StringSet("gettext"));
TranslationsResource translations = transResponse.getEntity();
// Make sure the headers are populated
PoTargetHeader header = translations.getExtensions(true).findByType(PoTargetHeader.class);
assertThat(header, notNullValue());
assertThat(header.getEntries().size(), greaterThan(0));
// Make sure the header values are the same as the ones pushed with the document
for( HeaderEntry entry : header.getEntries() )
{
if( entry.getKey().equals(HeaderFields.KEY_LastTranslator) )
{
assertThat( entry.getValue().trim(), is("Test User <test@zanata.org>") );
}
else if( entry.getKey().equals(HeaderFields.KEY_PoRevisionDate) )
{
assertThat( entry.getValue().trim(), is( dateFormat.format(poRevDate.getTime()) ) );
}
}
}
@Test
public void headersAfterTranslating() throws Exception
{
LocaleId de_DE = new LocaleId("de");
getZero();
// Push a document and its translations
createResourceWithContentUsingPut();
TranslationsResource entity = new TranslationsResource();
TextFlowTarget target = new TextFlowTarget();
target.setResId("tf1");
target.setContents("hello world");
target.setState(ContentState.Approved);
target.setTranslator(new Person("root@localhost", "Admin user"));
entity.getTextFlowTargets().add(target);
ClientResponse<String> putResponse = transResource.putTranslations("my.txt", de_DE, entity, null);
assertThat(putResponse.getResponseStatus(), is(Status.OK));
// Get the translations with PO headers
ClientResponse<TranslationsResource> response = transResource.getTranslations("my.txt", de_DE, new StringSet("gettext"));
TranslationsResource translations = response.getEntity();
assertThat( translations.getTextFlowTargets().size(), greaterThan(0) );
// Now translate and push them again
for( TextFlowTarget tft : translations.getTextFlowTargets() )
{
tft.setContents("Translated");
tft.setState(ContentState.Approved);
}
putResponse = transResource.putTranslations("my.txt", de_DE, translations, null);
assertThat(putResponse.getStatus(), is(Response.Status.OK.getStatusCode()));
// Fetch the translations again
response = transResource.getTranslations("my.txt", de_DE, new StringSet("gettext"));
translations = response.getEntity();
assertThat( translations.getTextFlowTargets().size(), greaterThan(0) );
// Make sure the headers are now populated
PoTargetHeader header = translations.getExtensions(true).findByType(PoTargetHeader.class);
assertThat(header, notNullValue());
assertThat(header.getEntries().size(), greaterThan(0));
// Make sure the headers have the correct value
for( HeaderEntry entry : header.getEntries() )
{
if( entry.getKey().equals(HeaderFields.KEY_LastTranslator) )
{
assertThat( entry.getValue().trim(), is("Administrator <root@localhost>") );
}
else if( entry.getKey().equals(HeaderFields.KEY_PoRevisionDate) )
{
assertThat( entry.getValue().trim().length(), greaterThan(0) );
}
}
}
// TODO This test is randomly failing. It should be replaced with an Arquillian integration test where
// multiple transactions can be reliably tested.
@Test(enabled = false)
public void headersAfterWebtransEdit() throws Exception
{
LocaleId de_de = new LocaleId("de");
getZero();
// Push a document with no translations
createResourceWithContentUsingPut();
super.newSession();
this.prepareResources(); // Reset Seam as part of new transaction simulation
AccountDAO accountDAO = getSeamAutowire().autowire(AccountDAO.class);
// Translator
HAccount translator = accountDAO.getByUsername("demo");
// Translate using the web editor
this.simulateWebEditorTranslation("sample-project", "1.0", "my.txt", "tf1", translator, de_de, "Translated", ContentState.Approved);
super.newSession();
this.prepareResources(); // Reset Seam as part of new transaction simulation
// Fetch the translations again
ClientResponse<TranslationsResource> response = transResource.getTranslations("my.txt", de_de, new StringSet("gettext"));
TranslationsResource translations = response.getEntity();
assertThat( translations.getTextFlowTargets().size(), greaterThan(0) );
// Make sure the headers are present
PoTargetHeader header = translations.getExtensions(true).findByType(PoTargetHeader.class);
assertThat(header, notNullValue());
assertThat(header.getEntries().size(), greaterThan(0));
// Make sure the headers have the correct value
for( HeaderEntry entry : header.getEntries() )
{
if( entry.getKey().equals(HeaderFields.KEY_LastTranslator) )
{
assertThat( entry.getValue().trim(), is("Sample User <user1@localhost>") );
}
else if( entry.getKey().equals(HeaderFields.KEY_PoRevisionDate) )
{
assertThat( entry.getValue().trim().length(), greaterThan(0) );
}
}
}
@Test
public void getBadProject() throws Exception
{
ISourceDocResource badSourceResource = getClientRequestFactory().createProxy(ISourceDocResource.class, createBaseURI(BAD_RESOURCE_PATH));
ClientResponse<List<ResourceMeta>> response = badSourceResource.get(null);
assertThat(response.getStatus(), is(404));
}
// END of tests
/**
* Simulates the translation of a Unit using the web editor. Only suitable for non-plural translations.
*
* @param projectSlug Project
* @param iterationSlug Project Iteration
* @param docId Document Id
* @param textFlowContent Text Flow's content
* @param translator The user that does the translation
* @param localeId Locale for the translation
* @param translation The translated text
* @param translationState The new state for the translation (can be null if no changes are needed)
*/
private void simulateWebEditorTranslation(String projectSlug, String iterationSlug, String docId, String textFlowContent,
HAccount translator, LocaleId localeId, String translation, ContentState translationState )
throws Exception
{
SeamAutowire seamAutowire = getSeamAutowire();
// Mock certain objects
TranslationWorkspace transWorkspace = mock(TranslationWorkspace.class);
WorkspaceId workspaceId = new WorkspaceId(new ProjectIterationId(projectSlug, iterationSlug, ProjectType.Podir), localeId);
// Set mock expectations
when(transWorspaceManager.getOrRegisterWorkspace(any(WorkspaceId.class))).thenReturn(transWorkspace);
seamAutowire.use(JpaIdentityStore.AUTHENTICATED_USER, translator); // use a given authenticated account
seamAutowire.use("translationServiceImpl", seamAutowire.autowire(TranslationServiceImpl.class));// TODO because translationService component has already been created in prepareResource and have a wrong HAccount injected
UpdateTransUnitHandler transUnitHandler = seamAutowire.autowire(UpdateTransUnitHandler.class);
// Translation unit id to update
HTextFlow hTextFlow = (HTextFlow) getSession().createQuery("select tf from HTextFlow tf where tf.contentHash = ? and " +
"tf.document.docId = ? and " +
"tf.document.projectIteration.slug = ? and " +
"tf.document.projectIteration.project.slug = ?")
.setString(0, HashUtil.generateHash(textFlowContent))
.setString(1, docId)
.setString(2, iterationSlug)
.setString(3, projectSlug)
.uniqueResult();
Long textFlowId = hTextFlow.getId();
int versionNum = 0; // no previous translation
// Translate using webtrans
UpdateType updateType = (translationState == ContentState.Approved ? UpdateType.WebEditorSave : UpdateType.WebEditorSaveFuzzy);
UpdateTransUnit action = new UpdateTransUnit(new TransUnitUpdateRequest(new TransUnitId(textFlowId), Lists.newArrayList(translation), translationState, versionNum), updateType);
action.setWorkspaceId( workspaceId );
UpdateTransUnitResult result = transUnitHandler.execute(action, null);
assertThat(result.isSingleSuccess(), is(true));
verify(mockIdentity).checkLoggedIn();