<commit_before>// 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.acceptance.restapi;

import static com.google.common.truth.Truth.assertThat;
import static com.google.gerrit.plugins.codeowners.testing.CodeOwnerInfoIterableSubject.assertThat;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.gerrit.acceptance.RestResponse;
import com.google.gerrit.extensions.client.ListAccountsOption;
import com.google.gerrit.extensions.restapi.IdString;
import com.google.gerrit.plugins.codeowners.acceptance.AbstractCodeOwnersIT;
import com.google.gerrit.plugins.codeowners.api.CodeOwnerInfo;
import com.google.gerrit.server.ServerInitiated;
import com.google.gerrit.server.account.AccountsUpdate;
import com.google.gerrit.server.account.externalids.ExternalId;
import com.google.gson.reflect.TypeToken;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.util.List;
import org.junit.Test;

/**
 * Acceptance test for the {@link
 * com.google.gerrit.plugins.codeowners.restapi.GetCodeOwnersForPathInBranch} REST endpoint. that
 * require using via REST.
 *
 * <p>Acceptance test for the {@link
 * com.google.gerrit.plugins.codeowners.restapi.GetCodeOwnersForPathInBranch} REST endpoint that can
 * use the Java API are implemented in {@link
 * com.google.gerrit.plugins.codeowners.acceptance.api.GetCodeOwnersForPathInBranchIT}.
 */
public class GetCodeOwnersForPathInBranchRestIT extends AbstractCodeOwnersIT {
  @Inject @ServerInitiated private Provider<AccountsUpdate> accountsUpdate;

  @Test
  public void getCodeOwnerConfigForInvalidPath() throws Exception {
    RestResponse r =
        adminRestSession.get(
            String.format(
                "/projects/%s/branches/%s/code_owners/%s",
                IdString.fromDecoded(project.get()),
                IdString.fromDecoded("master"),
                IdString.fromDecoded("\0")));
    r.assertBadRequest();
    assertThat(r.getEntityContent()).contains("Nul character not allowed");
  }

  @Test
  public void getCodeOwnersWithAccountOptions() throws Exception {
    codeOwnerConfigOperations
        .newCodeOwnerConfig()
        .project(project)
        .branch("master")
        .folderPath("/foo/bar/")
        .addCodeOwnerEmail(admin.email())
        .create();

    // add secondary email to admin account
    String secondaryEmail = "<EMAIL>";
    accountsUpdate
        .get()
        .update(
            "Add secondary email to admin test account",
            admin.id(),
            (a, u) -> u.addExternalId(ExternalId.createEmail(admin.id(), secondaryEmail)));

    // Make the request with the admin user that has the 'Modify Account' global capability.
    RestResponse r =
        adminRestSession.get(
            String.format(
                "/projects/%s/branches/%s/code_owners/%s?o=%s&o=%s",
                IdString.fromDecoded(project.get()),
                IdString.fromDecoded("master"),
                IdString.fromDecoded("/foo/bar/baz.md"),
                ListAccountsOption.DETAILS.name(),
                ListAccountsOption.ALL_EMAILS.name()));
    r.assertOK();
    List<CodeOwnerInfo> codeOwnerInfos =
        newGson().fromJson(r.getReader(), new TypeToken<List<CodeOwnerInfo>>() {}.getType());
    assertThat(codeOwnerInfos).hasAccountIdsThat().containsExactly(admin.id());
    assertThat(codeOwnerInfos).hasAccountNamesThat().containsExactly(admin.fullName());
    assertThat(Iterables.getOnlyElement(codeOwnerInfos).account.secondaryEmails)
        .containsExactly(secondaryEmail);
  }

  @Test
  public void getCodeOwnersWithHexAccountOptions() throws Exception {
    codeOwnerConfigOperations
        .newCodeOwnerConfig()
        .project(project)
        .branch("master")
        .folderPath("/foo/bar/")
        .addCodeOwnerEmail(admin.email())
        .create();

    // add secondary email to admin account
    String secondaryEmail = "<EMAIL>";
    accountsUpdate
        .get()
        .update(
            "Add secondary email to admin test account",
            admin.id(),
            (a, u) -> u.addExternalId(ExternalId.createEmail(admin.id(), secondaryEmail)));

    // Make the request with the admin user that has the 'Modify Account' global capability.
    RestResponse r =
        adminRestSession.get(
            String.format(
                "/projects/%s/branches/%s/code_owners/%s?O=%s",
                IdString.fromDecoded(project.get()),
                IdString.fromDecoded("master"),
                IdString.fromDecoded("/foo/bar/baz.md"),
                toHex(ImmutableSet.of(ListAccountsOption.DETAILS, ListAccountsOption.ALL_EMAILS))));
    r.assertOK();
    List<CodeOwnerInfo> codeOwnerInfos =
        newGson().fromJson(r.getReader(), new TypeToken<List<CodeOwnerInfo>>() {}.getType());
    assertThat(codeOwnerInfos).hasAccountIdsThat().containsExactly(admin.id());
    assertThat(codeOwnerInfos).hasAccountNamesThat().containsExactly(admin.fullName());
    assertThat(Iterables.getOnlyElement(codeOwnerInfos).account.secondaryEmails)
        .containsExactly(secondaryEmail);
  }

  @Test
  public void cannotGetCodeOwnersWithUnknownAccountOption() throws Exception {
    RestResponse r =
        adminRestSession.get(
            String.format(
                "/projects/%s/branches/%s/code_owners/%s?o=%s",
                IdString.fromDecoded(project.get()),
                IdString.fromDecoded("master"),
                IdString.fromDecoded("/foo/bar/baz.md"),
                "unknown-option"));
    r.assertBadRequest();
    assertThat(r.getEntityContent())
        .isEqualTo("\"unknown_option\" is not a valid value for \"-o\"");
  }

  @Test
  public void cannotGetCodeOwnersWithUnknownHexAccountOption() throws Exception {
    String unknownHexOption = Integer.toHexString(100);
    RestResponse r =
        adminRestSession.get(
            String.format(
                "/projects/%s/branches/%s/code_owners/%s?O=%s",
                IdString.fromDecoded(project.get()),
                IdString.fromDecoded("master"),
                IdString.fromDecoded("/foo/bar/baz.md"),
                unknownHexOption));
    r.assertBadRequest();
    assertThat(r.getEntityContent())
        .isEqualTo(String.format("\"%s\" is not a valid value for \"-O\"", unknownHexOption));
  }

  // TODO (ekempin): Generalize the
  // com.google.gerrit.extensions.client.ListOption#toHex(Set<ListChangesOption>) in Gerrit core
  // to be able to work with all kind of options. Once this is done, use the toHex method from
  // Gerrit core and remove this method.
  private static String toHex(ImmutableSet<ListAccountsOption> options) {
    int v = 0;
    for (ListAccountsOption option : options) {
      v |= 1 << option.getValue();
    }

    return Integer.toHexString(v);
  }
}<commit_msg>GetCodeOwnersForPathInBranchRestIT: Use toHex method from Gerrit core<commit_after>// 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.acceptance.restapi;

import static com.google.common.truth.Truth.assertThat;
import static com.google.gerrit.plugins.codeowners.testing.CodeOwnerInfoIterableSubject.assertThat;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.gerrit.acceptance.RestResponse;
import com.google.gerrit.extensions.client.ListAccountsOption;
import com.google.gerrit.extensions.client.ListOption;
import com.google.gerrit.extensions.restapi.IdString;
import com.google.gerrit.plugins.codeowners.acceptance.AbstractCodeOwnersIT;
import com.google.gerrit.plugins.codeowners.api.CodeOwnerInfo;
import com.google.gerrit.server.ServerInitiated;
import com.google.gerrit.server.account.AccountsUpdate;
import com.google.gerrit.server.account.externalids.ExternalId;
import com.google.gson.reflect.TypeToken;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.util.List;
import org.junit.Test;

/**
 * Acceptance test for the {@link
 * com.google.gerrit.plugins.codeowners.restapi.GetCodeOwnersForPathInBranch} REST endpoint. that
 * require using via REST.
 *
 * <p>Acceptance test for the {@link
 * com.google.gerrit.plugins.codeowners.restapi.GetCodeOwnersForPathInBranch} REST endpoint that can
 * use the Java API are implemented in {@link
 * com.google.gerrit.plugins.codeowners.acceptance.api.GetCodeOwnersForPathInBranchIT}.
 */
public class GetCodeOwnersForPathInBranchRestIT extends AbstractCodeOwnersIT {
  @Inject @ServerInitiated private Provider<AccountsUpdate> accountsUpdate;

  @Test
  public void getCodeOwnerConfigForInvalidPath() throws Exception {
    RestResponse r =
        adminRestSession.get(
            String.format(
                "/projects/%s/branches/%s/code_owners/%s",
                IdString.fromDecoded(project.get()),
                IdString.fromDecoded("master"),
                IdString.fromDecoded("\0")));
    r.assertBadRequest();
    assertThat(r.getEntityContent()).contains("Nul character not allowed");
  }

  @Test
  public void getCodeOwnersWithAccountOptions() throws Exception {
    codeOwnerConfigOperations
        .newCodeOwnerConfig()
        .project(project)
        .branch("master")
        .folderPath("/foo/bar/")
        .addCodeOwnerEmail(admin.email())
        .create();

    // add secondary email to admin account
    String secondaryEmail = "<EMAIL>";
    accountsUpdate
        .get()
        .update(
            "Add secondary email to admin test account",
            admin.id(),
            (a, u) -> u.addExternalId(ExternalId.createEmail(admin.id(), secondaryEmail)));

    // Make the request with the admin user that has the 'Modify Account' global capability.
    RestResponse r =
        adminRestSession.get(
            String.format(
                "/projects/%s/branches/%s/code_owners/%s?o=%s&o=%s",
                IdString.fromDecoded(project.get()),
                IdString.fromDecoded("master"),
                IdString.fromDecoded("/foo/bar/baz.md"),
                ListAccountsOption.DETAILS.name(),
                ListAccountsOption.ALL_EMAILS.name()));
    r.assertOK();
    List<CodeOwnerInfo> codeOwnerInfos =
        newGson().fromJson(r.getReader(), new TypeToken<List<CodeOwnerInfo>>() {}.getType());
    assertThat(codeOwnerInfos).hasAccountIdsThat().containsExactly(admin.id());
    assertThat(codeOwnerInfos).hasAccountNamesThat().containsExactly(admin.fullName());
    assertThat(Iterables.getOnlyElement(codeOwnerInfos).account.secondaryEmails)
        .containsExactly(secondaryEmail);
  }

  @Test
  public void getCodeOwnersWithHexAccountOptions() throws Exception {
    codeOwnerConfigOperations
        .newCodeOwnerConfig()
        .project(project)
        .branch("master")
        .folderPath("/foo/bar/")
        .addCodeOwnerEmail(admin.email())
        .create();

    // add secondary email to admin account
    String secondaryEmail = "<EMAIL>";
    accountsUpdate
        .get()
        .update(
            "Add secondary email to admin test account",
            admin.id(),
            (a, u) -> u.addExternalId(ExternalId.createEmail(admin.id(), secondaryEmail)));

    // Make the request with the admin user that has the 'Modify Account' global capability.
    RestResponse r =
        adminRestSession.get(
            String.format(
                "/projects/%s/branches/%s/code_owners/%s?O=%s",
                IdString.fromDecoded(project.get()),
                IdString.fromDecoded("master"),
                IdString.fromDecoded("/foo/bar/baz.md"),
                ListOption.toHex(
                    ImmutableSet.of(ListAccountsOption.DETAILS, ListAccountsOption.ALL_EMAILS))));
    r.assertOK();
    List<CodeOwnerInfo> codeOwnerInfos =
        newGson().fromJson(r.getReader(), new TypeToken<List<CodeOwnerInfo>>() {}.getType());
    assertThat(codeOwnerInfos).hasAccountIdsThat().containsExactly(admin.id());
    assertThat(codeOwnerInfos).hasAccountNamesThat().containsExactly(admin.fullName());
    assertThat(Iterables.getOnlyElement(codeOwnerInfos).account.secondaryEmails)
        .containsExactly(secondaryEmail);
  }

  @Test
  public void cannotGetCodeOwnersWithUnknownAccountOption() throws Exception {
    RestResponse r =
        adminRestSession.get(
            String.format(
                "/projects/%s/branches/%s/code_owners/%s?o=%s",
                IdString.fromDecoded(project.get()),
                IdString.fromDecoded("master"),
                IdString.fromDecoded("/foo/bar/baz.md"),
                "unknown-option"));
    r.assertBadRequest();
    assertThat(r.getEntityContent())
        .isEqualTo("\"unknown_option\" is not a valid value for \"-o\"");
  }

  @Test
  public void cannotGetCodeOwnersWithUnknownHexAccountOption() throws Exception {
    String unknownHexOption = Integer.toHexString(100);
    RestResponse r =
        adminRestSession.get(
            String.format(
                "/projects/%s/branches/%s/code_owners/%s?O=%s",
                IdString.fromDecoded(project.get()),
                IdString.fromDecoded("master"),
                IdString.fromDecoded("/foo/bar/baz.md"),
                unknownHexOption));
    r.assertBadRequest();
    assertThat(r.getEntityContent())
        .isEqualTo(String.format("\"%s\" is not a valid value for \"-O\"", unknownHexOption));
  }
}
{'fraction_non_alphanumeric': 0.11684014613634797, 'fraction_numerical': 0.0017922382298200868, 'mean_word_length': 3.122762148337596, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2149923', 'n_tokens_mistral': 4121, 'n_tokens_neox': 4016, 'n_words': 827}