├── .gitignore ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── netflix │ │ └── testingdemo │ │ ├── TestingDemoApplication.java │ │ └── lolomo │ │ ├── ai │ │ ├── AiConfig.java │ │ └── OpenAiService.java │ │ ├── config │ │ └── LolomoApplicationConfig.java │ │ ├── datafetchers │ │ ├── CustomDgsExceptionHandler.java │ │ ├── LolomoDataFetcher.java │ │ └── Top10NotAvailableException.java │ │ ├── repository │ │ ├── DataInitializer.java │ │ ├── ShowEntity.java │ │ └── ShowsRepository.java │ │ └── top10 │ │ └── Top10Service.java └── resources │ ├── application.yml │ └── schema │ └── schema.graphqls └── test ├── java └── com │ └── netflix │ └── testingdemo │ ├── EnableDatabaseTest.java │ ├── LolomoDataFetcherSpringTcTest.java │ ├── LolomoDataFetcherSpringTest.java │ ├── LolomoDataFetcherUnitTest.java │ ├── LolomoTestConfiguration.java │ ├── SmokeTest.java │ ├── SmokeTestWithRequest.java │ └── testcontainers │ └── PostgresTestContainerConfig.java └── resources ├── schema.sql └── shows.sql /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '3.3.2' 4 | id 'io.spring.dependency-management' version '1.1.6' 5 | id 'com.netflix.dgs.codegen' version '6.2.3' 6 | } 7 | 8 | group = 'com.netflix' 9 | version = '0.0.1-SNAPSHOT' 10 | 11 | java { 12 | toolchain { 13 | languageVersion = JavaLanguageVersion.of(22) 14 | } 15 | } 16 | 17 | repositories { 18 | mavenCentral() 19 | maven { url 'https://repo.spring.io/milestone' } 20 | maven { url 'https://repo.spring.io/snapshot' } 21 | } 22 | 23 | ext { 24 | set('netflixDgsVersion', "9.1.0") 25 | } 26 | 27 | dependencies { 28 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 29 | implementation 'org.springframework.boot:spring-boot-starter-web' 30 | implementation 'com.netflix.graphql.dgs:graphql-dgs-spring-graphql-starter' 31 | implementation 'org.postgresql:postgresql' 32 | implementation platform("org.springframework.ai:spring-ai-bom:1.0.0-SNAPSHOT") 33 | implementation 'org.springframework.ai:spring-ai-openai-spring-boot-starter' 34 | 35 | testImplementation 'org.testcontainers:postgresql:1.20.1' 36 | testImplementation 'org.springframework.boot:spring-boot-testcontainers' 37 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 38 | implementation 'com.netflix.graphql.dgs:graphql-dgs-spring-graphql-starter-test' 39 | testRuntimeOnly 'org.junit.platform:junit-platform-launcher' 40 | } 41 | 42 | dependencyManagement { 43 | imports { 44 | mavenBom "com.netflix.graphql.dgs:graphql-dgs-platform-dependencies:${netflixDgsVersion}" 45 | } 46 | } 47 | 48 | tasks.named('test') { 49 | useJUnitPlatform() 50 | } 51 | 52 | 53 | generateJava{ 54 | schemaPaths = ["${projectDir}/src/main/resources/schema"] // List of directories containing schema files 55 | packageName = 'com.netflix.testingdemo.lolomo.generated' // The package name to use to generate sources 56 | generateClientv2 = true // Enable generating the type safe query API 57 | } 58 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/paulbakker/testing-spring-boot-presentation/0360748076622eaecee8672456fc46bef49deef7/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 1>&2 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 48 | echo. 1>&2 49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 50 | echo location of your Java installation. 1>&2 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 1>&2 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 62 | echo. 1>&2 63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 64 | echo location of your Java installation. 1>&2 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'testing-demo' 2 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/testingdemo/TestingDemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo; 2 | 3 | import com.netflix.testingdemo.lolomo.config.LolomoApplicationConfig; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 7 | 8 | @SpringBootApplication 9 | @EnableConfigurationProperties(LolomoApplicationConfig.class) 10 | public class TestingDemoApplication { 11 | public static void main(String[] args) { 12 | SpringApplication.run(TestingDemoApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/testingdemo/lolomo/ai/AiConfig.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo.lolomo.ai; 2 | 3 | import org.springframework.ai.chat.client.ChatClient; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | 7 | @Configuration 8 | public class AiConfig { 9 | @Bean 10 | ChatClient chatClient(ChatClient.Builder builder) { 11 | return builder.build(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/testingdemo/lolomo/ai/OpenAiService.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo.lolomo.ai; 2 | 3 | import com.netflix.testingdemo.lolomo.generated.types.Show; 4 | import com.netflix.testingdemo.lolomo.repository.ShowsRepository; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.ai.chat.client.ChatClient; 8 | import org.springframework.core.ParameterizedTypeReference; 9 | import org.springframework.stereotype.Service; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | import java.util.stream.Collectors; 14 | 15 | @Service 16 | public class OpenAiService { 17 | 18 | private final static Logger LOGGER = LoggerFactory.getLogger(OpenAiService.class); 19 | private final ChatClient chatClient; 20 | private final ShowsRepository showsRepository; 21 | 22 | public OpenAiService(ChatClient chatClient, ShowsRepository showsRepository) { 23 | this.chatClient = chatClient; 24 | this.showsRepository = showsRepository; 25 | } 26 | 27 | public List generateShowData() { 28 | LOGGER.info("Retrieving show titles from OpenAI"); 29 | 30 | var showTitles = chatClient.prompt() 31 | .system("The following list are the possible show categories: ACTION, DRAMA, DOCUMENTARY, HORROR, SPORT") 32 | .user("Give me 100 titles and their category with a short description of popular Netflix shows") 33 | .call().responseEntity(new ParameterizedTypeReference>() { 34 | }) 35 | .entity(); 36 | 37 | LOGGER.info("Found show titles from OpenAI: {}", showTitles); 38 | 39 | return showTitles; 40 | } 41 | 42 | public List top10(String country) { 43 | List titles = new ArrayList<>(); 44 | showsRepository.findAll().forEach(s -> titles.add(new TitleWithId(s.getTitle(), s.getId()))); 45 | 46 | var titleInput = titles.stream().map(s -> "[identifier: %d] %s".formatted(s.id, s.title)).collect(Collectors.joining(",")); 47 | var top10Titles = chatClient.prompt() 48 | .system("The following is the list of shows to consider. Each show has an identifier. %s".formatted(titleInput)) 49 | .user("Give me the identifiers and titles of the top 10 shows in %s".formatted(country)).call().entity(new ParameterizedTypeReference>() { 50 | }); 51 | 52 | LOGGER.info("Top 10: {}", top10Titles); 53 | 54 | return top10Titles.stream().map(TitleWithId::id).toList(); 55 | } 56 | 57 | record TitleWithId(String title, Long id){} 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/testingdemo/lolomo/config/LolomoApplicationConfig.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo.lolomo.config; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | @ConfigurationProperties(prefix = "lolomo") 6 | public class LolomoApplicationConfig { 7 | 8 | private boolean initializeShows; 9 | 10 | public boolean isInitializeShows() { 11 | return initializeShows; 12 | } 13 | 14 | public void setInitializeShows(boolean initializeShows) { 15 | this.initializeShows = initializeShows; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/testingdemo/lolomo/datafetchers/CustomDgsExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo.lolomo.datafetchers; 2 | 3 | import graphql.ErrorType; 4 | import graphql.GraphQLError; 5 | import org.springframework.graphql.data.method.annotation.GraphQlExceptionHandler; 6 | import org.springframework.web.bind.annotation.ControllerAdvice; 7 | 8 | @ControllerAdvice 9 | public class CustomDgsExceptionHandler { 10 | @GraphQlExceptionHandler 11 | public GraphQLError handle(Top10NotAvailableException ex) { 12 | return GraphQLError.newError() 13 | .errorType(ErrorType.DataFetchingException) 14 | .message("Top 10 unavailable").build(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/testingdemo/lolomo/datafetchers/LolomoDataFetcher.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo.lolomo.datafetchers; 2 | 3 | import com.netflix.graphql.dgs.DgsComponent; 4 | import com.netflix.graphql.dgs.DgsQuery; 5 | import com.netflix.graphql.dgs.InputArgument; 6 | import com.netflix.testingdemo.lolomo.generated.types.Category; 7 | import com.netflix.testingdemo.lolomo.generated.types.Show; 8 | import com.netflix.testingdemo.lolomo.repository.ShowEntity; 9 | import com.netflix.testingdemo.lolomo.repository.ShowsRepository; 10 | import com.netflix.testingdemo.lolomo.top10.Top10Service; 11 | 12 | import java.util.List; 13 | import java.util.Set; 14 | 15 | @DgsComponent 16 | public class LolomoDataFetcher { 17 | 18 | private final ShowsRepository showsRepository; 19 | private final Top10Service top10Service; 20 | private final Set supportedCountryCodes = Set.of("USA", "JPN", "NLD", "GBR"); 21 | 22 | public LolomoDataFetcher(Top10Service top10Service, ShowsRepository showsRepository) { 23 | this.top10Service = top10Service; 24 | this.showsRepository = showsRepository; 25 | } 26 | 27 | @DgsQuery 28 | public List top10(@InputArgument String countryCode) { 29 | countryCode = countryCode != null && !countryCode.isEmpty() ? countryCode: "USA"; 30 | 31 | if(!supportedCountryCodes.contains(countryCode)) { 32 | throw new Top10NotAvailableException(countryCode); 33 | } 34 | 35 | return top10Service.top10(countryCode); 36 | } 37 | 38 | @DgsQuery 39 | public List showsInCategory(@InputArgument Category category) { 40 | if(category == null) { 41 | throw new IllegalArgumentException("Required argument category is not provided"); 42 | } 43 | 44 | var shows = showsRepository.findByCategory(category.name()); 45 | return shows.stream().map(ShowEntity::asShow).toList(); 46 | } 47 | 48 | } 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/testingdemo/lolomo/datafetchers/Top10NotAvailableException.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo.lolomo.datafetchers; 2 | 3 | public class Top10NotAvailableException extends RuntimeException { 4 | public Top10NotAvailableException(String country) { 5 | super("A top 10 is not available for the given country code '" + country + "'"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/testingdemo/lolomo/repository/DataInitializer.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo.lolomo.repository; 2 | 3 | import com.netflix.testingdemo.lolomo.ai.OpenAiService; 4 | import com.netflix.testingdemo.lolomo.config.LolomoApplicationConfig; 5 | import jakarta.annotation.PostConstruct; 6 | import org.springframework.stereotype.Component; 7 | 8 | import java.util.Set; 9 | 10 | @Component 11 | public class DataInitializer { 12 | private final LolomoApplicationConfig lolomoApplicationConfig; 13 | private final ShowsRepository showsRepository; 14 | private final OpenAiService openAiService; 15 | 16 | public DataInitializer(LolomoApplicationConfig lolomoApplicationConfig, ShowsRepository showsRepository, OpenAiService openAiService) { 17 | this.lolomoApplicationConfig = lolomoApplicationConfig; 18 | this.showsRepository = showsRepository; 19 | this.openAiService = openAiService; 20 | } 21 | 22 | @PostConstruct 23 | public void initShows() { 24 | if(lolomoApplicationConfig.isInitializeShows()) { 25 | showsRepository.deleteAll(); 26 | 27 | var titles = openAiService.generateShowData(); 28 | 29 | titles.forEach(show -> { 30 | var showEntity = new ShowEntity(); 31 | showEntity.setTitle(show.getTitle()); 32 | showEntity.setDescription(show.getDescription()); 33 | showEntity.setCategories(Set.copyOf(show.getCategories())); 34 | showsRepository.save(showEntity); 35 | }); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/testingdemo/lolomo/repository/ShowEntity.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo.lolomo.repository; 2 | 3 | import com.netflix.testingdemo.lolomo.generated.types.Category; 4 | import com.netflix.testingdemo.lolomo.generated.types.Show; 5 | import jakarta.persistence.*; 6 | 7 | import java.util.Collections; 8 | import java.util.Objects; 9 | import java.util.Set; 10 | 11 | @Entity 12 | @Table(name = "shows") 13 | public class ShowEntity { 14 | 15 | @Id 16 | @GeneratedValue(strategy = GenerationType.IDENTITY) 17 | private Long id; 18 | 19 | private String title; 20 | 21 | private String description; 22 | 23 | @Enumerated(EnumType.STRING) 24 | private Set categories; 25 | 26 | public Long getId() { 27 | return id; 28 | } 29 | 30 | public void setId(Long id) { 31 | this.id = id; 32 | } 33 | 34 | public String getTitle() { 35 | return title; 36 | } 37 | 38 | public void setTitle(String title) { 39 | this.title = title; 40 | } 41 | 42 | public Set getCategories() { 43 | return categories; 44 | } 45 | 46 | public void setCategories(Set categories) { 47 | this.categories = categories; 48 | } 49 | 50 | public String getDescription() { 51 | return description; 52 | } 53 | 54 | public void setDescription(String description) { 55 | this.description = description; 56 | } 57 | 58 | @Override 59 | public boolean equals(Object o) { 60 | if (this == o) return true; 61 | if (o == null || getClass() != o.getClass()) return false; 62 | ShowEntity that = (ShowEntity) o; 63 | return Objects.equals(id, that.id) && Objects.equals(title, that.title) && Objects.equals(description, that.description) && Objects.equals(categories, that.categories); 64 | } 65 | 66 | @Override 67 | public int hashCode() { 68 | return Objects.hash(id, title, description, categories); 69 | } 70 | 71 | @Override 72 | public String toString() { 73 | return "ShowEntity{" + 74 | "id=" + id + 75 | ", title='" + title + '\'' + 76 | ", categories=" + categories + 77 | '}'; 78 | } 79 | 80 | public Show asShow() { 81 | return Show.newBuilder() 82 | .title(title) 83 | .description(description) 84 | .categories(categories != null ? categories.stream().toList() : Collections.emptyList()) 85 | .build(); 86 | } 87 | 88 | public static ShowEntity fromShow(Show show) { 89 | var entity = new ShowEntity(); 90 | entity.setTitle(show.getTitle()); 91 | entity.setDescription(show.getDescription()); 92 | entity.setCategories(Set.copyOf(show.getCategories())); 93 | return entity; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/testingdemo/lolomo/repository/ShowsRepository.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo.lolomo.repository; 2 | 3 | import org.springframework.data.jpa.repository.Query; 4 | import org.springframework.data.repository.CrudRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | import java.util.List; 8 | 9 | @Repository 10 | public interface ShowsRepository extends CrudRepository { 11 | @Query(value = "SELECT * from shows where ?1 = any(categories)", nativeQuery = true) 12 | List findByCategory(String category); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/testingdemo/lolomo/top10/Top10Service.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo.lolomo.top10; 2 | 3 | import com.netflix.testingdemo.lolomo.ai.OpenAiService; 4 | import com.netflix.testingdemo.lolomo.generated.types.Show; 5 | import com.netflix.testingdemo.lolomo.repository.ShowsRepository; 6 | import jakarta.annotation.PostConstruct; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.stereotype.Component; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | import java.util.Map; 14 | import java.util.concurrent.ConcurrentHashMap; 15 | 16 | @Component 17 | public class Top10Service { 18 | 19 | private final Logger LOGGER = LoggerFactory.getLogger(Top10Service.class); 20 | private final OpenAiService openAiService; 21 | private final ShowsRepository showsRepository; 22 | private final Map> cachedTop10 = new ConcurrentHashMap<>(); 23 | 24 | public Top10Service(OpenAiService openAiService, ShowsRepository showsRepository) { 25 | this.openAiService = openAiService; 26 | this.showsRepository = showsRepository; 27 | } 28 | 29 | @PostConstruct 30 | public void prefetchTop10Data() { 31 | 32 | LOGGER.info("Prefetching top 10"); 33 | var usa = top10("USA"); 34 | if(!usa.isEmpty()) { 35 | cachedTop10.put("USA", usa); 36 | } 37 | var jpn = top10("JPN"); 38 | if(!jpn.isEmpty()) { 39 | cachedTop10.put("JPN", jpn); 40 | } 41 | LOGGER.info("Completed prefetching top 10 for countries: {}", cachedTop10.keySet()); 42 | } 43 | 44 | public List top10(String country) { 45 | if(cachedTop10.containsKey(country)) { 46 | return cachedTop10.get(country); 47 | } else { 48 | List shows = new ArrayList<>(); 49 | var top10ShowsFromAI = openAiService.top10(country); 50 | showsRepository.findAllById(top10ShowsFromAI).forEach(show -> shows.add(show.asShow())); 51 | return shows; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: testing-demo 4 | datasource: 5 | url: jdbc:postgresql://localhost:5432/postgres 6 | username: postgres 7 | password: mysecretpassword 8 | jpa: 9 | show-sql: true 10 | hibernate: 11 | ddl-auto: none 12 | logging: 13 | level: 14 | org: 15 | hibernate: 16 | tool: 17 | hbm2ddl: debug 18 | lolomo: 19 | initialize-shows: false 20 | -------------------------------------------------------------------------------- /src/main/resources/schema/schema.graphqls: -------------------------------------------------------------------------------- 1 | type Query { 2 | top10(countryCode: String = ""): [Show] 3 | watchAgain: [Show] 4 | showsInCategory(category: Category!): [Show] 5 | } 6 | 7 | enum Category { 8 | ACTION 9 | DRAMA 10 | DOCUMENTARY 11 | HORROR 12 | SPORT 13 | } 14 | 15 | type Show { 16 | title: String 17 | description: String 18 | categories: [Category] 19 | } 20 | -------------------------------------------------------------------------------- /src/test/java/com/netflix/testingdemo/EnableDatabaseTest.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo; 2 | 3 | import com.netflix.testingdemo.testcontainers.PostgresTestContainerConfig; 4 | import org.springframework.boot.autoconfigure.domain.EntityScan; 5 | import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; 6 | import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureDataJpa; 7 | import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestEntityManager; 8 | import org.springframework.context.annotation.Import; 9 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 10 | 11 | import java.lang.annotation.ElementType; 12 | import java.lang.annotation.Retention; 13 | import java.lang.annotation.RetentionPolicy; 14 | import java.lang.annotation.Target; 15 | 16 | @Target(ElementType.TYPE) 17 | @Retention(RetentionPolicy.RUNTIME) 18 | 19 | @EnableJpaRepositories(basePackages = "com.netflix.testingdemo.lolomo.repository") 20 | @EntityScan("com.netflix.testingdemo.lolomo.repository") 21 | @AutoConfigureDataJpa 22 | @AutoConfigureTestEntityManager 23 | @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) 24 | @Import(PostgresTestContainerConfig.class) 25 | public @interface EnableDatabaseTest { 26 | } 27 | -------------------------------------------------------------------------------- /src/test/java/com/netflix/testingdemo/LolomoDataFetcherSpringTcTest.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo; 2 | 3 | import com.jayway.jsonpath.TypeRef; 4 | import com.netflix.graphql.dgs.DgsQueryExecutor; 5 | import com.netflix.graphql.dgs.test.EnableDgsTest; 6 | import com.netflix.testingdemo.lolomo.datafetchers.LolomoDataFetcher; 7 | import com.netflix.testingdemo.lolomo.generated.types.Category; 8 | import com.netflix.testingdemo.lolomo.generated.types.Show; 9 | import com.netflix.testingdemo.lolomo.repository.ShowsRepository; 10 | import com.netflix.testingdemo.lolomo.top10.Top10Service; 11 | import org.intellij.lang.annotations.Language; 12 | import org.junit.jupiter.api.Test; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.boot.test.context.SpringBootTest; 15 | 16 | import java.util.List; 17 | 18 | import static org.assertj.core.api.Assertions.assertThat; 19 | 20 | @SpringBootTest(classes = {LolomoDataFetcher.class, ShowsRepository.class, Top10Service.class, LolomoTestConfiguration.class}) 21 | @EnableDgsTest 22 | @EnableDatabaseTest 23 | public class LolomoDataFetcherSpringTcTest { 24 | 25 | @Autowired 26 | DgsQueryExecutor dgsQueryExecutor; 27 | 28 | @Test 29 | void testTop10() { 30 | @Language("GraphQL") 31 | var query = """ 32 | query { 33 | top10(countryCode: "USA") { 34 | title 35 | categories 36 | } 37 | } 38 | """; 39 | 40 | var shows = dgsQueryExecutor.executeAndExtractJsonPathAsObject(query, "data.top10", new TypeRef>() { 41 | }); 42 | 43 | assertThat(shows).hasSize(10); 44 | assertThat(shows).extracting("title").containsExactly( 45 | "Stranger Things", 46 | "The Crown", 47 | "Tiger King", 48 | "Narcos", 49 | "Black Mirror", 50 | "The Haunting of Hill House", 51 | "Money Heist", 52 | "Making a Murderer", 53 | "13 Reasons Why", 54 | "The Witcher"); 55 | 56 | } 57 | 58 | @Test 59 | void testShowsInCategory() { 60 | @Language("GraphQL") 61 | var query = """ 62 | query { 63 | action: showsInCategory(category: ACTION) { 64 | title 65 | categories 66 | } 67 | 68 | sport: showsInCategory(category: SPORT) { 69 | title 70 | categories 71 | } 72 | } 73 | """; 74 | 75 | var actionShows = dgsQueryExecutor.executeAndExtractJsonPathAsObject(query, "data.action", new TypeRef>() { 76 | }); 77 | var sportShows = dgsQueryExecutor.executeAndExtractJsonPathAsObject(query, "data.sport", new TypeRef>() { 78 | }); 79 | 80 | assertThat(actionShows).allMatch(s -> s.getCategories().contains(Category.ACTION)); 81 | assertThat(sportShows).allMatch(s -> s.getCategories().contains(Category.SPORT)); 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/test/java/com/netflix/testingdemo/LolomoDataFetcherSpringTest.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo; 2 | 3 | import com.jayway.jsonpath.TypeRef; 4 | import com.netflix.graphql.dgs.DgsQueryExecutor; 5 | import com.netflix.graphql.dgs.test.EnableDgsTest; 6 | import com.netflix.testingdemo.lolomo.datafetchers.CustomDgsExceptionHandler; 7 | import com.netflix.testingdemo.lolomo.datafetchers.LolomoDataFetcher; 8 | import com.netflix.testingdemo.lolomo.generated.types.Category; 9 | import com.netflix.testingdemo.lolomo.generated.types.Show; 10 | import com.netflix.testingdemo.lolomo.repository.ShowEntity; 11 | import com.netflix.testingdemo.lolomo.repository.ShowsRepository; 12 | import com.netflix.testingdemo.lolomo.top10.Top10Service; 13 | import org.intellij.lang.annotations.Language; 14 | import org.junit.jupiter.api.Test; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.boot.test.context.SpringBootTest; 17 | import org.springframework.boot.test.mock.mockito.MockBean; 18 | 19 | import java.util.List; 20 | 21 | import static org.assertj.core.api.Assertions.assertThat; 22 | import static org.mockito.ArgumentMatchers.any; 23 | import static org.mockito.Mockito.when; 24 | 25 | @SpringBootTest(classes = {LolomoDataFetcher.class, Top10Service.class, CustomDgsExceptionHandler.class, LolomoTestConfiguration.class}) 26 | @EnableDgsTest 27 | public class LolomoDataFetcherSpringTest { 28 | 29 | @Autowired 30 | DgsQueryExecutor dgsQueryExecutor; 31 | 32 | @MockBean 33 | ShowsRepository showsRepository; 34 | 35 | private static final List SHOW_LIST = List.of( 36 | Show.newBuilder().title("Show 1").categories(List.of(Category.ACTION, Category.DRAMA)).build(), 37 | Show.newBuilder().title("Show 2").categories(List.of(Category.SPORT)).build(), 38 | Show.newBuilder().title("Show 3").categories(List.of(Category.DRAMA)).build() 39 | ); 40 | 41 | @Test 42 | void testTop10() { 43 | 44 | when(showsRepository.findAllById(any())).thenReturn(SHOW_LIST.stream().map(ShowEntity::fromShow).toList()); 45 | 46 | @Language("GraphQL") 47 | var query = """ 48 | query { 49 | top10(countryCode: "USA") { 50 | title 51 | categories 52 | } 53 | } 54 | """; 55 | 56 | var shows = dgsQueryExecutor.executeAndExtractJsonPathAsObject(query, "data.top10", new TypeRef>() { 57 | }); 58 | 59 | assertThat(shows).hasSize(3); 60 | } 61 | 62 | @Test 63 | void testTop10DefaultCountry() { 64 | 65 | when(showsRepository.findAllById(any())).thenReturn(SHOW_LIST.stream().map(ShowEntity::fromShow).toList()); 66 | 67 | @Language("GraphQL") 68 | var query = """ 69 | query { 70 | top10 { 71 | title 72 | categories 73 | } 74 | } 75 | """; 76 | 77 | var result = dgsQueryExecutor.execute(query); 78 | assertThat(result.getErrors()).isEmpty(); 79 | } 80 | 81 | @Test 82 | void testTop10UnsupportedCountry() { 83 | @Language("GraphQL") 84 | var query = """ 85 | query { 86 | top10(countryCode: "bogus") { 87 | title 88 | categories 89 | } 90 | } 91 | """; 92 | 93 | var result = dgsQueryExecutor.execute(query); 94 | assertThat(result.getErrors()).extracting("message").containsExactly("Top 10 unavailable"); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/test/java/com/netflix/testingdemo/LolomoDataFetcherUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo; 2 | 3 | import com.netflix.testingdemo.lolomo.datafetchers.LolomoDataFetcher; 4 | import com.netflix.testingdemo.lolomo.generated.types.Category; 5 | import com.netflix.testingdemo.lolomo.generated.types.Show; 6 | import com.netflix.testingdemo.lolomo.repository.ShowEntity; 7 | import com.netflix.testingdemo.lolomo.repository.ShowsRepository; 8 | import com.netflix.testingdemo.lolomo.top10.Top10Service; 9 | import org.junit.jupiter.api.BeforeEach; 10 | import org.junit.jupiter.api.Test; 11 | import org.junit.jupiter.api.extension.ExtendWith; 12 | import org.mockito.Mock; 13 | import org.mockito.junit.jupiter.MockitoExtension; 14 | 15 | import java.util.List; 16 | 17 | import static org.assertj.core.api.Assertions.assertThat; 18 | import static org.junit.jupiter.api.Assertions.assertThrows; 19 | import static org.mockito.Mockito.verify; 20 | import static org.mockito.Mockito.when; 21 | 22 | @ExtendWith(MockitoExtension.class) 23 | public class LolomoDataFetcherUnitTest { 24 | private static final List SHOW_LIST = List.of( 25 | Show.newBuilder().title("Show 1").build(), 26 | Show.newBuilder().title("Show 2").build(), 27 | Show.newBuilder().title("Show 3").build() 28 | ); 29 | @Mock 30 | Top10Service top10Service; 31 | 32 | @Mock 33 | ShowsRepository showsRepository; 34 | 35 | LolomoDataFetcher dataFetcher; 36 | 37 | @BeforeEach 38 | void setup() { 39 | dataFetcher = new LolomoDataFetcher(top10Service, showsRepository); 40 | } 41 | 42 | @Test 43 | void testTop10() { 44 | when(top10Service.top10("USA")).thenReturn(SHOW_LIST); 45 | var top10 = dataFetcher.top10("USA"); 46 | 47 | assertThat(top10).extracting("title").containsExactly("Show 1", "Show 2", "Show 3"); 48 | verify(top10Service).top10("USA"); 49 | } 50 | 51 | @Test 52 | void testTop10WithNoCountry() { 53 | when(top10Service.top10("USA")).thenReturn(SHOW_LIST); 54 | var top10 = dataFetcher.top10(null); 55 | 56 | assertThat(top10).extracting("title").containsExactly("Show 1", "Show 2", "Show 3"); 57 | verify(top10Service).top10("USA"); 58 | } 59 | 60 | @Test 61 | void testTop10WithEmptyCountry() { 62 | when(top10Service.top10("USA")).thenReturn(SHOW_LIST); 63 | var top10 = dataFetcher.top10(""); 64 | 65 | assertThat(top10).extracting("title").containsExactly("Show 1", "Show 2", "Show 3"); 66 | verify(top10Service).top10("USA"); 67 | } 68 | 69 | @Test 70 | void testShowsInCategories() { 71 | 72 | var showEntity1 = new ShowEntity(); 73 | showEntity1.setTitle("Show 1"); 74 | 75 | var showEntity2 = new ShowEntity(); 76 | showEntity2.setTitle("Show 2"); 77 | 78 | var showEntity3 = new ShowEntity(); 79 | showEntity3.setTitle("Show 3"); 80 | 81 | when(showsRepository.findByCategory(Category.ACTION.name())).thenReturn(List.of(showEntity1, showEntity2, showEntity3)); 82 | 83 | var shows = dataFetcher.showsInCategory(Category.ACTION); 84 | assertThat(shows).extracting("title").containsExactly("Show 1", "Show 2", "Show 3"); 85 | } 86 | 87 | @Test 88 | void testShowsInCategoriesWithoutCategory() { 89 | assertThrows(IllegalArgumentException.class, () -> dataFetcher.showsInCategory(null)); 90 | } 91 | } -------------------------------------------------------------------------------- /src/test/java/com/netflix/testingdemo/LolomoTestConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo; 2 | 3 | import com.netflix.testingdemo.lolomo.ai.OpenAiService; 4 | import org.springframework.boot.test.context.TestConfiguration; 5 | import org.springframework.context.annotation.Bean; 6 | 7 | import java.util.List; 8 | 9 | import static org.mockito.Mockito.mock; 10 | import static org.mockito.Mockito.when; 11 | 12 | @TestConfiguration 13 | public class LolomoTestConfiguration { 14 | @Bean 15 | OpenAiService openAiService() { 16 | var mock = mock(OpenAiService.class); 17 | when(mock.top10("USA")).thenReturn(List.of(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L)); 18 | return mock; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/com/netflix/testingdemo/SmokeTest.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class SmokeTest { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/com/netflix/testingdemo/SmokeTestWithRequest.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import org.intellij.lang.annotations.Language; 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.http.MediaType; 10 | import org.springframework.test.web.servlet.MockMvc; 11 | 12 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 13 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 14 | 15 | @SpringBootTest 16 | @AutoConfigureMockMvc 17 | public class SmokeTestWithRequest { 18 | @Autowired 19 | MockMvc mockMvc; 20 | 21 | @Autowired 22 | ObjectMapper objectMapper; 23 | 24 | @Test 25 | public void top10() throws Exception { 26 | @Language("GraphQL") 27 | var query = """ 28 | { 29 | top10(countryCode: "NLD") { 30 | title 31 | categories 32 | } 33 | } 34 | """; 35 | 36 | mockMvc.perform(post("/graphql") 37 | .secure(true) 38 | .content(objectMapper.writeValueAsBytes(new GraphqlRequest(query))) 39 | .contentType(MediaType.APPLICATION_JSON) 40 | .accept(MediaType.APPLICATION_JSON)) 41 | .andExpect(jsonPath("data.top10").isArray()) 42 | .andExpect(jsonPath("data.top10[0].title").exists()); 43 | } 44 | 45 | record GraphqlRequest(String query){} 46 | } 47 | -------------------------------------------------------------------------------- /src/test/java/com/netflix/testingdemo/testcontainers/PostgresTestContainerConfig.java: -------------------------------------------------------------------------------- 1 | package com.netflix.testingdemo.testcontainers; 2 | 3 | import org.springframework.boot.test.context.TestConfiguration; 4 | import org.springframework.boot.testcontainers.properties.TestcontainersPropertySourceAutoConfiguration; 5 | import org.springframework.boot.testcontainers.service.connection.ServiceConnection; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Import; 8 | import org.springframework.test.context.DynamicPropertyRegistry; 9 | import org.testcontainers.containers.PostgreSQLContainer; 10 | import org.testcontainers.utility.MountableFile; 11 | 12 | @TestConfiguration(proxyBeanMethods = false) 13 | @Import({ TestcontainersPropertySourceAutoConfiguration.class }) 14 | public class PostgresTestContainerConfig { 15 | 16 | @ServiceConnection 17 | @Bean 18 | PostgreSQLContainer postgreSQLContainer(DynamicPropertyRegistry properties) { 19 | var db = new PostgreSQLContainer("postgres"); 20 | 21 | db.withCopyFileToContainer(MountableFile.forClasspathResource("schema.sql"), 22 | "/docker-entrypoint-initdb.d/init.sql"); 23 | db.withInitScript("shows.sql"); 24 | 25 | properties.add("spring.datasource.url", db::getJdbcUrl); 26 | properties.add("spring.datasource.username", db::getUsername); 27 | properties.add("spring.datasource.password", db::getPassword); 28 | 29 | return db; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/resources/schema.sql: -------------------------------------------------------------------------------- 1 | create table shows (id bigint generated by default as identity, title varchar(255), description text, categories varchar[]) 2 | 3 | -------------------------------------------------------------------------------- /src/test/resources/shows.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO public.shows (id, title, description, categories) VALUES (1, 'Stranger Things', 'A group of kids in the 1980s uncover government experiments and supernatural forces.', '{HORROR,ACTION,DRAMA}'); 2 | INSERT INTO public.shows (id, title, description, categories) VALUES (2, 'The Crown', 'A dramatized history of the reign of Queen Elizabeth II.', '{DRAMA}'); 3 | INSERT INTO public.shows (id, title, description, categories) VALUES (3, 'Tiger King', 'A true crime documentary about the life of eccentric zookeeper Joe Exotic.', '{DOCUMENTARY}'); 4 | INSERT INTO public.shows (id, title, description, categories) VALUES (4, 'Narcos', 'The rise and fall of the notorious Colombian drug lord, Pablo Escobar.', '{DRAMA,ACTION}'); 5 | INSERT INTO public.shows (id, title, description, categories) VALUES (5, 'Black Mirror', 'An anthology series exploring a twisted, high-tech multiverse where humanity''s greatest innovations and darkest instincts collide.', '{HORROR,DRAMA}'); 6 | INSERT INTO public.shows (id, title, description, categories) VALUES (6, 'The Haunting of Hill House', 'A family confronts haunting memories of their old home and the terrifying events that drove them from it.', '{HORROR,DRAMA}'); 7 | INSERT INTO public.shows (id, title, description, categories) VALUES (7, 'Money Heist', 'A criminal mastermind plans the biggest heist in recorded history.', '{DRAMA,ACTION}'); 8 | INSERT INTO public.shows (id, title, description, categories) VALUES (8, 'Making a Murderer', 'A real-life thriller following Steven Avery, a man who was exonerated for one crime only to be accused of another.', '{DOCUMENTARY}'); 9 | INSERT INTO public.shows (id, title, description, categories) VALUES (9, '13 Reasons Why', 'A teenager''s suicide leads to a series of tapes revealing the reasons for her tragic decision.', '{DRAMA}'); 10 | INSERT INTO public.shows (id, title, description, categories) VALUES (10, 'The Witcher', 'Geralt of Rivia, a monster hunter, struggles to find his place in a world where people are often more wicked than beasts.', '{DRAMA,ACTION}'); 11 | INSERT INTO public.shows (id, title, description, categories) VALUES (11, 'The Last Dance', 'A chronicle of Michael Jordan and the 1990s Chicago Bulls.', '{SPORT,DOCUMENTARY}'); 12 | INSERT INTO public.shows (id, title, description, categories) VALUES (12, 'Ozark', 'A financial planner relocates his family to the Ozarks after a money-laundering scheme goes wrong.', '{DRAMA,ACTION}'); 13 | INSERT INTO public.shows (id, title, description, categories) VALUES (13, 'The Umbrella Academy', 'A dysfunctional family of adopted sibling superheroes reunites to solve the mystery of their father''s death.', '{DRAMA,ACTION}'); 14 | INSERT INTO public.shows (id, title, description, categories) VALUES (14, 'Mindhunter', 'FBI agents interview serial killers to understand how they think, in order to solve ongoing cases.', '{DRAMA}'); 15 | INSERT INTO public.shows (id, title, description, categories) VALUES (15, 'BoJack Horseman', 'A former sitcom star, BoJack Horseman, deals with addiction, self-loathing, and relationships.', '{DRAMA}'); 16 | INSERT INTO public.shows (id, title, description, categories) VALUES (16, 'The Keepers', 'An investigation into the unsolved murder of a nun and the dark secrets and pain that linger nearly five decades after her death.', '{DOCUMENTARY}'); 17 | INSERT INTO public.shows (id, title, description, categories) VALUES (17, 'Daredevil', 'A blind lawyer by day, vigilante by night, Matt Murdock fights crime as Daredevil.', '{DRAMA,ACTION}'); 18 | INSERT INTO public.shows (id, title, description, categories) VALUES (18, 'Unsolved Mysteries', 'Real-life mysteries and unsolved cases, from disappearances to shocking murders.', '{DOCUMENTARY}'); 19 | INSERT INTO public.shows (id, title, description, categories) VALUES (19, 'The Queen''s Gambit', 'An orphaned chess prodigy''s journey to become the world''s greatest chess player while battling addiction.', '{DRAMA}'); 20 | INSERT INTO public.shows (id, title, description, categories) VALUES (20, 'The Punisher', 'A former Marine out to punish the criminals responsible for his family''s murder finds himself ensnared in a military conspiracy.', '{DRAMA,ACTION}'); 21 | INSERT INTO public.shows (id, title, description, categories) VALUES (21, 'Don''t F**k with Cats: Hunting an Internet Killer', 'A group of online justice seekers track down a man who posted a video of himself killing kittens.', '{DOCUMENTARY}'); 22 | INSERT INTO public.shows (id, title, description, categories) VALUES (22, 'Breaking Bad', 'A high school chemistry teacher turned methamphetamine producer partners with a former student.', '{DRAMA}'); 23 | INSERT INTO public.shows (id, title, description, categories) VALUES (23, 'Cheer', 'Follows the competitive cheerleaders of Navarro College as they prepare for the biggest moment of their lives.', '{SPORT,DOCUMENTARY}'); 24 | INSERT INTO public.shows (id, title, description, categories) VALUES (24, 'The Stranger', 'A web of secrets sends family man Adam Price on a desperate quest to uncover the truth about the people closest to him.', '{DRAMA}'); 25 | INSERT INTO public.shows (id, title, description, categories) VALUES (25, 'Dark', 'A family saga with a supernatural twist, set in a German town where the disappearance of two young children exposes the relationships among four families.', '{DRAMA}'); 26 | INSERT INTO public.shows (id, title, description, categories) VALUES (26, 'Lucifer', 'Lucifer Morningstar, the Devil, relocates to Los Angeles and opens a nightclub while consulting for the LAPD.', '{DRAMA,ACTION}'); 27 | INSERT INTO public.shows (id, title, description, categories) VALUES (27, 'Haunted', 'Real people share their true stories of terrifying events and paranormal encounters.', '{HORROR,DOCUMENTARY}'); 28 | INSERT INTO public.shows (id, title, description, categories) VALUES (28, 'House of Cards', 'A ruthless politician will stop at nothing to conquer Washington, D.C., in this Emmy and Golden Globe-winning political drama.', '{DRAMA}'); 29 | INSERT INTO public.shows (id, title, description, categories) VALUES (29, 'You', 'A dangerously charming, intensely obsessive young man goes to extreme measures to insert himself into the lives of those he is transfixed by.', '{DRAMA}'); 30 | INSERT INTO public.shows (id, title, description, categories) VALUES (30, 'The Circle', 'Contestants compete in a reality show where they must win over each other via social media.', '{DOCUMENTARY}'); 31 | INSERT INTO public.shows (id, title, description, categories) VALUES (31, 'Ratched', 'A young nurse at a mental institution becomes jaded, bitter, and a downright monster to her patients.', '{DRAMA}'); 32 | INSERT INTO public.shows (id, title, description, categories) VALUES (32, 'The Innocent Man', 'A true-crime story based on John Grisham''s only nonfiction book, focusing on two murders in Ada, Oklahoma.', '{DOCUMENTARY}'); 33 | INSERT INTO public.shows (id, title, description, categories) VALUES (33, 'Bodyguard', 'A war veteran turned special protection officer is assigned to protect a controversial politician.', '{DRAMA,ACTION}'); 34 | INSERT INTO public.shows (id, title, description, categories) VALUES (34, 'Unbelievable', 'A teenager is charged with lying about her rape, and two female detectives investigate a spate of eerily similar attacks.', '{DRAMA}'); 35 | INSERT INTO public.shows (id, title, description, categories) VALUES (35, 'The Confession Tapes', 'True crime cases where people convicted of murder claim their confessions were coerced, involuntary or false.', '{DOCUMENTARY}'); 36 | INSERT INTO public.shows (id, title, description, categories) VALUES (36, 'GLOW', 'The Gorgeous Ladies of Wrestling navigate their way through personal and professional struggles.', '{SPORT,DRAMA}'); 37 | INSERT INTO public.shows (id, title, description, categories) VALUES (37, 'Sense8', 'Eight strangers from around the globe suddenly become mentally and emotionally linked.', '{DRAMA,ACTION}'); 38 | INSERT INTO public.shows (id, title, description, categories) VALUES (38, 'The OA', 'A young woman reappears after being missing for seven years and now has mysterious new abilities.', '{DRAMA}'); 39 | INSERT INTO public.shows (id, title, description, categories) VALUES (39, 'Wormwood', 'An exploration of the limits of knowledge about the past and the lengths we''ll go in our search for the truth.', '{DOCUMENTARY}'); 40 | INSERT INTO public.shows (id, title, description, categories) VALUES (40, 'The Spy', 'The real-life story of former Mossad agent Eli Cohen, who successfully went undercover in Syria.', '{DRAMA}'); 41 | INSERT INTO public.shows (id, title, description, categories) VALUES (41, 'The Great British Baking Show', 'Amateur bakers compete in a series of challenges to impress a panel of judges and win the title of Britain''s best.', '{DOCUMENTARY}'); 42 | INSERT INTO public.shows (id, title, description, categories) VALUES (42, 'Designated Survivor', 'A low-level Cabinet member suddenly becomes President after a catastrophic attack.', '{DRAMA,ACTION}'); 43 | INSERT INTO public.shows (id, title, description, categories) VALUES (43, 'The Pharmacist', 'A small-town pharmacist stakes a mission to save his community long before the opioid epidemic gained nationwide attention.', '{DOCUMENTARY}'); 44 | INSERT INTO public.shows (id, title, description, categories) VALUES (44, 'The Sinner', 'Detective Harry Ambrose investigates various atrocious murder cases and uncovers the hidden motives behind them.', '{DRAMA}'); 45 | INSERT INTO public.shows (id, title, description, categories) VALUES (45, 'Russian Doll', 'A woman repeatedly dies and relives the same night in an ongoing loop, trying to solve the mystery.', '{DRAMA}'); 46 | INSERT INTO public.shows (id, title, description, categories) VALUES (46, 'The Trials of Gabriel Fernandez', 'A harrowing account of the systemic failures that led to the tragic death of an eight-year-old boy.', '{DOCUMENTARY}'); 47 | INSERT INTO public.shows (id, title, description, categories) VALUES (47, 'Altered Carbon', 'In a future where consciousness is digitized and stored, a prisoner returns to life in a new body and must solve a mind-bending murder to win his freedom.', '{DRAMA,ACTION}'); 48 | INSERT INTO public.shows (id, title, description, categories) VALUES (48, 'The Society', 'A group of teenagers must learn to run their own community after the rest of the population mysteriously disappears.', '{DRAMA}'); 49 | INSERT INTO public.shows (id, title, description, categories) VALUES (49, 'The Protector', 'A young man discovers that he has special powers and must protect his city from an immortal enemy.', '{DRAMA,ACTION}'); 50 | INSERT INTO public.shows (id, title, description, categories) VALUES (50, 'The Disappearance of Madeleine McCann', 'An in-depth look at the disappearance of three-year-old Madeleine McCann while on holiday with her family.', '{DOCUMENTARY}'); 51 | INSERT INTO public.shows (id, title, description, categories) VALUES (51, 'Locke & Key', 'Three siblings move into a house filled with reality-bending keys and must protect them from a cunning demon.', '{HORROR,DRAMA}'); 52 | INSERT INTO public.shows (id, title, description, categories) VALUES (52, 'The End of the F***ing World', 'A budding teen psychopath and a rebel hungry for adventure embark on a star-crossed road trip.', '{DRAMA}'); 53 | INSERT INTO public.shows (id, title, description, categories) VALUES (53, 'The Staircase', 'Explores the life of Michael Peterson, his sprawling North Carolina family, and the suspicious death of his wife, Kathleen.', '{DOCUMENTARY}'); 54 | INSERT INTO public.shows (id, title, description, categories) VALUES (54, 'Daybreak', 'High school outcast Josh searches for his missing girlfriend in post-apocalyptic Glendale.', '{DRAMA,ACTION}'); 55 | INSERT INTO public.shows (id, title, description, categories) VALUES (55, 'The Confession Killer', 'Examines the story of Henry Lee Lucas, who confessed to hundreds of murders, and the truth behind his confessions.', '{DOCUMENTARY}'); 56 | INSERT INTO public.shows (id, title, description, categories) VALUES (56, 'Alias Grace', 'Based on Margaret Atwood''s novel, this miniseries follows Grace Marks, a convicted murderer who might be innocent.', '{DRAMA}'); 57 | INSERT INTO public.shows (id, title, description, categories) VALUES (57, 'The Spy Who Fell to Earth', 'Based on a best-selling book exploring the life and mysterious death of an Egyptian billionaire turned Israeli spy.', '{DOCUMENTARY}'); 58 | INSERT INTO public.shows (id, title, description, categories) VALUES (58, 'The Valhalla Murders', 'An Icelandic detective reluctantly partners with a Norwegian investigator to hunt down a serial killer.', '{DRAMA}'); 59 | INSERT INTO public.shows (id, title, description, categories) VALUES (59, 'The Devil Next Door', 'A Cleveland grandfather is brought to trial in Israel, accused of being the infamous Nazi death camp guard known as Ivan the Terrible.', '{DOCUMENTARY}'); 60 | INSERT INTO public.shows (id, title, description, categories) VALUES (60, 'Messiah', 'A CIA officer investigates a charismatic figure whose followers believe he can perform miracles.', '{DRAMA}'); 61 | INSERT INTO public.shows (id, title, description, categories) VALUES (61, 'Quicksand', 'After a school shooting, a high school student finds herself on trial for murder.', '{DRAMA}'); 62 | INSERT INTO public.shows (id, title, description, categories) VALUES (62, 'Dogs of Berlin', 'Two German police detectives investigate the murder of a famous Turkish-German soccer player.', '{DRAMA,ACTION}'); 63 | INSERT INTO public.shows (id, title, description, categories) VALUES (63, 'The Family', 'Investigates a conservative Christian group known as The Family and its influence on American politics.', '{DOCUMENTARY}'); 64 | INSERT INTO public.shows (id, title, description, categories) VALUES (64, 'I Am a Killer', 'Death row inmates recount their crimes and reflect on how their actions destroyed lives, including their own.', '{DOCUMENTARY}'); 65 | INSERT INTO public.shows (id, title, description, categories) VALUES (65, 'Alias JJ, la celebridad del mal', 'A look at the life of John Jairo Velásquez, a hitman for Pablo Escobar, after his surrender to authorities.', '{DRAMA}'); 66 | INSERT INTO public.shows (id, title, description, categories) VALUES (66, 'The Forest', 'In a small village, a teenage girl’s disappearance sets off a series of unsettling events.', '{DRAMA}'); 67 | INSERT INTO public.shows (id, title, description, categories) VALUES (67, 'American Vandal', 'A true-crime satire that explores the aftermath of a costly high school prank that left twenty-seven faculty cars vandalized.', '{DOCUMENTARY}'); 68 | INSERT INTO public.shows (id, title, description, categories) VALUES (68, 'The Rain', 'Six years after a brutal virus wipes out most of Scandinavia''s population, two siblings join a band of young survivors.', '{DRAMA}'); 69 | INSERT INTO public.shows (id, title, description, categories) VALUES (69, 'Unorthodox', 'A young woman flees her arranged marriage in Brooklyn and sets out on a journey of self-discovery in Berlin.', '{DRAMA}'); 70 | INSERT INTO public.shows (id, title, description, categories) VALUES (70, 'Sacred Games', 'A Mumbai police officer''s chance encounter with an enigmatic gangster launches him on a quest to save the city.', '{DRAMA,ACTION}'); 71 | INSERT INTO public.shows (id, title, description, categories) VALUES (71, 'The Mechanism', 'A scandal erupts in Brazil during an investigation of alleged government corruption via oil and construction companies.', '{DRAMA}'); 72 | INSERT INTO public.shows (id, title, description, categories) VALUES (72, 'Safe', 'After his teenage daughter goes missing, a widowed surgeon begins uncovering dark secrets about the people closest to him.', '{DRAMA}'); 73 | INSERT INTO public.shows (id, title, description, categories) VALUES (73, 'The Stranger', 'A web of secrets sends family man Adam Price on a desperate quest to uncover the truth about the people closest to him.', '{DRAMA}'); 74 | INSERT INTO public.shows (id, title, description, categories) VALUES (74, 'The I-Land', 'Ten people wake up on a treacherous island with no memory and soon discover this world is not as it seems.', '{DRAMA}'); 75 | INSERT INTO public.shows (id, title, description, categories) VALUES (75, 'When They See Us', 'Based on the true story of the Central Park Five, this series explores the lives of five African American teenagers who were wrongfully convicted of a brutal crime.', '{DRAMA}'); 76 | INSERT INTO public.shows (id, title, description, categories) VALUES (76, 'The Confession', 'A look into the coercive interrogation tactics used by police that often lead to false confessions.', '{DOCUMENTARY}'); 77 | INSERT INTO public.shows (id, title, description, categories) VALUES (77, 'The Night Comes For Us', 'An elite Triad enforcer turns against his own organization to protect a young girl, sparking a violent battle.', '{DRAMA,ACTION}'); 78 | INSERT INTO public.shows (id, title, description, categories) VALUES (78, 'The Serpent', 'The twisting, real-life story of Charles Sobhraj, a murderer, thief, and master of disguise, who was a hidden darkness in the mid-70s on Asia''s hippie trail.', '{DRAMA}'); 79 | INSERT INTO public.shows (id, title, description, categories) VALUES (79, 'The One', 'A DNA researcher helps discover a way to find the perfect partner, and creates a bold new matchmaking service.', '{DRAMA}'); 80 | INSERT INTO public.shows (id, title, description, categories) VALUES (80, 'Get Even', 'A group of teenage girls at an elite school form a secret society to expose bullies.', '{DRAMA}'); 81 | INSERT INTO public.shows (id, title, description, categories) VALUES (81, 'The Gift', 'A painter in Istanbul embarks on a personal journey as she unearths universal secrets about an Anatolian archaeological site.', '{DRAMA}'); 82 | INSERT INTO public.shows (id, title, description, categories) VALUES (82, 'The Mire', 'The 1980s-set Polish drama about a journalist who uncovers corruption and secrets hidden in a small town.', '{DRAMA}'); 83 | INSERT INTO public.shows (id, title, description, categories) VALUES (83, 'The Twelve', 'Twelve jurors must decide the fate of a woman accused of two murders, while their own lives are affected by the case.', '{DRAMA}'); 84 | INSERT INTO public.shows (id, title, description, categories) VALUES (84, 'The Woods', 'Evidence found on a body resurrects a prosecutor''s long-buried trauma and truth about his sister''s disappearance.', '{DRAMA}'); 85 | --------------------------------------------------------------------------------