1 // Copyright 2020 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package com.google.api.generator.gapic.composer.samplecode; 16 17 import static junit.framework.TestCase.assertEquals; 18 import static org.junit.Assert.assertThrows; 19 20 import com.google.api.generator.testutils.LineFormatter; 21 import org.junit.Test; 22 23 public class SampleBodyJavaFormatterTest { 24 25 @Test validFormatSampleCode_tryCatchStatement()26 public void validFormatSampleCode_tryCatchStatement() { 27 String samplecode = LineFormatter.lines("try(boolean condition = false){", "int x = 3;", "}"); 28 String result = SampleBodyJavaFormatter.format(samplecode); 29 String expected = 30 LineFormatter.lines("try (boolean condition = false) {\n", " int x = 3;\n", "}"); 31 assertEquals(expected, result); 32 } 33 34 @Test validFormatSampleCode_longLineStatement()35 public void validFormatSampleCode_longLineStatement() { 36 String sampleCode = 37 "SubscriptionAdminSettings subscriptionAdminSettings = " 38 + "SubscriptionAdminSettings.newBuilder().setEndpoint(myEndpoint).build();"; 39 String result = SampleBodyJavaFormatter.format(sampleCode); 40 String expected = 41 LineFormatter.lines( 42 "SubscriptionAdminSettings subscriptionAdminSettings =\n", 43 " SubscriptionAdminSettings.newBuilder().setEndpoint(myEndpoint).build();"); 44 assertEquals(expected, result); 45 } 46 47 @Test validFormatSampleCode_longChainMethod()48 public void validFormatSampleCode_longChainMethod() { 49 String sampleCode = 50 "echoSettingsBuilder.echoSettings().setRetrySettings(" 51 + "echoSettingsBuilder.echoSettings().getRetrySettings().toBuilder()" 52 + ".setTotalTimeout(Duration.ofSeconds(30)).build());"; 53 String result = SampleBodyJavaFormatter.format(sampleCode); 54 String expected = 55 LineFormatter.lines( 56 "echoSettingsBuilder\n", 57 " .echoSettings()\n", 58 " .setRetrySettings(\n", 59 " echoSettingsBuilder\n", 60 " .echoSettings()\n", 61 " .getRetrySettings()\n", 62 " .toBuilder()\n", 63 " .setTotalTimeout(Duration.ofSeconds(30))\n", 64 " .build());"); 65 assertEquals(expected, result); 66 } 67 68 @Test invalidFormatSampleCode_nonStatement()69 public void invalidFormatSampleCode_nonStatement() { 70 assertThrows( 71 SampleBodyJavaFormatter.FormatException.class, 72 () -> { 73 SampleBodyJavaFormatter.format("abc"); 74 }); 75 } 76 } 77