Add API for code owner backends

Having an abstraction for code owner backends allow us to support
different syntaxes and storages for code owner configurations.

For the start we have only a single method that allows us to get a code
owner config. Follow-up changes will add further methods (e.g. to
create/update code owner configs).

For testing the functionality we need to write a test code owner config
to a repository that we can then read through the new CodeOwnerBackend
API. This logic was already implemented in CodeOwnerConfigFileTest. To
avoid duplicating this logic, we extract it (and the logic to read code
owner configs directly from a repository) into a new FindOwnersTestUtil
class, which allows to reuse this logic from multiple tests.

Signed-off-by: Edwin Kempin <ekempin@google.com>
Change-Id: Id2799cf17efe9ef3695719730c5f9384d5539d84
diff --git a/java/com/google/gerrit/plugins/codeowners/backend/CodeOwnersBackend.java b/java/com/google/gerrit/plugins/codeowners/backend/CodeOwnersBackend.java
new file mode 100644
index 0000000..e069a7c
--- /dev/null
+++ b/java/com/google/gerrit/plugins/codeowners/backend/CodeOwnersBackend.java
@@ -0,0 +1,33 @@
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.gerrit.plugins.codeowners.backend;
+
+import java.util.Optional;
+
+/**
+ * Interface for code owner backends.
+ *
+ * <p>Allows to implement different syntaxes and storages for code owner configurations.
+ */
+public interface CodeOwnersBackend {
+  /**
+   * Gets the code owner config for the given key if it exists.
+   *
+   * @param codeOwnerConfigKey the code owner config key for which the code owner config should be
+   *     returned
+   * @return code owner config for the given key if it exists, otherwise {@link Optional#empty()}
+   */
+  Optional<CodeOwnerConfig> getCodeOwnerConfig(CodeOwnerConfig.Key codeOwnerConfigKey);
+}
diff --git a/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFile.java b/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFile.java
index a4a1b0b..06e2838 100644
--- a/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFile.java
+++ b/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFile.java
@@ -45,9 +45,10 @@
  * permanent (and hence written to repository) if {@link
  * #commit(com.google.gerrit.server.git.meta.MetaDataUpdate)} is called.
  */
-class CodeOwnerConfigFile extends VersionedMetaData {
+@VisibleForTesting
+public class CodeOwnerConfigFile extends VersionedMetaData {
   /** Name of the file in which the code owner config for a folder in a branch is stored. */
-  @VisibleForTesting static final String FILE_NAME = "OWNERS";
+  @VisibleForTesting public static final String FILE_NAME = "OWNERS";
 
   @Singleton
   static class Factory {
diff --git a/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigParser.java b/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigParser.java
index 044b773..01c4e66 100644
--- a/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigParser.java
+++ b/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigParser.java
@@ -16,6 +16,7 @@
 
 import static java.util.stream.Collectors.joining;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Splitter;
 import com.google.common.collect.Streams;
 import com.google.common.flogger.FluentLogger;
@@ -45,7 +46,8 @@
  * 'foo.bar@example.com # Foo Bar' would be invalid).
  */
 @Singleton
-class CodeOwnerConfigParser {
+@VisibleForTesting
+public class CodeOwnerConfigParser {
   private static final FluentLogger logger = FluentLogger.forEnclosingClass();
 
   /**
@@ -79,7 +81,9 @@
    * @param codeOwnerConfigFileContent string that represents the content of an {@code OWNERS} file
    * @return the parsed {@link CodeOwnerConfig}
    */
-  CodeOwnerConfig parse(CodeOwnerConfig.Key codeOwnerConfigKey, String codeOwnerConfigFileContent) {
+  @VisibleForTesting
+  public CodeOwnerConfig parse(
+      CodeOwnerConfig.Key codeOwnerConfigKey, String codeOwnerConfigFileContent) {
     CodeOwnerConfig.Builder codeOwnerConfig = CodeOwnerConfig.builder(codeOwnerConfigKey);
 
     Streams.stream(Splitter.on('\n').split(codeOwnerConfigFileContent))
@@ -100,7 +104,8 @@
    * @return the code owner config as string that represents the code owner config in an {@code
    *     OWNERS} file
    */
-  String formatAsString(CodeOwnerConfig codeOwnerConfig) {
+  @VisibleForTesting
+  public String formatAsString(CodeOwnerConfig codeOwnerConfig) {
     return codeOwnerConfig.codeOwners().stream()
         .map(CodeOwnerReference::email)
         .sorted()
diff --git a/java/com/google/gerrit/plugins/codeowners/backend/findowners/FindOwnersBackend.java b/java/com/google/gerrit/plugins/codeowners/backend/findowners/FindOwnersBackend.java
new file mode 100644
index 0000000..0da94e6
--- /dev/null
+++ b/java/com/google/gerrit/plugins/codeowners/backend/findowners/FindOwnersBackend.java
@@ -0,0 +1,44 @@
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.gerrit.plugins.codeowners.backend.findowners;
+
+import com.google.gerrit.exceptions.StorageException;
+import com.google.gerrit.plugins.codeowners.backend.CodeOwnerConfig;
+import com.google.gerrit.plugins.codeowners.backend.CodeOwnersBackend;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import java.io.IOException;
+import java.util.Optional;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+
+@Singleton
+public class FindOwnersBackend implements CodeOwnersBackend {
+  private final CodeOwnerConfigFile.Factory codeOwnerConfigFileFactory;
+
+  @Inject
+  FindOwnersBackend(CodeOwnerConfigFile.Factory codeOwnerConfigFileFactory) {
+    this.codeOwnerConfigFileFactory = codeOwnerConfigFileFactory;
+  }
+
+  @Override
+  public Optional<CodeOwnerConfig> getCodeOwnerConfig(CodeOwnerConfig.Key codeOwnerConfigKey) {
+    try {
+      return codeOwnerConfigFileFactory.load(codeOwnerConfigKey).getLoadedCodeOwnerConfig();
+    } catch (IOException | ConfigInvalidException e) {
+      throw new StorageException(
+          String.format("failed to load code owner config %s", codeOwnerConfigKey), e);
+    }
+  }
+}
diff --git a/java/com/google/gerrit/plugins/codeowners/testing/findowners/BUILD b/java/com/google/gerrit/plugins/codeowners/testing/findowners/BUILD
new file mode 100644
index 0000000..96745e0
--- /dev/null
+++ b/java/com/google/gerrit/plugins/codeowners/testing/findowners/BUILD
@@ -0,0 +1,16 @@
+load("@rules_java//java:defs.bzl", "java_library")
+
+package(default_testonly = True)
+
+java_library(
+    name = "testutil",
+    srcs = glob(["*.java"]),
+    visibility = ["//visibility:public"],
+    deps = [
+        "//java/com/google/gerrit/server",
+        "//lib:jgit",
+        "//lib:jgit-junit",
+        "//lib/guice",
+        "//plugins/code-owners:code-owners__plugin",
+    ],
+)
diff --git a/java/com/google/gerrit/plugins/codeowners/testing/findowners/FindOwnersTestUtil.java b/java/com/google/gerrit/plugins/codeowners/testing/findowners/FindOwnersTestUtil.java
new file mode 100644
index 0000000..f58468f
--- /dev/null
+++ b/java/com/google/gerrit/plugins/codeowners/testing/findowners/FindOwnersTestUtil.java
@@ -0,0 +1,100 @@
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.gerrit.plugins.codeowners.testing.findowners;
+
+import com.google.gerrit.plugins.codeowners.backend.CodeOwnerConfig;
+import com.google.gerrit.plugins.codeowners.backend.findowners.CodeOwnerConfigFile;
+import com.google.gerrit.plugins.codeowners.backend.findowners.CodeOwnerConfigParser;
+import com.google.gerrit.server.git.GitRepositoryManager;
+import com.google.inject.Inject;
+import java.util.Optional;
+import org.eclipse.jgit.junit.TestRepository;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevObject;
+import org.eclipse.jgit.treewalk.TreeWalk;
+import org.eclipse.jgit.util.RawParseUtils;
+
+/** Test utility to read/write find-owners code owner configs directly from/to a repository. */
+public class FindOwnersTestUtil {
+  private final GitRepositoryManager repoManager;
+  private final CodeOwnerConfigParser codeOwnerConfigParser;
+
+  @Inject
+  FindOwnersTestUtil(
+      GitRepositoryManager repoManager, CodeOwnerConfigParser codeOwnerConfigParser) {
+    this.repoManager = repoManager;
+    this.codeOwnerConfigParser = codeOwnerConfigParser;
+  }
+
+  /**
+   * Write a code owner config directly to a repository.
+   *
+   * <p>Requires that the repository and the branch in which the code owner config should be stored
+   * already exist.
+   *
+   * @param codeOwnerConfig the code owner config that should be written
+   */
+  public void writeCodeOwnerConfig(CodeOwnerConfig codeOwnerConfig) throws Exception {
+    String formattedCodeOwnerConfig = codeOwnerConfigParser.formatAsString(codeOwnerConfig);
+    try (TestRepository<Repository> testRepo =
+        new TestRepository<>(repoManager.openRepository(codeOwnerConfig.key().project()))) {
+      Ref ref = testRepo.getRepository().exactRef(codeOwnerConfig.key().ref());
+      RevCommit head = testRepo.getRevWalk().parseCommit(ref.getObjectId());
+      testRepo.update(
+          codeOwnerConfig.key().ref(),
+          testRepo
+              .commit()
+              .parent(head)
+              .message("Add test code owner config")
+              .add(
+                  codeOwnerConfig.key().filePathForJgit(CodeOwnerConfigFile.FILE_NAME),
+                  formattedCodeOwnerConfig));
+    }
+  }
+
+  /**
+   * Reads a code owner config directly from a repository.
+   *
+   * @param codeOwnerConfigKey the key of the code owner config that should be read
+   * @return the code owner config if it exist, otherwise {@link Optional#empty()}
+   */
+  public Optional<CodeOwnerConfig> readCodeOwnerConfig(CodeOwnerConfig.Key codeOwnerConfigKey)
+      throws Exception {
+    try (TestRepository<Repository> testRepo =
+        new TestRepository<>(repoManager.openRepository(codeOwnerConfigKey.project()))) {
+      Ref ref = testRepo.getRepository().exactRef(codeOwnerConfigKey.ref());
+      if (ref == null) {
+        // branch does not exist
+        return Optional.empty();
+      }
+
+      RevCommit commit = testRepo.getRevWalk().parseCommit(ref.getObjectId());
+      String filePath = codeOwnerConfigKey.filePathForJgit(CodeOwnerConfigFile.FILE_NAME);
+      try (TreeWalk tw =
+          TreeWalk.forPath(testRepo.getRevWalk().getObjectReader(), filePath, commit.getTree())) {
+        if (tw == null) {
+          // file does not exist
+          return Optional.empty();
+        }
+      }
+      RevObject blob = testRepo.get(commit.getTree(), filePath);
+      byte[] data = testRepo.getRepository().open(blob).getCachedBytes(Integer.MAX_VALUE);
+      return Optional.of(
+          codeOwnerConfigParser.parse(codeOwnerConfigKey, RawParseUtils.decode(data)));
+    }
+  }
+}
diff --git a/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/BUILD b/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/BUILD
index b32e5b7..ceb8b68 100644
--- a/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/BUILD
+++ b/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/BUILD
@@ -7,6 +7,7 @@
         "//plugins/code-owners:code-owners__plugin",
         "//plugins/code-owners/java/com/google/gerrit/plugins/codeowners/acceptance",
         "//plugins/code-owners/java/com/google/gerrit/plugins/codeowners/testing",
+        "//plugins/code-owners/java/com/google/gerrit/plugins/codeowners/testing/findowners:testutil",
     ],
 )
 
diff --git a/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFileTest.java b/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFileTest.java
index 3a0cf8d..da74dc5 100644
--- a/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFileTest.java
+++ b/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFileTest.java
@@ -25,16 +25,12 @@
 import com.google.gerrit.plugins.codeowners.backend.CodeOwnerConfig;
 import com.google.gerrit.plugins.codeowners.backend.CodeOwnerConfigUpdate;
 import com.google.gerrit.plugins.codeowners.backend.CodeOwnerReference;
+import com.google.gerrit.plugins.codeowners.testing.findowners.FindOwnersTestUtil;
 import com.google.gerrit.server.git.meta.MetaDataUpdate;
 import com.google.inject.Inject;
 import java.util.Optional;
-import org.eclipse.jgit.junit.TestRepository;
-import org.eclipse.jgit.lib.Ref;
 import org.eclipse.jgit.lib.Repository;
 import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevObject;
-import org.eclipse.jgit.treewalk.TreeWalk;
-import org.eclipse.jgit.util.RawParseUtils;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -42,14 +38,14 @@
 public class CodeOwnerConfigFileTest extends AbstractCodeOwnersTest {
   @Inject private MetaDataUpdate.Server metaDataUpdateServer;
 
+  private FindOwnersTestUtil findOwnersTestUtil;
   private CodeOwnerConfigFile.Factory codeOwnerConfigFileFactory;
-  private CodeOwnerConfigParser codeOwnerConfigParser;
 
   @Before
   public void setUpCodeOwnersPlugin() throws Exception {
+    findOwnersTestUtil = plugin.getSysInjector().getInstance(FindOwnersTestUtil.class);
     codeOwnerConfigFileFactory =
         plugin.getSysInjector().getInstance(CodeOwnerConfigFile.Factory.class);
-    codeOwnerConfigParser = plugin.getSysInjector().getInstance(CodeOwnerConfigParser.class);
   }
 
   @Test
@@ -72,7 +68,7 @@
   public void loadEmptyCodeOwnerConfigFile() throws Exception {
     CodeOwnerConfig.Key codeOwnerConfigKey = CodeOwnerConfig.Key.create(project, "master", "/");
     CodeOwnerConfig codeOwnerConfig = CodeOwnerConfig.builder(codeOwnerConfigKey).build();
-    writeCodeOwnerConfig(codeOwnerConfig);
+    findOwnersTestUtil.writeCodeOwnerConfig(codeOwnerConfig);
 
     CodeOwnerConfigFile codeOwnerConfigFile = codeOwnerConfigFileFactory.load(codeOwnerConfigKey);
     assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig()).isPresent();
@@ -84,7 +80,7 @@
     CodeOwnerConfig.Key codeOwnerConfigKey = CodeOwnerConfig.Key.create(project, "master", "/");
     CodeOwnerConfig codeOwnerConfig =
         CodeOwnerConfig.builder(codeOwnerConfigKey).addCodeOwnerEmail(admin.email()).build();
-    writeCodeOwnerConfig(codeOwnerConfig);
+    findOwnersTestUtil.writeCodeOwnerConfig(codeOwnerConfig);
 
     CodeOwnerConfigFile codeOwnerConfigFile = codeOwnerConfigFileFactory.load(codeOwnerConfigKey);
     assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig()).isPresent();
@@ -103,7 +99,7 @@
 
       // Check that the code owner config doesn't exist yet.
       assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig()).isEmpty();
-      assertThat(readCodeOwnerConfig(codeOwnerConfigKey)).isEmpty();
+      assertThat(findOwnersTestUtil.readCodeOwnerConfig(codeOwnerConfigKey)).isEmpty();
 
       // Remember head so that we can check that the branch is changed.
       RevCommit head = getHead(repo, codeOwnerConfigKey.ref());
@@ -125,7 +121,8 @@
           .containsExactly(admin.email());
 
       // Check that the code owner config was created in the repository.
-      Optional<CodeOwnerConfig> codeOwnerConfigInRepo = readCodeOwnerConfig(codeOwnerConfigKey);
+      Optional<CodeOwnerConfig> codeOwnerConfigInRepo =
+          findOwnersTestUtil.readCodeOwnerConfig(codeOwnerConfigKey);
       assertThat(codeOwnerConfigInRepo).isPresent();
       assertThat(codeOwnerConfigInRepo.get())
           .hasCodeOwnersEmailsThat()
@@ -146,7 +143,7 @@
 
       // Check that the code owner config doesn't exist yet.
       assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig()).isEmpty();
-      assertThat(readCodeOwnerConfig(codeOwnerConfigKey)).isEmpty();
+      assertThat(findOwnersTestUtil.readCodeOwnerConfig(codeOwnerConfigKey)).isEmpty();
 
       // Remember head so that we can check that the branch doesn't change.
       RevCommit head = getHead(repo, codeOwnerConfigKey.ref());
@@ -158,7 +155,8 @@
       assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig()).isEmpty();
 
       // Check that no code owner config was created in the repository.
-      Optional<CodeOwnerConfig> codeOwnerConfigInRepo = readCodeOwnerConfig(codeOwnerConfigKey);
+      Optional<CodeOwnerConfig> codeOwnerConfigInRepo =
+          findOwnersTestUtil.readCodeOwnerConfig(codeOwnerConfigKey);
       assertThat(codeOwnerConfigInRepo).isEmpty();
 
       // Check that the branch didn't change.
@@ -176,7 +174,7 @@
 
       // Check that the code owner config doesn't exist yet.
       assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig()).isEmpty();
-      assertThat(readCodeOwnerConfig(codeOwnerConfigKey)).isEmpty();
+      assertThat(findOwnersTestUtil.readCodeOwnerConfig(codeOwnerConfigKey)).isEmpty();
 
       // Remember head so that we can check that the branch doesn't change.
       RevCommit head = getHead(repo, codeOwnerConfigKey.ref());
@@ -189,7 +187,8 @@
       assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig()).isEmpty();
 
       // Check that no code owner config was created in the repository.
-      Optional<CodeOwnerConfig> codeOwnerConfigInRepo = readCodeOwnerConfig(codeOwnerConfigKey);
+      Optional<CodeOwnerConfig> codeOwnerConfigInRepo =
+          findOwnersTestUtil.readCodeOwnerConfig(codeOwnerConfigKey);
       assertThat(codeOwnerConfigInRepo).isEmpty();
 
       // Check that the branch didn't change.
@@ -207,7 +206,7 @@
 
       // Check that the code owner config doesn't exist yet.
       assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig()).isEmpty();
-      assertThat(readCodeOwnerConfig(codeOwnerConfigKey)).isEmpty();
+      assertThat(findOwnersTestUtil.readCodeOwnerConfig(codeOwnerConfigKey)).isEmpty();
 
       // Create the code owner config.
       String email = "admin@example.com";
@@ -228,7 +227,7 @@
       assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig()).isEmpty();
 
       // Check that the code owner config was not created in the repository.
-      assertThat(readCodeOwnerConfig(codeOwnerConfigKey)).isEmpty();
+      assertThat(findOwnersTestUtil.readCodeOwnerConfig(codeOwnerConfigKey)).isEmpty();
 
       // Check that the branch was not created.
       assertThat(repo.exactRef(codeOwnerConfigKey.ref())).isNull();
@@ -240,7 +239,7 @@
     CodeOwnerConfig.Key codeOwnerConfigKey = CodeOwnerConfig.Key.create(project, "master", "/");
     CodeOwnerConfig codeOwnerConfig =
         CodeOwnerConfig.builder(codeOwnerConfigKey).addCodeOwnerEmail(admin.email()).build();
-    writeCodeOwnerConfig(codeOwnerConfig);
+    findOwnersTestUtil.writeCodeOwnerConfig(codeOwnerConfig);
 
     try (Repository repo = repoManager.openRepository(project);
         MetaDataUpdate metaDataUpdate = metaDataUpdateServer.create(project)) {
@@ -248,7 +247,7 @@
 
       // Check that the code owner config exists.
       assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig()).isPresent();
-      assertThat(readCodeOwnerConfig(codeOwnerConfigKey)).isPresent();
+      assertThat(findOwnersTestUtil.readCodeOwnerConfig(codeOwnerConfigKey)).isPresent();
 
       // Remember head so that we can check that the branch is changed.
       RevCommit head = getHead(repo, codeOwnerConfigKey.ref());
@@ -270,7 +269,8 @@
           .containsExactly(admin.email(), user.email());
 
       // Check that the code owner config was updated in the repository.
-      Optional<CodeOwnerConfig> codeOwnerConfigInRepo = readCodeOwnerConfig(codeOwnerConfigKey);
+      Optional<CodeOwnerConfig> codeOwnerConfigInRepo =
+          findOwnersTestUtil.readCodeOwnerConfig(codeOwnerConfigKey);
       assertThat(codeOwnerConfigInRepo).isPresent();
       assertThat(codeOwnerConfigInRepo.get())
           .hasCodeOwnersEmailsThat()
@@ -286,7 +286,7 @@
     CodeOwnerConfig.Key codeOwnerConfigKey = CodeOwnerConfig.Key.create(project, "master", "/");
     CodeOwnerConfig codeOwnerConfig =
         CodeOwnerConfig.builder(codeOwnerConfigKey).addCodeOwnerEmail(admin.email()).build();
-    writeCodeOwnerConfig(codeOwnerConfig);
+    findOwnersTestUtil.writeCodeOwnerConfig(codeOwnerConfig);
 
     try (Repository repo = repoManager.openRepository(project);
         MetaDataUpdate metaDataUpdate = metaDataUpdateServer.create(project)) {
@@ -294,7 +294,7 @@
 
       // Check that the code owner config exists.
       assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig()).isPresent();
-      assertThat(readCodeOwnerConfig(codeOwnerConfigKey)).isPresent();
+      assertThat(findOwnersTestUtil.readCodeOwnerConfig(codeOwnerConfigKey)).isPresent();
 
       // Remember head so that we can check that the branch doesn't change.
       RevCommit head = getHead(repo, codeOwnerConfigKey.ref());
@@ -310,7 +310,8 @@
           .containsExactly(admin.email());
 
       // Check that the code owner config in the repository didn't change.
-      Optional<CodeOwnerConfig> codeOwnerConfigInRepo = readCodeOwnerConfig(codeOwnerConfigKey);
+      Optional<CodeOwnerConfig> codeOwnerConfigInRepo =
+          findOwnersTestUtil.readCodeOwnerConfig(codeOwnerConfigKey);
       assertThat(codeOwnerConfigInRepo).isPresent();
       assertThat(codeOwnerConfigInRepo.get())
           .hasCodeOwnersEmailsThat()
@@ -326,7 +327,7 @@
     CodeOwnerConfig.Key codeOwnerConfigKey = CodeOwnerConfig.Key.create(project, "master", "/");
     CodeOwnerConfig codeOwnerConfig =
         CodeOwnerConfig.builder(codeOwnerConfigKey).addCodeOwnerEmail(admin.email()).build();
-    writeCodeOwnerConfig(codeOwnerConfig);
+    findOwnersTestUtil.writeCodeOwnerConfig(codeOwnerConfig);
 
     try (Repository repo = repoManager.openRepository(project);
         MetaDataUpdate metaDataUpdate = metaDataUpdateServer.create(project)) {
@@ -334,7 +335,7 @@
 
       // Check that the code owner config exists.
       assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig()).isPresent();
-      assertThat(readCodeOwnerConfig(codeOwnerConfigKey)).isPresent();
+      assertThat(findOwnersTestUtil.readCodeOwnerConfig(codeOwnerConfigKey)).isPresent();
 
       // Remember head so that we can check that the branch is changed.
       RevCommit head = getHead(repo, codeOwnerConfigKey.ref());
@@ -350,52 +351,10 @@
       assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig()).isEmpty();
 
       // Check that the code owner config was deleted in the repository.
-      assertThat(readCodeOwnerConfig(codeOwnerConfigKey)).isEmpty();
+      assertThat(findOwnersTestUtil.readCodeOwnerConfig(codeOwnerConfigKey)).isEmpty();
 
       // Check that the branch was changed.
       assertThat(head).isNotEqualTo(getHead(repo, codeOwnerConfigKey.ref()));
     }
   }
-
-  private void writeCodeOwnerConfig(CodeOwnerConfig codeOwnerConfig) throws Exception {
-    String formattedCodeOwnerConfig = codeOwnerConfigParser.formatAsString(codeOwnerConfig);
-    try (TestRepository<Repository> testRepo =
-        new TestRepository<>(repoManager.openRepository(project))) {
-      testRepo.update(
-          codeOwnerConfig.key().ref(),
-          testRepo
-              .commit()
-              .parent(getHead(testRepo.getRepository(), codeOwnerConfig.key().ref()))
-              .message("Add test code owner config")
-              .add(
-                  codeOwnerConfig.key().filePathForJgit(CodeOwnerConfigFile.FILE_NAME),
-                  formattedCodeOwnerConfig));
-    }
-  }
-
-  private Optional<CodeOwnerConfig> readCodeOwnerConfig(CodeOwnerConfig.Key codeOwnerConfigKey)
-      throws Exception {
-    try (TestRepository<Repository> testRepo =
-        new TestRepository<>(repoManager.openRepository(project))) {
-      Ref ref = testRepo.getRepository().exactRef(codeOwnerConfigKey.ref());
-      if (ref == null) {
-        // branch does not exist
-        return Optional.empty();
-      }
-
-      RevCommit commit = testRepo.getRevWalk().parseCommit(ref.getObjectId());
-      String filePath = codeOwnerConfigKey.filePathForJgit(CodeOwnerConfigFile.FILE_NAME);
-      try (TreeWalk tw =
-          TreeWalk.forPath(testRepo.getRevWalk().getObjectReader(), filePath, commit.getTree())) {
-        if (tw == null) {
-          // file does not exist
-          return Optional.empty();
-        }
-      }
-      RevObject blob = testRepo.get(commit.getTree(), filePath);
-      byte[] data = testRepo.getRepository().open(blob).getCachedBytes(Integer.MAX_VALUE);
-      return Optional.of(
-          codeOwnerConfigParser.parse(codeOwnerConfigKey, RawParseUtils.decode(data)));
-    }
-  }
 }
diff --git a/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/FindOwnersBackendTest.java b/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/FindOwnersBackendTest.java
new file mode 100644
index 0000000..df20ddc
--- /dev/null
+++ b/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/FindOwnersBackendTest.java
@@ -0,0 +1,64 @@
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.gerrit.plugins.codeowners.backend.findowners;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth8.assertThat;
+
+import com.google.gerrit.plugins.codeowners.acceptance.AbstractCodeOwnersTest;
+import com.google.gerrit.plugins.codeowners.backend.CodeOwnerConfig;
+import com.google.gerrit.plugins.codeowners.testing.findowners.FindOwnersTestUtil;
+import java.util.Optional;
+import org.junit.Before;
+import org.junit.Test;
+
+/** Tests for {@link FindOwnersBackend}. */
+public class FindOwnersBackendTest extends AbstractCodeOwnersTest {
+  private FindOwnersTestUtil findOwnersTestUtil;
+  private FindOwnersBackend findOwnersBackend;
+
+  @Before
+  public void setUpCodeOwnersPlugin() throws Exception {
+    findOwnersTestUtil = plugin.getSysInjector().getInstance(FindOwnersTestUtil.class);
+    findOwnersBackend = plugin.getSysInjector().getInstance(FindOwnersBackend.class);
+  }
+
+  @Test
+  public void getNonExistingCodeOwnerConfig() throws Exception {
+    CodeOwnerConfig.Key codeOwnerConfigKey =
+        CodeOwnerConfig.Key.create(project, "master", "/non-existing/");
+    assertThat(findOwnersBackend.getCodeOwnerConfig(codeOwnerConfigKey)).isEmpty();
+  }
+
+  @Test
+  public void getCodeOwnerConfigFromNonExistingBranch() throws Exception {
+    CodeOwnerConfig.Key codeOwnerConfigKey =
+        CodeOwnerConfig.Key.create(project, "non-existing", "/");
+    assertThat(findOwnersBackend.getCodeOwnerConfig(codeOwnerConfigKey)).isEmpty();
+  }
+
+  @Test
+  public void getCodeOwnerConfig() throws Exception {
+    CodeOwnerConfig.Key codeOwnerConfigKey = CodeOwnerConfig.Key.create(project, "master", "/");
+    CodeOwnerConfig codeOwnerConfigInRepository =
+        CodeOwnerConfig.builder(codeOwnerConfigKey).addCodeOwnerEmail(admin.email()).build();
+    findOwnersTestUtil.writeCodeOwnerConfig(codeOwnerConfigInRepository);
+
+    Optional<CodeOwnerConfig> codeOwnerConfig =
+        findOwnersBackend.getCodeOwnerConfig(codeOwnerConfigKey);
+    assertThat(codeOwnerConfig).isPresent();
+    assertThat(codeOwnerConfig.get()).isEqualTo(codeOwnerConfigInRepository);
+  }
+}