diff --git a/.github/workflows/cron-licenses.yml b/.github/workflows/cron-licenses.yml index 6ef5813a64fc..cd8386ecc521 100644 --- a/.github/workflows/cron-licenses.yml +++ b/.github/workflows/cron-licenses.yml @@ -11,7 +11,7 @@ jobs: if: github.repository == 'go-gitea/gitea' steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true diff --git a/.github/workflows/cron-lock.yml b/.github/workflows/cron-lock.yml index 935f926cce9c..746ec49bc63e 100644 --- a/.github/workflows/cron-lock.yml +++ b/.github/workflows/cron-lock.yml @@ -17,6 +17,6 @@ jobs: runs-on: ubuntu-latest if: github.repository == 'go-gitea/gitea' steps: - - uses: dessant/lock-threads@v4 + - uses: dessant/lock-threads@v5 with: issue-inactive-days: 45 diff --git a/.github/workflows/pull-compliance.yml b/.github/workflows/pull-compliance.yml index 6977dc32b291..0472d9a9f07e 100644 --- a/.github/workflows/pull-compliance.yml +++ b/.github/workflows/pull-compliance.yml @@ -17,7 +17,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -70,7 +70,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -87,7 +87,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -102,7 +102,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -130,7 +130,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -175,7 +175,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true diff --git a/.github/workflows/pull-db-tests.yml b/.github/workflows/pull-db-tests.yml index 97446e6cd3b2..a3886bf61807 100644 --- a/.github/workflows/pull-db-tests.yml +++ b/.github/workflows/pull-db-tests.yml @@ -39,7 +39,7 @@ jobs: - "9000:9000" steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -64,7 +64,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -115,7 +115,7 @@ jobs: - "9000:9000" steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -165,7 +165,7 @@ jobs: - "993:993" steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -198,7 +198,7 @@ jobs: - "1433:1433" steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true diff --git a/.github/workflows/pull-e2e-tests.yml b/.github/workflows/pull-e2e-tests.yml index 540263788d46..5a249db9f8dd 100644 --- a/.github/workflows/pull-e2e-tests.yml +++ b/.github/workflows/pull-e2e-tests.yml @@ -17,7 +17,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true diff --git a/.github/workflows/release-nightly.yml b/.github/workflows/release-nightly.yml index ef1e63df2ffc..80e6683919fc 100644 --- a/.github/workflows/release-nightly.yml +++ b/.github/workflows/release-nightly.yml @@ -18,7 +18,7 @@ jobs: # fetch all commits instead of only the last as some branches are long lived and could have many between versions # fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567 - run: git fetch --unshallow --quiet --tags --force - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -64,7 +64,7 @@ jobs: # fetch all commits instead of only the last as some branches are long lived and could have many between versions # fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567 - run: git fetch --unshallow --quiet --tags --force - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -101,7 +101,7 @@ jobs: # fetch all commits instead of only the last as some branches are long lived and could have many between versions # fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567 - run: git fetch --unshallow --quiet --tags --force - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true diff --git a/.github/workflows/release-tag-rc.yml b/.github/workflows/release-tag-rc.yml index d73d67aede76..12d1e1e4bebe 100644 --- a/.github/workflows/release-tag-rc.yml +++ b/.github/workflows/release-tag-rc.yml @@ -17,7 +17,7 @@ jobs: # fetch all commits instead of only the last as some branches are long lived and could have many between versions # fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567 - run: git fetch --unshallow --quiet --tags --force - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true diff --git a/.github/workflows/release-tag-version.yml b/.github/workflows/release-tag-version.yml index 0379350900a9..e0e93633e8ab 100644 --- a/.github/workflows/release-tag-version.yml +++ b/.github/workflows/release-tag-version.yml @@ -19,7 +19,7 @@ jobs: # fetch all commits instead of only the last as some branches are long lived and could have many between versions # fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567 - run: git fetch --unshallow --quiet --tags --force - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true diff --git a/README.md b/README.md index dc396465a7e3..5ab5ab858643 100644 --- a/README.md +++ b/README.md @@ -62,11 +62,16 @@ painless way of setting up a self-hosted Git service. As Gitea is written in Go, it works across **all** the platforms and architectures that are supported by Go, including Linux, macOS, and Windows on x86, amd64, ARM and PowerPC architectures. -You can try it out using [the online demo](https://try.gitea.io/). This project has been [forked](https://blog.gitea.com/welcome-to-gitea/) from [Gogs](https://gogs.io) since November of 2016, but a lot has changed. +For online demonstrations, you can visit [try.gitea.io](https://try.gitea.io). + +For accessing free Gitea service (with a limited number of repositories), you can visit [gitea.com](https://gitea.com/user/login). + +To quickly deploy your own dedicated Gitea instance on Gitea Cloud, you can start a free trial at [cloud.gitea.com](https://cloud.gitea.com). + ## Building From the root of the source tree, run: diff --git a/README_ZH.md b/README_ZH.md index dd77c05de8f0..b9384a9825b8 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -58,7 +58,11 @@ Gitea 的首要目标是创建一个极易安装,运行非常快速,安装和使用体验良好的自建 Git 服务。我们采用 Go 作为后端语言,这使我们只要生成一个可执行程序即可。并且他还支持跨平台,支持 Linux, macOS 和 Windows 以及各种架构,除了 x86,amd64,还包括 ARM 和 PowerPC。 -如果您想试用一下,请访问 [在线Demo](https://try.gitea.io/)! +如果你想试用在线演示,请访问 [try.gitea.io](https://try.gitea.io/)。 + +如果你想使用免费的 Gitea 服务(有仓库数量限制),请访问 [gitea.com](https://gitea.com/user/login)。 + +如果你想在 Gitea Cloud 上快速部署你自己独享的 Gitea 实例,请访问 [cloud.gitea.com](https://cloud.gitea.com) 开始免费试用。 ## 提示 diff --git a/cmd/hook.go b/cmd/hook.go index 6f31c326fd06..6a3358853ddc 100644 --- a/cmd/hook.go +++ b/cmd/hook.go @@ -377,7 +377,7 @@ Gitea or set your environment appropriately.`, "") newCommitIDs[count] = string(fields[1]) refFullNames[count] = git.RefName(fields[2]) - commitID, _ := git.IDFromString(newCommitIDs[count]) + commitID, _ := git.NewIDFromString(newCommitIDs[count]) if refFullNames[count] == git.BranchPrefix+"master" && !commitID.IsZero() && count == total { masterPushed = true } @@ -671,7 +671,7 @@ Gitea or set your environment appropriately.`, "") if err != nil { return err } - commitID, _ := git.IDFromString(rs.OldOID) + commitID, _ := git.NewIDFromString(rs.OldOID) if !commitID.IsZero() { err = writeDataPktLine(ctx, os.Stdout, []byte("option old-oid "+rs.OldOID)) if err != nil { diff --git a/custom/conf/app.example.ini b/custom/conf/app.example.ini index 9a5d19074595..f9111d541c73 100644 --- a/custom/conf/app.example.ini +++ b/custom/conf/app.example.ini @@ -234,7 +234,7 @@ RUN_USER = ; git ;MINIMUM_KEY_SIZE_CHECK = false ;; ;; Disable CDN even in "prod" mode -;OFFLINE_MODE = false +;OFFLINE_MODE = true ;; ;; TLS Settings: Either ACME or manual ;; (Other common TLS configuration are found before) @@ -1705,9 +1705,6 @@ LEVEL = Info ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; -;; if the cache enabled -;ENABLED = true -;; ;; Either "memory", "redis", "memcache", or "twoqueue". default is "memory" ;ADAPTER = memory ;; @@ -1732,8 +1729,6 @@ LEVEL = Info ;[cache.last_commit] ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; if the cache enabled -;ENABLED = true ;; ;; Time to keep items in cache if not used, default is 8760 hours. ;; Setting it to -1 disables caching diff --git a/docs/content/administration/config-cheat-sheet.en-us.md b/docs/content/administration/config-cheat-sheet.en-us.md index 9810dab49bc1..1ba5dd04cc40 100644 --- a/docs/content/administration/config-cheat-sheet.en-us.md +++ b/docs/content/administration/config-cheat-sheet.en-us.md @@ -357,7 +357,7 @@ The following configuration set `Content-Type: application/vnd.android.package-a - `SSH_PER_WRITE_PER_KB_TIMEOUT`: **10s**: Timeout per Kb written to SSH connections. - `MINIMUM_KEY_SIZE_CHECK`: **true**: Indicate whether to check minimum key size with corresponding type. -- `OFFLINE_MODE`: **false**: Disables use of CDN for static files and Gravatar for profile pictures. +- `OFFLINE_MODE`: **true**: Disables use of CDN for static files and Gravatar for profile pictures. - `CERT_FILE`: **https/cert.pem**: Cert file path used for HTTPS. When chaining, the server certificate must come first, then intermediate CA certificates (if any). This is ignored if `ENABLE_ACME=true`. Paths are relative to `CUSTOM_PATH`. - `KEY_FILE`: **https/key.pem**: Key file path used for HTTPS. This is ignored if `ENABLE_ACME=true`. Paths are relative to `CUSTOM_PATH`. - `STATIC_ROOT_PATH`: **_`StaticRootPath`_**: Upper level of template and static files path. @@ -763,7 +763,6 @@ and ## Cache (`cache`) -- `ENABLED`: **true**: Enable the cache. - `ADAPTER`: **memory**: Cache engine adapter, either `memory`, `redis`, `redis-cluster`, `twoqueue` or `memcache`. (`twoqueue` represents a size limited LRU cache.) - `INTERVAL`: **60**: Garbage Collection interval (sec), for memory and twoqueue cache only. - `HOST`: **_empty_**: Connection string for `redis`, `redis-cluster` and `memcache`. For `twoqueue` sets configuration for the queue. @@ -775,7 +774,6 @@ and ## Cache - LastCommitCache settings (`cache.last_commit`) -- `ENABLED`: **true**: Enable the cache. - `ITEM_TTL`: **8760h**: Time to keep items in cache if not used, Setting it to -1 disables caching. - `COMMITS_COUNT`: **1000**: Only enable the cache when repository's commits count great than. @@ -1401,8 +1399,8 @@ PROXY_HOSTS = *.github.com - `SKIP_WORKFLOW_STRINGS`: **[skip ci],[ci skip],[no ci],[skip actions],[actions skip]**: Strings committers can place inside a commit message to skip executing the corresponding actions workflow `DEFAULT_ACTIONS_URL` indicates where the Gitea Actions runners should find the actions with relative path. -For example, `uses: actions/checkout@v3` means `https://github.com/actions/checkout@v3` since the value of `DEFAULT_ACTIONS_URL` is `github`. -And it can be changed to `self` to make it `root_url_of_your_gitea/actions/checkout@v3`. +For example, `uses: actions/checkout@v4` means `https://github.com/actions/checkout@v4` since the value of `DEFAULT_ACTIONS_URL` is `github`. +And it can be changed to `self` to make it `root_url_of_your_gitea/actions/checkout@v4`. Please note that using `self` is not recommended for most cases, as it could make names globally ambiguous. Additionally, it requires you to mirror all the actions you need to your Gitea instance, which may not be worth it. @@ -1411,7 +1409,7 @@ Therefore, please use `self` only if you understand what you are doing. In earlier versions (`<= 1.19`), `DEFAULT_ACTIONS_URL` could be set to any custom URLs like `https://gitea.com` or `http://your-git-server,https://gitea.com`, and the default value was `https://gitea.com`. However, later updates removed those options, and now the only options are `github` and `self`, with the default value being `github`. However, if you want to use actions from other git server, you can use a complete URL in `uses` field, it's supported by Gitea (but not GitHub). -Like `uses: https://gitea.com/actions/checkout@v3` or `uses: http://your-git-server/actions/checkout@v3`. +Like `uses: https://gitea.com/actions/checkout@v4` or `uses: http://your-git-server/actions/checkout@v4`. ## Other (`other`) diff --git a/docs/content/administration/config-cheat-sheet.zh-cn.md b/docs/content/administration/config-cheat-sheet.zh-cn.md index eed752c1cbd7..434d69815b19 100644 --- a/docs/content/administration/config-cheat-sheet.zh-cn.md +++ b/docs/content/administration/config-cheat-sheet.zh-cn.md @@ -346,7 +346,7 @@ menu: - `SSH_PER_WRITE_TIMEOUT`: **30s**:对 SSH 连接的任何写入设置超时。(将其设置为 -1 可以禁用所有超时。) - `SSH_PER_WRITE_PER_KB_TIMEOUT`: **10s**:对写入 SSH 连接的每 KB 设置超时。 - `MINIMUM_KEY_SIZE_CHECK`: **true**:指示是否检查最小密钥大小与相应类型。 -- `OFFLINE_MODE`: **false**:禁用 CDN 用于静态文件和 Gravatar 用于个人资料图片。 +- `OFFLINE_MODE`: **true**:禁用 CDN 用于静态文件和 Gravatar 用于个人资料图片。 - `CERT_FILE`: **https/cert.pem**:用于 HTTPS 的证书文件路径。在链接时,服务器证书必须首先出现,然后是中间 CA 证书(如果有)。如果 `ENABLE_ACME=true`,则此设置会被忽略。路径相对于 `CUSTOM_PATH`。 - `KEY_FILE`: **https/key.pem**:用于 HTTPS 的密钥文件路径。如果 `ENABLE_ACME=true`,则此设置会被忽略。路径相对于 `CUSTOM_PATH`。 - `STATIC_ROOT_PATH`: **_`StaticRootPath`_**:模板和静态文件路径的上一级。 @@ -721,7 +721,6 @@ Gitea 创建以下非唯一队列: ## 缓存 (`cache`) -- `ENABLED`: **true**: 是否启用缓存。 - `ADAPTER`: **memory**: 缓存引擎,可以为 `memory`, `redis`, `redis-cluster`, `twoqueue` 和 `memcache`. (`twoqueue` 代表缓冲区固定的LRU缓存) - `INTERVAL`: **60**: 垃圾回收间隔(秒),只对`memory`和`towqueue`有效。 - `HOST`: **_empty_**: 缓存配置。`redis`, `redis-cluster`,`memcache`配置连接字符串;`twoqueue` 设置队列参数 @@ -733,7 +732,6 @@ Gitea 创建以下非唯一队列: ### 缓存 - 最后提交缓存设置 (`cache.last_commit`) -- `ENABLED`: **true**:是否启用缓存。 - `ITEM_TTL`: **8760h**:如果未使用,保持缓存中的项目的时间,将其设置为 -1 会禁用缓存。 - `COMMITS_COUNT`: **1000**:仅在存储库的提交计数大于时启用缓存。 @@ -1337,8 +1335,8 @@ PROXY_HOSTS = *.github.com - `MINIO_BASE_PATH`: **actions_log/**:Minio存储桶上的基本路径,仅在`STORAGE_TYPE`为`minio`时可用。 `DEFAULT_ACTIONS_URL` 指示 Gitea 操作运行程序应该在哪里找到带有相对路径的操作。 -例如,`uses: actions/checkout@v3` 表示 `https://github.com/actions/checkout@v3`,因为 `DEFAULT_ACTIONS_URL` 的值为 `github`。 -它可以更改为 `self`,以使其成为 `root_url_of_your_gitea/actions/checkout@v3`。 +例如,`uses: actions/checkout@v4` 表示 `https://github.com/actions/checkout@v4`,因为 `DEFAULT_ACTIONS_URL` 的值为 `github`。 +它可以更改为 `self`,以使其成为 `root_url_of_your_gitea/actions/checkout@v4`。 请注意,对于大多数情况,不建议使用 `self`,因为它可能使名称在全局范围内产生歧义。 此外,它要求您将所有所需的操作镜像到您的 Gitea 实例,这可能不值得。 @@ -1347,7 +1345,7 @@ PROXY_HOSTS = *.github.com 在早期版本(`<= 1.19`)中,`DEFAULT_ACTIONS_URL` 可以设置为任何自定义 URL,例如 `https://gitea.com` 或 `http://your-git-server,https://gitea.com`,默认值为 `https://gitea.com`。 然而,后来的更新删除了这些选项,现在唯一的选项是 `github` 和 `self`,默认值为 `github`。 但是,如果您想要使用其他 Git 服务器中的操作,您可以在 `uses` 字段中使用完整的 URL,Gitea 支持此功能(GitHub 不支持)。 -例如 `uses: https://gitea.com/actions/checkout@v3` 或 `uses: http://your-git-server/actions/checkout@v3`。 +例如 `uses: https://gitea.com/actions/checkout@v4` 或 `uses: http://your-git-server/actions/checkout@v4`。 ## 其他 (`other`) diff --git a/docs/content/usage/actions/comparison.en-us.md b/docs/content/usage/actions/comparison.en-us.md index be40657bed70..1ea3afac5bf4 100644 --- a/docs/content/usage/actions/comparison.en-us.md +++ b/docs/content/usage/actions/comparison.en-us.md @@ -22,13 +22,17 @@ Even though Gitea Actions is designed to be compatible with GitHub Actions, ther ### Absolute action URLs Gitea Actions supports defining actions via absolute URL, which means that you can use actions from any git repository. -Like `uses: https://github.com/actions/checkout@v3` or `uses: http://your_gitea.com/owner/repo@branch`. +Like `uses: https://github.com/actions/checkout@v4` or `uses: http://your_gitea.com/owner/repo@branch`. ### Actions written in Go Gitea Actions supports writing actions in Go. See [Creating Go Actions](https://blog.gitea.com/creating-go-actions/). +### Support the non-standard syntax @yearly, @monthly, @weekly, @daily, @hourly on schedule + +Github Actions doesn't support that. https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#schedule + ## Unsupported workflows syntax ### `concurrency` @@ -110,6 +114,10 @@ It's ignored by Gitea Actions now. Pre and Post steps don't have their own section in the job log user interface. +### Services steps + +Services steps don't have their own section in the job log user interface. + ## Different behavior ### Downloading actions @@ -117,9 +125,9 @@ Pre and Post steps don't have their own section in the job log user interface. Previously (Pre 1.21.0), `[actions].DEFAULT_ACTIONS_URL` defaulted to `https://gitea.com`. We have since restricted this option to only allow two values (`github` and `self`). When set to `github`, the new default, Gitea will download non-fully-qualified actions from `https://github.com`. -For example, if you use `uses: actions/checkout@v3`, it will download the checkout repository from `https://github.com/actions/checkout.git`. +For example, if you use `uses: actions/checkout@v4`, it will download the checkout repository from `https://github.com/actions/checkout.git`. -If you want to download an action from another git hoster, you can use an absolute URL, e.g. `uses: https://gitea.com/actions/checkout@v3`. +If you want to download an action from another git hoster, you can use an absolute URL, e.g. `uses: https://gitea.com/actions/checkout@v4`. If your Gitea instance is in an intranet or a restricted area, you can set the URL to `self` to only download actions from your own instance by default. Of course, you can still use absolute URLs in workflows. diff --git a/docs/content/usage/actions/comparison.zh-cn.md b/docs/content/usage/actions/comparison.zh-cn.md index 1ef7d3ca9892..006fc8de3f53 100644 --- a/docs/content/usage/actions/comparison.zh-cn.md +++ b/docs/content/usage/actions/comparison.zh-cn.md @@ -22,13 +22,17 @@ menu: ### Action URL绝对路径 Gitea Actions支持通过URL绝对路径定义actions,这意味着您可以使用来自任何Git存储库的Actions。 -例如,`uses: https://github.com/actions/checkout@v3`或`uses: http://your_gitea.com/owner/repo@branch`。 +例如,`uses: https://github.com/actions/checkout@v4`或`uses: http://your_gitea.com/owner/repo@branch`。 ### 使用Go编写Actions Gitea Actions支持使用Go编写Actions。 请参阅[创建Go Actions](https://blog.gitea.com/creating-go-actions/)。 +### 支持非标准的调度语法 @yearly, @monthly, @weekly, @daily, @hourly + +Github Actions 不支持这些语法,详见: https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#schedule + ## 不支持的工作流语法 ### `concurrency` @@ -116,15 +120,19 @@ Gitea Actions目前不支持此功能。 预处理和后处理步骤在Job日志用户界面中没有自己的用户界面。 +### 服务步骤 + +服务步骤在Job日志用户界面中没有自己的用户界面。 + ## 不一样的行为 ### 下载Actions 当 `[actions].DEFAULT_ACTIONS_URL` 保持默认值为 `github` 时,Gitea将会从 https://github.com 下载相对路径的actions。比如: -如果你使用 `uses: actions/checkout@v3`,Gitea将会从 https://github.com/actions/checkout.git 下载这个 actions 项目。 -如果你想要从另外一个 Git服务下载actions,你只需要使用绝对URL `uses: https://gitea.com/actions/checkout@v3` 来下载。 +如果你使用 `uses: actions/checkout@v4`,Gitea将会从 https://github.com/actions/checkout.git 下载这个 actions 项目。 +如果你想要从另外一个 Git服务下载actions,你只需要使用绝对URL `uses: https://gitea.com/actions/checkout@v4` 来下载。 -如果你的 Gitea 实例是部署在一个互联网限制的网络中,有可以使用绝对地址来下载 actions。你也可以讲配置项修改为 `[actions].DEFAULT_ACTIONS_URL = self`。这样所有的相对路径的actions引用,将不再会从 github.com 去下载,而会从这个 Gitea 实例自己的仓库中去下载。例如: `uses: actions/checkout@v3` 将会从 `[server].ROOT_URL`/actions/checkout.git 这个地址去下载 actions。 +如果你的 Gitea 实例是部署在一个互联网限制的网络中,有可以使用绝对地址来下载 actions。你也可以讲配置项修改为 `[actions].DEFAULT_ACTIONS_URL = self`。这样所有的相对路径的actions引用,将不再会从 github.com 去下载,而会从这个 Gitea 实例自己的仓库中去下载。例如: `uses: actions/checkout@v4` 将会从 `[server].ROOT_URL`/actions/checkout.git 这个地址去下载 actions。 设置`[actions].DEFAULT_ACTIONS_URL`进行配置。请参阅[配置备忘单](administration/config-cheat-sheet.md#actions-actions)。 diff --git a/docs/content/usage/actions/design.en-us.md b/docs/content/usage/actions/design.en-us.md index 8394e822dc60..29fa433e59b5 100644 --- a/docs/content/usage/actions/design.en-us.md +++ b/docs/content/usage/actions/design.en-us.md @@ -95,7 +95,7 @@ The act runner must be able to connect to Gitea to receive tasks and send back t ### Connection 2, job containers to Gitea instance The job containers have different network namespaces than the runner, even if they are on the same machine. -They need to connect to Gitea to fetch codes if there is `actions/checkout@v3` in the workflow, for example. +They need to connect to Gitea to fetch codes if there is `actions/checkout@v4` in the workflow, for example. Fetching code is not always necessary to run some jobs, but it is required in most cases. If you use a loopback address to register a runner, the runner can connect to Gitea when it is on the same machine. @@ -103,7 +103,7 @@ However, if a job container tries to fetch code from localhost, it will fail bec ### Connection 3, act runner to internet -When you use some actions like `actions/checkout@v3`, the act runner downloads the scripts, not the job containers. +When you use some actions like `actions/checkout@v4`, the act runner downloads the scripts, not the job containers. By default, it downloads from [gitea.com](http://gitea.com/), so it requires access to the internet. It also downloads some docker images from Docker Hub by default, which also requires internet access. @@ -116,7 +116,7 @@ And [Gitea Container Registry](usage/packages/container.md) can be used as a Doc ### Connection 4, job containers to internet -When using actions such as `actions/setup-go@v4`, it may be necessary to download resources from the internet to set up the Go language environment in job containers. +When using actions such as `actions/setup-go@v5`, it may be necessary to download resources from the internet to set up the Go language environment in job containers. Therefore, access to the internet is required for the successful completion of these actions. However, it is optional as well. diff --git a/docs/content/usage/actions/design.zh-cn.md b/docs/content/usage/actions/design.zh-cn.md index 06f600f39152..8add1cf7c54a 100644 --- a/docs/content/usage/actions/design.zh-cn.md +++ b/docs/content/usage/actions/design.zh-cn.md @@ -96,7 +96,7 @@ act runner 必须能够连接到Gitea以接收任务并发送执行结果回来 ### 连接 2,Job容器到Gitea实例 即使Job容器位于同一台机器上,它们的网络命名空间与Runner不同。 -举个例子,如果工作流中包含 `actions/checkout@v3`,Job容器需要连接到Gitea来获取代码。 +举个例子,如果工作流中包含 `actions/checkout@v4`,Job容器需要连接到Gitea来获取代码。 获取代码并不总是运行某些Job所必需的,但在大多数情况下是必需的。 如果您使用回环地址注册Runner,当Runner与Gitea在同一台机器上时,Runner可以连接到Gitea。 @@ -104,7 +104,7 @@ act runner 必须能够连接到Gitea以接收任务并发送执行结果回来 ### 连接 3,act runner到互联网 -当您使用诸如 `actions/checkout@v3` 的一些Actions时,act runner下载的是脚本,而不是Job容器。 +当您使用诸如 `actions/checkout@v4` 的一些Actions时,act runner下载的是脚本,而不是Job容器。 默认情况下,它从[gitea.com](http://gitea.com/)下载,因此需要访问互联网。 它还默认从Docker Hub下载一些Docker镜像,这也需要互联网访问。 @@ -117,7 +117,7 @@ act runner 必须能够连接到Gitea以接收任务并发送执行结果回来 ### 连接 4,Job容器到互联网 -当使用诸如`actions/setup-go@v4`的Actions时,可能需要从互联网下载资源,以设置Job容器中的Go语言环境。 +当使用诸如`actions/setup-go@v5`的Actions时,可能需要从互联网下载资源,以设置Job容器中的Go语言环境。 因此,成功完成这些Actions需要访问互联网。 然而,这也是可选的。 diff --git a/docs/content/usage/actions/faq.en-us.md b/docs/content/usage/actions/faq.en-us.md index 1d59872936a4..7ed59e02cdc0 100644 --- a/docs/content/usage/actions/faq.en-us.md +++ b/docs/content/usage/actions/faq.en-us.md @@ -43,10 +43,10 @@ Still, this is completely optional since both options have the same effect at th Not yet. It is technically possible to implement, but we need to discuss whether it is necessary. -## Where will the runner download scripts when using actions such as `actions/checkout@v3`? +## Where will the runner download scripts when using actions such as `actions/checkout@v4`? You may be aware that there are tens of thousands of [marketplace actions](https://github.com/marketplace?type=actions) in GitHub. -However, when you write `uses: actions/checkout@v3`, it actually downloads the scripts from [gitea.com/actions/checkout](http://gitea.com/actions/checkout) by default (not GitHub). +However, when you write `uses: actions/checkout@v4`, it actually downloads the scripts from [gitea.com/actions/checkout](http://gitea.com/actions/checkout) by default (not GitHub). This is a mirror of [github.com/actions/checkout](http://github.com/actions/checkout), but it's impossible to mirror all of them. That's why you may encounter failures when trying to use some actions that haven't been mirrored. diff --git a/docs/content/usage/actions/faq.zh-cn.md b/docs/content/usage/actions/faq.zh-cn.md index 7bb79d02fc4a..ba5f87bf0c4d 100644 --- a/docs/content/usage/actions/faq.zh-cn.md +++ b/docs/content/usage/actions/faq.zh-cn.md @@ -43,10 +43,10 @@ DEFAULT_REPO_UNITS = ...,repo.actions 目前还不可以。 从技术上讲是可以实现的,但我们需要讨论是否有必要。 -## 使用`actions/checkout@v3`等Actions时,Job容器会从何处下载脚本? +## 使用`actions/checkout@v4`等Actions时,Job容器会从何处下载脚本? 您可能知道GitHub上有成千上万个[Actions市场](https://github.com/marketplace?type=actions)。 -然而,当您编写`uses: actions/checkout@v3`时,它实际上默认从[gitea.com/actions/checkout](http://gitea.com/actions/checkout)下载脚本(而不是从GitHub下载)。 +然而,当您编写`uses: actions/checkout@v4`时,它实际上默认从[gitea.com/actions/checkout](http://gitea.com/actions/checkout)下载脚本(而不是从GitHub下载)。 这是[github.com/actions/checkout](http://github.com/actions/checkout)的镜像,但无法将它们全部镜像。 这就是为什么在尝试使用尚未镜像的某些Actions时可能会遇到失败的原因。 diff --git a/docs/content/usage/actions/overview.en-us.md b/docs/content/usage/actions/overview.en-us.md index 59e539f9c1ba..135fdfd4337f 100644 --- a/docs/content/usage/actions/overview.en-us.md +++ b/docs/content/usage/actions/overview.en-us.md @@ -25,7 +25,7 @@ To avoid confusion, we have clarified the spelling here: - "Gitea Actions" (with an "s", both words capitalized) is the name of the Gitea feature. - "GitHub Actions" is the name of the GitHub feature. - "Actions" could refer to either of the above, depending on the context. So it refers to "Gitea Actions" in this document. -- "action" or "actions" refer to some scripts/plugins to be used, like "actions/checkout@v3" or "actions/cache@v3". +- "action" or "actions" refer to some scripts/plugins to be used, like "actions/checkout@v4" or "actions/cache@v3". ## Runners diff --git a/docs/content/usage/actions/overview.zh-cn.md b/docs/content/usage/actions/overview.zh-cn.md index 0e57bf568f8b..a2ec3070bcfe 100644 --- a/docs/content/usage/actions/overview.zh-cn.md +++ b/docs/content/usage/actions/overview.zh-cn.md @@ -25,7 +25,7 @@ Gitea Actions与[GitHub Actions](https://github.com/features/actions)相似且 - "Gitea Actions"(两个单词都大写且带有"s")是Gitea功能的名称。 - "GitHub Actions"是GitHub功能的名称。 - "Actions"根据上下文的不同可以指代以上任意一个。在本文档中指代的是"Gitea Actions"。 -- "action"或"actions"指代一些要使用的脚本/插件,比如"actions/checkout@v3"或"actions/cache@v3"。 +- "action"或"actions"指代一些要使用的脚本/插件,比如"actions/checkout@v4"或"actions/cache@v3"。 ## Runner diff --git a/docs/content/usage/actions/quickstart.en-us.md b/docs/content/usage/actions/quickstart.en-us.md index f7f4ee2c3669..2a2cf7258477 100644 --- a/docs/content/usage/actions/quickstart.en-us.md +++ b/docs/content/usage/actions/quickstart.en-us.md @@ -113,7 +113,7 @@ jobs: - run: echo "🐧 This job is now running on a ${{ runner.os }} server hosted by Gitea!" - run: echo "🔎 The name of your branch is ${{ gitea.ref }} and your repository is ${{ gitea.repository }}." - name: Check out repository code - uses: actions/checkout@v3 + uses: actions/checkout@v4 - run: echo "💡 The ${{ gitea.repository }} repository has been cloned to the runner." - run: echo "🖥️ The workflow is now ready to test your code on the runner." - name: List files in the repository diff --git a/docs/content/usage/actions/quickstart.zh-cn.md b/docs/content/usage/actions/quickstart.zh-cn.md index ffc1f07df257..8fccc6c909cd 100644 --- a/docs/content/usage/actions/quickstart.zh-cn.md +++ b/docs/content/usage/actions/quickstart.zh-cn.md @@ -112,7 +112,7 @@ jobs: - run: echo "🐧 This job is now running on a ${{ runner.os }} server hosted by Gitea!" - run: echo "🔎 The name of your branch is ${{ gitea.ref }} and your repository is ${{ gitea.repository }}." - name: Check out repository code - uses: actions/checkout@v3 + uses: actions/checkout@v4 - run: echo "💡 The ${{ gitea.repository }} repository has been cloned to the runner." - run: echo "🖥️ The workflow is now ready to test your code on the runner." - name: List files in the repository diff --git a/models/git/branch_test.go b/models/git/branch_test.go index 8febc80f1474..d480e2ec30c2 100644 --- a/models/git/branch_test.go +++ b/models/git/branch_test.go @@ -30,9 +30,8 @@ func TestAddDeletedBranch(t *testing.T) { secondBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{RepoID: repo.ID, Name: "branch2"}) assert.True(t, secondBranch.IsDeleted) - objectFormat := git.ObjectFormatFromName(repo.ObjectFormatName) commit := &git.Commit{ - ID: objectFormat.MustIDFromString(secondBranch.CommitID), + ID: git.MustIDFromString(secondBranch.CommitID), CommitMessage: secondBranch.CommitMessage, Committer: &git.Signature{ When: secondBranch.CommitTime.AsLocalTime(), diff --git a/models/git/commit_status.go b/models/git/commit_status.go index a22fd2304362..488e45de26f3 100644 --- a/models/git/commit_status.go +++ b/models/git/commit_status.go @@ -114,7 +114,7 @@ WHEN NOT MATCHED // GetNextCommitStatusIndex retried 3 times to generate a resource index func GetNextCommitStatusIndex(ctx context.Context, repoID int64, sha string) (int64, error) { - _, err := git.IDFromString(sha) + _, err := git.NewIDFromString(sha) if err != nil { return 0, git.ErrInvalidSHA{SHA: sha} } diff --git a/models/issues/assignees_test.go b/models/issues/assignees_test.go index 3898e814c313..2c33efd99e66 100644 --- a/models/issues/assignees_test.go +++ b/models/issues/assignees_test.go @@ -18,7 +18,10 @@ func TestUpdateAssignee(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // Fake issue with assignees - issue, err := issues_model.GetIssueWithAttrsByID(db.DefaultContext, 1) + issue, err := issues_model.GetIssueByID(db.DefaultContext, 1) + assert.NoError(t, err) + + err = issue.LoadAttributes(db.DefaultContext) assert.NoError(t, err) // Assign multiple users diff --git a/models/issues/comment.go b/models/issues/comment.go index ba5aed9c652e..ce5cf5902d77 100644 --- a/models/issues/comment.go +++ b/models/issues/comment.go @@ -1161,14 +1161,9 @@ func DeleteComment(ctx context.Context, comment *Comment) error { // UpdateCommentsMigrationsByType updates comments' migrations information via given git service type and original id and poster id func UpdateCommentsMigrationsByType(ctx context.Context, tp structs.GitServiceType, originalAuthorID string, posterID int64) error { _, err := db.GetEngine(ctx).Table("comment"). - Where(builder.In("issue_id", - builder.Select("issue.id"). - From("issue"). - InnerJoin("repository", "issue.repo_id = repository.id"). - Where(builder.Eq{ - "repository.original_service_type": tp, - }), - )). + Join("INNER", "issue", "issue.id = comment.issue_id"). + Join("INNER", "repository", "issue.repo_id = repository.id"). + Where("repository.original_service_type = ?", tp). And("comment.original_author_id = ?", originalAuthorID). Update(map[string]any{ "poster_id": posterID, diff --git a/models/issues/issue.go b/models/issues/issue.go index b0ff0adddda1..90aad10bb900 100644 --- a/models/issues/issue.go +++ b/models/issues/issue.go @@ -534,15 +534,6 @@ func GetIssueByID(ctx context.Context, id int64) (*Issue, error) { return issue, nil } -// GetIssueWithAttrsByID returns an issue with attributes by given ID. -func GetIssueWithAttrsByID(ctx context.Context, id int64) (*Issue, error) { - issue, err := GetIssueByID(ctx, id) - if err != nil { - return nil, err - } - return issue, issue.LoadAttributes(ctx) -} - // GetIssuesByIDs return issues with the given IDs. // If keepOrder is true, the order of the returned issues will be the same as the given IDs. func GetIssuesByIDs(ctx context.Context, issueIDs []int64, keepOrder ...bool) (IssueList, error) { diff --git a/models/issues/issue_search.go b/models/issues/issue_search.go index 0bea1fed143b..749a9416085f 100644 --- a/models/issues/issue_search.go +++ b/models/issues/issue_search.go @@ -448,26 +448,6 @@ func applySubscribedCondition(sess *xorm.Session, subscriberID int64) *xorm.Sess ) } -// GetRepoIDsForIssuesOptions find all repo ids for the given options -func GetRepoIDsForIssuesOptions(ctx context.Context, opts *IssuesOptions, user *user_model.User) ([]int64, error) { - repoIDs := make([]int64, 0, 5) - e := db.GetEngine(ctx) - - sess := e.Join("INNER", "repository", "`issue`.repo_id = `repository`.id") - - applyConditions(sess, opts) - - accessCond := repo_model.AccessibleRepositoryCondition(user, unit.TypeInvalid) - if err := sess.Where(accessCond). - Distinct("issue.repo_id"). - Table("issue"). - Find(&repoIDs); err != nil { - return nil, fmt.Errorf("unable to GetRepoIDsForIssuesOptions: %w", err) - } - - return repoIDs, nil -} - // Issues returns a list of issues by given conditions. func Issues(ctx context.Context, opts *IssuesOptions) (IssueList, error) { sess := db.GetEngine(ctx). diff --git a/models/issues/issue_test.go b/models/issues/issue_test.go index 4393d18bcf49..723fa27b1be2 100644 --- a/models/issues/issue_test.go +++ b/models/issues/issue_test.go @@ -216,36 +216,6 @@ func TestIssue_loadTotalTimes(t *testing.T) { assert.Equal(t, int64(3682), ms.TotalTrackedTime) } -func TestGetRepoIDsForIssuesOptions(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) - user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - for _, test := range []struct { - Opts issues_model.IssuesOptions - ExpectedRepoIDs []int64 - }{ - { - issues_model.IssuesOptions{ - AssigneeID: 2, - }, - []int64{3, 32}, - }, - { - issues_model.IssuesOptions{ - RepoCond: builder.In("repo_id", 1, 2), - }, - []int64{1, 2}, - }, - } { - repoIDs, err := issues_model.GetRepoIDsForIssuesOptions(db.DefaultContext, &test.Opts, user) - assert.NoError(t, err) - if assert.Len(t, repoIDs, len(test.ExpectedRepoIDs)) { - for i, repoID := range repoIDs { - assert.EqualValues(t, test.ExpectedRepoIDs[i], repoID) - } - } - } -} - func testInsertIssue(t *testing.T, title, content string, expectIndex int64) *issues_model.Issue { var newIssue issues_model.Issue t.Run(title, func(t *testing.T) { diff --git a/models/issues/label.go b/models/issues/label.go index 5c6b8e08d72f..3b811c1529a5 100644 --- a/models/issues/label.go +++ b/models/issues/label.go @@ -424,22 +424,6 @@ func GetLabelInOrgByID(ctx context.Context, orgID, labelID int64) (*Label, error return l, nil } -// GetLabelIDsInOrgByNames returns a list of labelIDs by names in a given -// organization. -func GetLabelIDsInOrgByNames(ctx context.Context, orgID int64, labelNames []string) ([]int64, error) { - if orgID <= 0 { - return nil, ErrOrgLabelNotExist{0, orgID} - } - labelIDs := make([]int64, 0, len(labelNames)) - - return labelIDs, db.GetEngine(ctx).Table("label"). - Where("org_id = ?", orgID). - In("name", labelNames). - Asc("name"). - Cols("id"). - Find(&labelIDs) -} - // GetLabelsInOrgByIDs returns a list of labels by IDs in given organization, // it silently ignores label IDs that do not belong to the organization. func GetLabelsInOrgByIDs(ctx context.Context, orgID int64, labelIDs []int64) ([]*Label, error) { diff --git a/models/issues/label_test.go b/models/issues/label_test.go index 3a8db6ceec5a..517a3cf1abd4 100644 --- a/models/issues/label_test.go +++ b/models/issues/label_test.go @@ -164,30 +164,6 @@ func TestGetLabelInOrgByName(t *testing.T) { assert.True(t, issues_model.IsErrOrgLabelNotExist(err)) } -func TestGetLabelInOrgByNames(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) - labelIDs, err := issues_model.GetLabelIDsInOrgByNames(db.DefaultContext, 3, []string{"orglabel3", "orglabel4"}) - assert.NoError(t, err) - - assert.Len(t, labelIDs, 2) - - assert.Equal(t, int64(3), labelIDs[0]) - assert.Equal(t, int64(4), labelIDs[1]) -} - -func TestGetLabelInOrgByNamesDiscardsNonExistentLabels(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) - // orglabel99 doesn't exists.. See labels.yml - labelIDs, err := issues_model.GetLabelIDsInOrgByNames(db.DefaultContext, 3, []string{"orglabel3", "orglabel4", "orglabel99"}) - assert.NoError(t, err) - - assert.Len(t, labelIDs, 2) - - assert.Equal(t, int64(3), labelIDs[0]) - assert.Equal(t, int64(4), labelIDs[1]) - assert.NoError(t, err) -} - func TestGetLabelInOrgByID(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) label, err := issues_model.GetLabelInOrgByID(db.DefaultContext, 3, 3) diff --git a/models/issues/milestone_list.go b/models/issues/milestone_list.go index f331b2590faa..a73bf73c17c9 100644 --- a/models/issues/milestone_list.go +++ b/models/issues/milestone_list.go @@ -160,32 +160,6 @@ func (m MilestonesStats) Total() int64 { return m.OpenCount + m.ClosedCount } -// GetMilestonesStatsByRepoCond returns milestone statistic information for dashboard by given conditions. -func GetMilestonesStatsByRepoCond(ctx context.Context, repoCond builder.Cond) (*MilestonesStats, error) { - var err error - stats := &MilestonesStats{} - - sess := db.GetEngine(ctx).Where("is_closed = ?", false) - if repoCond.IsValid() { - sess.And(builder.In("repo_id", builder.Select("id").From("repository").Where(repoCond))) - } - stats.OpenCount, err = sess.Count(new(Milestone)) - if err != nil { - return nil, err - } - - sess = db.GetEngine(ctx).Where("is_closed = ?", true) - if repoCond.IsValid() { - sess.And(builder.In("repo_id", builder.Select("id").From("repository").Where(repoCond))) - } - stats.ClosedCount, err = sess.Count(new(Milestone)) - if err != nil { - return nil, err - } - - return stats, nil -} - // GetMilestonesStatsByRepoCondAndKw returns milestone statistic information for dashboard by given repo conditions and name keyword. func GetMilestonesStatsByRepoCondAndKw(ctx context.Context, repoCond builder.Cond, keyword string) (*MilestonesStats, error) { var err error diff --git a/models/issues/milestone_test.go b/models/issues/milestone_test.go index 0581d3d14881..7477af92c8c4 100644 --- a/models/issues/milestone_test.go +++ b/models/issues/milestone_test.go @@ -17,7 +17,6 @@ import ( "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" - "xorm.io/builder" ) func TestMilestone_State(t *testing.T) { @@ -285,34 +284,6 @@ func TestGetMilestonesByRepoIDs(t *testing.T) { }) } -func TestGetMilestonesStats(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) - - test := func(repoID int64) { - repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) - stats, err := issues_model.GetMilestonesStatsByRepoCond(db.DefaultContext, builder.And(builder.Eq{"repo_id": repoID})) - assert.NoError(t, err) - assert.EqualValues(t, repo.NumMilestones-repo.NumClosedMilestones, stats.OpenCount) - assert.EqualValues(t, repo.NumClosedMilestones, stats.ClosedCount) - } - test(1) - test(2) - test(3) - - stats, err := issues_model.GetMilestonesStatsByRepoCond(db.DefaultContext, builder.And(builder.Eq{"repo_id": unittest.NonexistentID})) - assert.NoError(t, err) - assert.EqualValues(t, 0, stats.OpenCount) - assert.EqualValues(t, 0, stats.ClosedCount) - - repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) - - milestoneStats, err := issues_model.GetMilestonesStatsByRepoCond(db.DefaultContext, builder.In("repo_id", []int64{repo1.ID, repo2.ID})) - assert.NoError(t, err) - assert.EqualValues(t, repo1.NumOpenMilestones+repo2.NumOpenMilestones, milestoneStats.OpenCount) - assert.EqualValues(t, repo1.NumClosedMilestones+repo2.NumClosedMilestones, milestoneStats.ClosedCount) -} - func TestNewMilestone(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) milestone := &issues_model.Milestone{ diff --git a/models/issues/pull.go b/models/issues/pull.go index c51a7daf4eca..34bea921a0d2 100644 --- a/models/issues/pull.go +++ b/models/issues/pull.go @@ -78,24 +78,6 @@ func (err ErrPullRequestAlreadyExists) Unwrap() error { return util.ErrAlreadyExist } -// ErrPullRequestHeadRepoMissing represents a "ErrPullRequestHeadRepoMissing" error -type ErrPullRequestHeadRepoMissing struct { - ID int64 - HeadRepoID int64 -} - -// IsErrErrPullRequestHeadRepoMissing checks if an error is a ErrPullRequestHeadRepoMissing. -func IsErrErrPullRequestHeadRepoMissing(err error) bool { - _, ok := err.(ErrPullRequestHeadRepoMissing) - return ok -} - -// Error does pretty-printing :D -func (err ErrPullRequestHeadRepoMissing) Error() string { - return fmt.Sprintf("pull request head repo missing [id: %d, head_repo_id: %d]", - err.ID, err.HeadRepoID) -} - // ErrPullWasClosed is used close a closed pull request type ErrPullWasClosed struct { ID int64 @@ -758,18 +740,6 @@ func (pr *PullRequest) IsSameRepo() bool { return pr.BaseRepoID == pr.HeadRepoID } -// GetPullRequestsByHeadBranch returns all prs by head branch -// Since there could be multiple prs with the same head branch, this function returns a slice of prs -func GetPullRequestsByHeadBranch(ctx context.Context, headBranch string, headRepoID int64) ([]*PullRequest, error) { - log.Trace("GetPullRequestsByHeadBranch: headBranch: '%s', headRepoID: '%d'", headBranch, headRepoID) - prs := make([]*PullRequest, 0, 2) - if err := db.GetEngine(ctx).Where(builder.Eq{"head_branch": headBranch, "head_repo_id": headRepoID}). - Find(&prs); err != nil { - return nil, err - } - return prs, nil -} - // GetBaseBranchLink returns the relative URL of the base branch func (pr *PullRequest) GetBaseBranchLink(ctx context.Context) string { if err := pr.LoadBaseRepo(ctx); err != nil { diff --git a/models/issues/review.go b/models/issues/review.go index 3db73a09ebcb..e2f65e369f1c 100644 --- a/models/issues/review.go +++ b/models/issues/review.go @@ -460,8 +460,10 @@ func SubmitReview(ctx context.Context, doer *user_model.User, issue *Issue, revi func GetReviewByIssueIDAndUserID(ctx context.Context, issueID, userID int64) (*Review, error) { review := new(Review) - has, err := db.GetEngine(ctx).SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_id = ? AND original_author_id = 0 AND type in (?, ?, ?))", - issueID, userID, ReviewTypeApprove, ReviewTypeReject, ReviewTypeRequest). + has, err := db.GetEngine(ctx).Where( + builder.In("type", ReviewTypeApprove, ReviewTypeReject, ReviewTypeRequest). + And(builder.Eq{"issue_id": issueID, "reviewer_id": userID, "original_author_id": 0})). + Desc("id"). Get(review) if err != nil { return nil, err @@ -475,13 +477,13 @@ func GetReviewByIssueIDAndUserID(ctx context.Context, issueID, userID int64) (*R } // GetTeamReviewerByIssueIDAndTeamID get the latest review request of reviewer team for a pull request -func GetTeamReviewerByIssueIDAndTeamID(ctx context.Context, issueID, teamID int64) (review *Review, err error) { - review = new(Review) +func GetTeamReviewerByIssueIDAndTeamID(ctx context.Context, issueID, teamID int64) (*Review, error) { + review := new(Review) - var has bool - if has, err = db.GetEngine(ctx).SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_team_id = ?)", - issueID, teamID). - Get(review); err != nil { + has, err := db.GetEngine(ctx).Where(builder.Eq{"issue_id": issueID, "reviewer_team_id": teamID}). + Desc("id"). + Get(review) + if err != nil { return nil, err } diff --git a/models/issues/stopwatch.go b/models/issues/stopwatch.go index 2c662bdb06a8..fd9c7d787552 100644 --- a/models/issues/stopwatch.go +++ b/models/issues/stopwatch.go @@ -29,20 +29,6 @@ func (err ErrIssueStopwatchNotExist) Unwrap() error { return util.ErrNotExist } -// ErrIssueStopwatchAlreadyExist represents an error that stopwatch is already exist -type ErrIssueStopwatchAlreadyExist struct { - UserID int64 - IssueID int64 -} - -func (err ErrIssueStopwatchAlreadyExist) Error() string { - return fmt.Sprintf("issue stopwatch already exists[uid: %d, issue_id: %d", err.UserID, err.IssueID) -} - -func (err ErrIssueStopwatchAlreadyExist) Unwrap() error { - return util.ErrAlreadyExist -} - // Stopwatch represents a stopwatch for time tracking. type Stopwatch struct { ID int64 `xorm:"pk autoincr"` diff --git a/modules/cache/cache.go b/modules/cache/cache.go index edaf483135b8..09afc8b7f736 100644 --- a/modules/cache/cache.go +++ b/modules/cache/cache.go @@ -24,11 +24,11 @@ func newCache(cacheConfig setting.Cache) (mc.Cache, error) { }) } -// NewContext start cache service -func NewContext() error { +// Init start cache service +func Init() error { var err error - if conn == nil && setting.CacheService.Enabled { + if conn == nil { if conn, err = newCache(setting.CacheService.Cache); err != nil { return err } diff --git a/modules/cache/cache_test.go b/modules/cache/cache_test.go index cf464af392d5..3f6504092462 100644 --- a/modules/cache/cache_test.go +++ b/modules/cache/cache_test.go @@ -22,9 +22,9 @@ func createTestCache() { } func TestNewContext(t *testing.T) { - assert.NoError(t, NewContext()) + assert.NoError(t, Init()) - setting.CacheService.Cache = setting.Cache{Enabled: true, Adapter: "redis", Conn: "some random string"} + setting.CacheService.Cache = setting.Cache{Adapter: "redis", Conn: "some random string"} con, err := newCache(setting.Cache{ Adapter: "rand", Conn: "false conf", diff --git a/modules/git/commit_info_nogogit.go b/modules/git/commit_info_nogogit.go index 8cf8200c3f74..e469d2cab637 100644 --- a/modules/git/commit_info_nogogit.go +++ b/modules/git/commit_info_nogogit.go @@ -153,7 +153,7 @@ func GetLastCommitForPaths(ctx context.Context, commit *Commit, treePath string, if typ != "commit" { return nil, fmt.Errorf("unexpected type: %s for commit id: %s", typ, commitID) } - c, err = CommitFromReader(commit.repo, commit.ID.Type().MustIDFromString(commitID), io.LimitReader(batchReader, size)) + c, err = CommitFromReader(commit.repo, MustIDFromString(commitID), io.LimitReader(batchReader, size)) if err != nil { return nil, err } diff --git a/modules/git/commit_reader.go b/modules/git/commit_reader.go index 08a529a13219..d74bcffed8a6 100644 --- a/modules/git/commit_reader.go +++ b/modules/git/commit_reader.go @@ -71,10 +71,10 @@ readLoop: switch string(split[0]) { case "tree": - commit.Tree = *NewTree(gitRepo, objectID.Type().MustIDFromString(string(data))) + commit.Tree = *NewTree(gitRepo, MustIDFromString(string(data))) _, _ = payloadSB.Write(line) case "parent": - commit.Parents = append(commit.Parents, objectID.Type().MustIDFromString(string(data))) + commit.Parents = append(commit.Parents, MustIDFromString(string(data))) _, _ = payloadSB.Write(line) case "author": commit.Author = &Signature{} diff --git a/modules/git/commit_test.go b/modules/git/commit_test.go index dec67f662860..e512eecc563b 100644 --- a/modules/git/commit_test.go +++ b/modules/git/commit_test.go @@ -135,8 +135,8 @@ func TestHasPreviousCommit(t *testing.T) { commit, err := repo.GetCommit("8006ff9adbf0cb94da7dad9e537e53817f9fa5c0") assert.NoError(t, err) - parentSHA := repo.objectFormat.MustIDFromString("8d92fc957a4d7cfd98bc375f0b7bb189a0d6c9f2") - notParentSHA := repo.objectFormat.MustIDFromString("2839944139e0de9737a044f78b0e4b40d989a9e3") + parentSHA := MustIDFromString("8d92fc957a4d7cfd98bc375f0b7bb189a0d6c9f2") + notParentSHA := MustIDFromString("2839944139e0de9737a044f78b0e4b40d989a9e3") haz, err := commit.HasPreviousCommit(parentSHA) assert.NoError(t, err) diff --git a/modules/git/last_commit_cache.go b/modules/git/last_commit_cache.go index 55585ac4ac9e..7c7baedd2f39 100644 --- a/modules/git/last_commit_cache.go +++ b/modules/git/last_commit_cache.go @@ -39,7 +39,7 @@ func NewLastCommitCache(count int64, repoPath string, gitRepo *Repository, cache if cache == nil { return nil } - if !setting.CacheService.LastCommit.Enabled || count < setting.CacheService.LastCommit.CommitsCount { + if count < setting.CacheService.LastCommit.CommitsCount { return nil } @@ -92,11 +92,7 @@ func (c *LastCommitCache) Get(ref, entryPath string) (*Commit, error) { // GetCommitByPath gets the last commit for the entry in the provided commit func (c *LastCommitCache) GetCommitByPath(commitID, entryPath string) (*Commit, error) { - objectFormat, err := c.repo.GetObjectFormat() - if err != nil { - return nil, err - } - sha, err := objectFormat.NewIDFromString(commitID) + sha, err := NewIDFromString(commitID) if err != nil { return nil, err } diff --git a/modules/git/object_format.go b/modules/git/object_format.go index ee7e659ed04d..27771e74598d 100644 --- a/modules/git/object_format.go +++ b/modules/git/object_format.go @@ -6,6 +6,7 @@ package git import ( "crypto/sha1" "regexp" + "strconv" ) // sha1Pattern can be used to determine if a string is an valid sha @@ -20,14 +21,12 @@ type ObjectFormat interface { EmptyTree() ObjectID // FullLength is the length of the hash's hex string FullLength() int - + // IsValid returns true if the input is a valid hash IsValid(input string) bool + // MustID creates a new ObjectID from a byte slice MustID(b []byte) ObjectID - MustIDFromString(s string) ObjectID - NewID(b []byte) (ObjectID, error) - NewIDFromString(s string) (ObjectID, error) - - NewHasher() HasherInterface + // ComputeHash compute the hash for a given ObjectType and content + ComputeHash(t ObjectType, content []byte) ObjectID } type Sha1ObjectFormatImpl struct{} @@ -59,20 +58,18 @@ func (Sha1ObjectFormatImpl) MustID(b []byte) ObjectID { return &id } -func (h Sha1ObjectFormatImpl) MustIDFromString(s string) ObjectID { - return MustIDFromString(h, s) -} - -func (h Sha1ObjectFormatImpl) NewID(b []byte) (ObjectID, error) { - return IDFromRaw(h, b) -} - -func (h Sha1ObjectFormatImpl) NewIDFromString(s string) (ObjectID, error) { - return genericIDFromString(h, s) -} - -func (h Sha1ObjectFormatImpl) NewHasher() HasherInterface { - return &Sha1Hasher{sha1.New()} +// ComputeHash compute the hash for a given ObjectType and content +func (h Sha1ObjectFormatImpl) ComputeHash(t ObjectType, content []byte) ObjectID { + hasher := sha1.New() + _, _ = hasher.Write(t.Bytes()) + _, _ = hasher.Write([]byte(" ")) + _, _ = hasher.Write([]byte(strconv.FormatInt(int64(len(content)), 10))) + _, _ = hasher.Write([]byte{0}) + + // HashSum generates a SHA1 for the provided hash + var sha1 Sha1Hash + copy(sha1[:], hasher.Sum(nil)) + return &sha1 } var Sha1ObjectFormat ObjectFormat = Sha1ObjectFormatImpl{} diff --git a/modules/git/object_id.go b/modules/git/object_id.go index a90683678a81..01c23ed3dae8 100644 --- a/modules/git/object_id.go +++ b/modules/git/object_id.go @@ -6,11 +6,7 @@ package git import ( "bytes" "encoding/hex" - "errors" "fmt" - "hash" - "strconv" - "strings" ) type ObjectID interface { @@ -35,48 +31,36 @@ func (*Sha1Hash) Type() ObjectFormat { return Sha1ObjectFormat } var _ ObjectID = &Sha1Hash{} -// EmptyObjectID creates a new ObjectID from an object format hash name -func EmptyObjectID(objectFormatName string) (ObjectID, error) { - objectFormat := ObjectFormatFromName(objectFormatName) - if objectFormat != nil { - return objectFormat.EmptyObjectID(), nil +func MustIDFromString(hexHash string) ObjectID { + id, err := NewIDFromString(hexHash) + if err != nil { + panic(err) } - - return nil, errors.New("unsupported hash type") + return id } -func IDFromRaw(h ObjectFormat, b []byte) (ObjectID, error) { - if len(b) != h.FullLength()/2 { - return h.EmptyObjectID(), fmt.Errorf("length must be %d: %v", h.FullLength(), b) +func NewIDFromString(hexHash string) (ObjectID, error) { + var theObjectFormat ObjectFormat + for _, objectFormat := range SupportedObjectFormats { + if len(hexHash) == objectFormat.FullLength() { + theObjectFormat = objectFormat + break + } } - return h.MustID(b), nil -} -func MustIDFromString(h ObjectFormat, s string) ObjectID { - b, _ := hex.DecodeString(s) - return h.MustID(b) -} - -func genericIDFromString(h ObjectFormat, s string) (ObjectID, error) { - s = strings.TrimSpace(s) - if len(s) != h.FullLength() { - return h.EmptyObjectID(), fmt.Errorf("length must be %d: %s", h.FullLength(), s) + if theObjectFormat == nil { + return nil, fmt.Errorf("length %d has no matched object format: %s", len(hexHash), hexHash) } - b, err := hex.DecodeString(s) + + b, err := hex.DecodeString(hexHash) if err != nil { - return h.EmptyObjectID(), err + return nil, err } - return h.NewID(b) -} -func IDFromString(hexHash string) (ObjectID, error) { - for _, objectFormat := range SupportedObjectFormats { - if len(hexHash) == objectFormat.FullLength() { - return objectFormat.NewIDFromString(hexHash) - } + if len(b) != theObjectFormat.FullLength()/2 { + return theObjectFormat.EmptyObjectID(), fmt.Errorf("length must be %d: %v", theObjectFormat.FullLength(), b) } - - return nil, fmt.Errorf("invalid hash hex string: '%s' len: %d", hexHash, len(hexHash)) + return theObjectFormat.MustID(b), nil } func IsEmptyCommitID(commitID string) bool { @@ -84,7 +68,7 @@ func IsEmptyCommitID(commitID string) bool { return true } - id, err := IDFromString(commitID) + id, err := NewIDFromString(commitID) if err != nil { return false } @@ -92,37 +76,9 @@ func IsEmptyCommitID(commitID string) bool { return id.IsZero() } -// HasherInterface is a struct that will generate a Hash -type HasherInterface interface { - hash.Hash - - HashSum() ObjectID -} - -type Sha1Hasher struct { - hash.Hash -} - // ComputeBlobHash compute the hash for a given blob content func ComputeBlobHash(hashType ObjectFormat, content []byte) ObjectID { - return ComputeHash(hashType, ObjectBlob, content) -} - -// ComputeHash compute the hash for a given ObjectType and content -func ComputeHash(hashType ObjectFormat, t ObjectType, content []byte) ObjectID { - h := hashType.NewHasher() - _, _ = h.Write(t.Bytes()) - _, _ = h.Write([]byte(" ")) - _, _ = h.Write([]byte(strconv.FormatInt(int64(len(content)), 10))) - _, _ = h.Write([]byte{0}) - return h.HashSum() -} - -// HashSum generates a SHA1 for the provided hash -func (h *Sha1Hasher) HashSum() ObjectID { - var sha1 Sha1Hash - copy(sha1[:], h.Hash.Sum(nil)) - return &sha1 + return hashType.ComputeHash(ObjectBlob, content) } type ErrInvalidSHA struct { diff --git a/modules/git/parse_gogit.go b/modules/git/parse_gogit.go index 6c22ea8da7bf..d1fdd346e415 100644 --- a/modules/git/parse_gogit.go +++ b/modules/git/parse_gogit.go @@ -57,7 +57,7 @@ func parseTreeEntries(data []byte, ptree *Tree) ([]*TreeEntry, error) { return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data)) } var err error - entry.ID, err = IDFromString(string(data[pos : pos+hash.Size*2])) + entry.ID, err = NewIDFromString(string(data[pos : pos+hash.Size*2])) if err != nil { return nil, fmt.Errorf("invalid ls-tree output: %w", err) } diff --git a/modules/git/parse_gogit_test.go b/modules/git/parse_gogit_test.go index 9755f81cce61..d9e5b4441fff 100644 --- a/modules/git/parse_gogit_test.go +++ b/modules/git/parse_gogit_test.go @@ -28,9 +28,9 @@ func TestParseTreeEntries(t *testing.T) { Input: "100644 blob 61ab7345a1a3bbc590068ccae37b8515cfc5843c 1022\texample/file2.txt\n", Expected: []*TreeEntry{ { - ID: Sha1ObjectFormat.MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c"), + ID: MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c"), gogitTreeEntry: &object.TreeEntry{ - Hash: plumbing.Hash(Sha1ObjectFormat.MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c").RawValue()), + Hash: plumbing.Hash(MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c").RawValue()), Name: "example/file2.txt", Mode: filemode.Regular, }, @@ -44,9 +44,9 @@ func TestParseTreeEntries(t *testing.T) { "040000 tree 1d01fb729fb0db5881daaa6030f9f2d3cd3d5ae8 -\texample\n", Expected: []*TreeEntry{ { - ID: Sha1ObjectFormat.MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c"), + ID: MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c"), gogitTreeEntry: &object.TreeEntry{ - Hash: plumbing.Hash(Sha1ObjectFormat.MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c").RawValue()), + Hash: plumbing.Hash(MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c").RawValue()), Name: "example/\n.txt", Mode: filemode.Symlink, }, @@ -54,10 +54,10 @@ func TestParseTreeEntries(t *testing.T) { sized: true, }, { - ID: Sha1ObjectFormat.MustIDFromString("1d01fb729fb0db5881daaa6030f9f2d3cd3d5ae8"), + ID: MustIDFromString("1d01fb729fb0db5881daaa6030f9f2d3cd3d5ae8"), sized: true, gogitTreeEntry: &object.TreeEntry{ - Hash: plumbing.Hash(Sha1ObjectFormat.MustIDFromString("1d01fb729fb0db5881daaa6030f9f2d3cd3d5ae8").RawValue()), + Hash: plumbing.Hash(MustIDFromString("1d01fb729fb0db5881daaa6030f9f2d3cd3d5ae8").RawValue()), Name: "example", Mode: filemode.Dir, }, diff --git a/modules/git/parse_nogogit.go b/modules/git/parse_nogogit.go index e35704eb34e9..225342cc5a10 100644 --- a/modules/git/parse_nogogit.go +++ b/modules/git/parse_nogogit.go @@ -72,7 +72,7 @@ func parseTreeEntries(objectFormat ObjectFormat, data []byte, ptree *Tree) ([]*T return nil, fmt.Errorf("unknown type: %v", string(entryMode)) } - entry.ID, err = objectFormat.NewIDFromString(string(entryObjectID)) + entry.ID, err = NewIDFromString(string(entryObjectID)) if err != nil { return nil, fmt.Errorf("invalid ls-tree output (invalid object id): %q, err: %w", line, err) } diff --git a/modules/git/parse_nogogit_test.go b/modules/git/parse_nogogit_test.go index 36313e00f331..f037fd7a2e75 100644 --- a/modules/git/parse_nogogit_test.go +++ b/modules/git/parse_nogogit_test.go @@ -26,28 +26,28 @@ func TestParseTreeEntriesLong(t *testing.T) { `, Expected: []*TreeEntry{ { - ID: objectFormat.MustIDFromString("ea0d83c9081af9500ac9f804101b3fd0a5c293af"), + ID: MustIDFromString("ea0d83c9081af9500ac9f804101b3fd0a5c293af"), name: "README.md", entryMode: EntryModeBlob, size: 8218, sized: true, }, { - ID: objectFormat.MustIDFromString("037f27dc9d353ae4fd50f0474b2194c593914e35"), + ID: MustIDFromString("037f27dc9d353ae4fd50f0474b2194c593914e35"), name: "README_ZH.md", entryMode: EntryModeBlob, size: 4681, sized: true, }, { - ID: objectFormat.MustIDFromString("9846a94f7e8350a916632929d0fda38c90dd2ca8"), + ID: MustIDFromString("9846a94f7e8350a916632929d0fda38c90dd2ca8"), name: "SECURITY.md", entryMode: EntryModeBlob, size: 429, sized: true, }, { - ID: objectFormat.MustIDFromString("84b90550547016f73c5dd3f50dea662389e67b6d"), + ID: MustIDFromString("84b90550547016f73c5dd3f50dea662389e67b6d"), name: "assets", entryMode: EntryModeTree, sized: true, @@ -78,12 +78,12 @@ func TestParseTreeEntriesShort(t *testing.T) { `, Expected: []*TreeEntry{ { - ID: objectFormat.MustIDFromString("ea0d83c9081af9500ac9f804101b3fd0a5c293af"), + ID: MustIDFromString("ea0d83c9081af9500ac9f804101b3fd0a5c293af"), name: "README.md", entryMode: EntryModeBlob, }, { - ID: objectFormat.MustIDFromString("84b90550547016f73c5dd3f50dea662389e67b6d"), + ID: MustIDFromString("84b90550547016f73c5dd3f50dea662389e67b6d"), name: "assets", entryMode: EntryModeTree, }, diff --git a/modules/git/pipeline/lfs_nogogit.go b/modules/git/pipeline/lfs_nogogit.go index 89cbf740ffa9..a725f4799db8 100644 --- a/modules/git/pipeline/lfs_nogogit.go +++ b/modules/git/pipeline/lfs_nogogit.go @@ -115,11 +115,7 @@ func FindLFSFile(repo *git.Repository, objectID git.ObjectID) ([]*LFSResult, err continue case "commit": // Read in the commit to get its tree and in case this is one of the last used commits - objectFormat, err := repo.GetObjectFormat() - if err != nil { - return nil, err - } - curCommit, err = git.CommitFromReader(repo, objectFormat.MustIDFromString(string(commitID)), io.LimitReader(batchReader, size)) + curCommit, err = git.CommitFromReader(repo, git.MustIDFromString(string(commitID)), io.LimitReader(batchReader, size)) if err != nil { return nil, err } diff --git a/modules/git/repo.go b/modules/git/repo.go index 52e54715d653..7ccce0ba20e6 100644 --- a/modules/git/repo.go +++ b/modules/git/repo.go @@ -81,7 +81,7 @@ func GetObjectFormatOfRepo(ctx context.Context, repoPath string) (ObjectFormat, return nil, errors.New(stderr.String()) } - h, err := IDFromString(strings.TrimRight(stdout.String(), "\n")) + h, err := NewIDFromString(strings.TrimRight(stdout.String(), "\n")) if err != nil { return nil, err } diff --git a/modules/git/repo_blob.go b/modules/git/repo_blob.go index b5447b2bb131..698b6c7074a6 100644 --- a/modules/git/repo_blob.go +++ b/modules/git/repo_blob.go @@ -5,7 +5,7 @@ package git // GetBlob finds the blob object in the repository. func (repo *Repository) GetBlob(idStr string) (*Blob, error) { - id, err := repo.objectFormat.NewIDFromString(idStr) + id, err := NewIDFromString(idStr) if err != nil { return nil, err } diff --git a/modules/git/repo_blob_test.go b/modules/git/repo_blob_test.go index e12257395418..8a5f5fcd5b05 100644 --- a/modules/git/repo_blob_test.go +++ b/modules/git/repo_blob_test.go @@ -61,7 +61,7 @@ func TestRepository_GetBlob_NoId(t *testing.T) { defer r.Close() testCase := "" - testError := fmt.Errorf("length must be 40: %s", testCase) + testError := fmt.Errorf("length %d has no matched object format: %s", len(testCase), testCase) blob, err := r.GetBlob(testCase) assert.Nil(t, blob) diff --git a/modules/git/repo_commit.go b/modules/git/repo_commit.go index 58bbcf9303f2..ccb3eb4adef0 100644 --- a/modules/git/repo_commit.go +++ b/modules/git/repo_commit.go @@ -63,7 +63,7 @@ func (repo *Repository) getCommitByPathWithID(id ObjectID, relpath string) (*Com return nil, runErr } - id, err := repo.objectFormat.NewIDFromString(stdout) + id, err := NewIDFromString(stdout) if err != nil { return nil, err } @@ -254,7 +254,7 @@ func (repo *Repository) CommitsByFileAndRange(opts CommitsByFileAndRangeOptions) } return commits, err } - objectID, err := repo.objectFormat.NewIDFromString(string(shaline[0:len])) + objectID, err := NewIDFromString(string(shaline[0:len])) if err != nil { return nil, err } diff --git a/modules/git/repo_commit_gogit.go b/modules/git/repo_commit_gogit.go index d0992fd385ae..4cab9575644c 100644 --- a/modules/git/repo_commit_gogit.go +++ b/modules/git/repo_commit_gogit.go @@ -43,7 +43,7 @@ func (repo *Repository) RemoveReference(name string) error { func (repo *Repository) ConvertToGitID(commitID string) (ObjectID, error) { objectFormat := repo.objectFormat if len(commitID) == hash.HexSize && objectFormat.IsValid(commitID) { - ID, err := objectFormat.NewIDFromString(commitID) + ID, err := NewIDFromString(commitID) if err == nil { return ID, nil } @@ -59,7 +59,7 @@ func (repo *Repository) ConvertToGitID(commitID string) (ObjectID, error) { return objectFormat.EmptyObjectID(), err } - return objectFormat.NewIDFromString(actualCommitID) + return NewIDFromString(actualCommitID) } // IsCommitExist returns true if given commit exists in current repository. diff --git a/modules/git/repo_commit_nogogit.go b/modules/git/repo_commit_nogogit.go index 018e271c394e..f0214e1ff858 100644 --- a/modules/git/repo_commit_nogogit.go +++ b/modules/git/repo_commit_nogogit.go @@ -135,7 +135,7 @@ func (repo *Repository) getCommitFromBatchReader(rd *bufio.Reader, id ObjectID) func (repo *Repository) ConvertToGitID(commitID string) (ObjectID, error) { IDType := repo.objectFormat if len(commitID) == IDType.FullLength() && IDType.IsValid(commitID) { - ID, err := repo.objectFormat.NewIDFromString(commitID) + ID, err := NewIDFromString(commitID) if err == nil { return ID, nil } @@ -155,5 +155,5 @@ func (repo *Repository) ConvertToGitID(commitID string) (ObjectID, error) { return nil, err } - return repo.objectFormat.MustIDFromString(string(sha)), nil + return MustIDFromString(string(sha)), nil } diff --git a/modules/git/repo_index.go b/modules/git/repo_index.go index e3b19bf03646..47705a92af6f 100644 --- a/modules/git/repo_index.go +++ b/modules/git/repo_index.go @@ -30,7 +30,7 @@ func (repo *Repository) ReadTreeToIndex(treeish string, indexFilename ...string) treeish = res[:len(res)-1] } } - id, err := objectFormat.NewIDFromString(treeish) + id, err := NewIDFromString(treeish) if err != nil { return err } @@ -128,7 +128,7 @@ func (repo *Repository) WriteTree() (*Tree, error) { if runErr != nil { return nil, runErr } - id, err := repo.objectFormat.NewIDFromString(strings.TrimSpace(stdout)) + id, err := NewIDFromString(strings.TrimSpace(stdout)) if err != nil { return nil, err } diff --git a/modules/git/repo_language_stats_nogogit.go b/modules/git/repo_language_stats_nogogit.go index b733c119f9e7..1d94ad6c00f4 100644 --- a/modules/git/repo_language_stats_nogogit.go +++ b/modules/git/repo_language_stats_nogogit.go @@ -39,7 +39,7 @@ func (repo *Repository) GetLanguageStats(commitID string) (map[string]int64, err return nil, ErrNotExist{commitID, ""} } - sha, err := repo.objectFormat.NewIDFromString(string(shaBytes)) + sha, err := NewIDFromString(string(shaBytes)) if err != nil { log.Debug("Unable to get commit for: %s. Err: %v", commitID, err) return nil, ErrNotExist{commitID, ""} diff --git a/modules/git/repo_object.go b/modules/git/repo_object.go index 220fdb38074d..3d48b91c6d96 100644 --- a/modules/git/repo_object.go +++ b/modules/git/repo_object.go @@ -46,7 +46,7 @@ func (repo *Repository) GetObjectFormat() (ObjectFormat, error) { if err != nil { return nil, err } - hash, err := IDFromString(str) + hash, err := NewIDFromString(str) if err != nil { return nil, err } @@ -62,7 +62,7 @@ func (repo *Repository) HashObject(reader io.Reader) (ObjectID, error) { if err != nil { return nil, err } - return repo.objectFormat.NewIDFromString(idStr) + return NewIDFromString(idStr) } func (repo *Repository) hashObject(reader io.Reader, save bool) (string, error) { diff --git a/modules/git/repo_ref_nogogit.go b/modules/git/repo_ref_nogogit.go index c1be60871cfe..ac53d661b517 100644 --- a/modules/git/repo_ref_nogogit.go +++ b/modules/git/repo_ref_nogogit.go @@ -75,7 +75,7 @@ func (repo *Repository) GetRefsFiltered(pattern string) ([]*Reference, error) { if pattern == "" || strings.HasPrefix(refName, pattern) { r := &Reference{ Name: refName, - Object: repo.objectFormat.MustIDFromString(sha), + Object: MustIDFromString(sha), Type: typ, repo: repo, } diff --git a/modules/git/repo_tag.go b/modules/git/repo_tag.go index 0b08e457cbe9..698b9b41f3ce 100644 --- a/modules/git/repo_tag.go +++ b/modules/git/repo_tag.go @@ -84,7 +84,7 @@ func (repo *Repository) GetTag(name string) (*Tag, error) { return nil, err } - id, err := repo.objectFormat.NewIDFromString(idStr) + id, err := NewIDFromString(idStr) if err != nil { return nil, err } @@ -98,7 +98,7 @@ func (repo *Repository) GetTag(name string) (*Tag, error) { // GetTagWithID returns a Git tag by given name and ID func (repo *Repository) GetTagWithID(idStr, name string) (*Tag, error) { - id, err := repo.objectFormat.NewIDFromString(idStr) + id, err := NewIDFromString(idStr) if err != nil { return nil, err } @@ -165,7 +165,7 @@ func parseTagRef(objectFormat ObjectFormat, ref map[string]string) (tag *Tag, er Name: ref["refname:short"], } - tag.ID, err = objectFormat.NewIDFromString(ref["objectname"]) + tag.ID, err = NewIDFromString(ref["objectname"]) if err != nil { return nil, fmt.Errorf("parse objectname '%s': %w", ref["objectname"], err) } @@ -175,7 +175,7 @@ func parseTagRef(objectFormat ObjectFormat, ref map[string]string) (tag *Tag, er tag.Object = tag.ID } else { // annotated tag - tag.Object, err = objectFormat.NewIDFromString(ref["object"]) + tag.Object, err = NewIDFromString(ref["object"]) if err != nil { return nil, fmt.Errorf("parse object '%s': %w", ref["object"], err) } @@ -208,7 +208,7 @@ func parseTagRef(objectFormat ObjectFormat, ref map[string]string) (tag *Tag, er // GetAnnotatedTag returns a Git tag by its SHA, must be an annotated tag func (repo *Repository) GetAnnotatedTag(sha string) (*Tag, error) { - id, err := repo.objectFormat.NewIDFromString(sha) + id, err := NewIDFromString(sha) if err != nil { return nil, err } diff --git a/modules/git/repo_tag_gogit.go b/modules/git/repo_tag_gogit.go index c3711ba5a07d..4a7a06e9bdaf 100644 --- a/modules/git/repo_tag_gogit.go +++ b/modules/git/repo_tag_gogit.go @@ -88,7 +88,7 @@ func (repo *Repository) getTag(tagID ObjectID, name string) (*Tag, error) { // every tag should have a commit ID so return all errors return nil, err } - commitID, err := IDFromString(commitIDStr) + commitID, err := NewIDFromString(commitIDStr) if err != nil { return nil, err } diff --git a/modules/git/repo_tag_nogogit.go b/modules/git/repo_tag_nogogit.go index 3cea4894f17a..5d98fadd5436 100644 --- a/modules/git/repo_tag_nogogit.go +++ b/modules/git/repo_tag_nogogit.go @@ -64,7 +64,7 @@ func (repo *Repository) getTag(tagID ObjectID, name string) (*Tag, error) { // every tag should have a commit ID so return all errors return nil, err } - commitID, err := repo.objectFormat.NewIDFromString(commitIDStr) + commitID, err := NewIDFromString(commitIDStr) if err != nil { return nil, err } diff --git a/modules/git/repo_tag_test.go b/modules/git/repo_tag_test.go index 48c1bc41c237..6b9df1746f7d 100644 --- a/modules/git/repo_tag_test.go +++ b/modules/git/repo_tag_test.go @@ -224,8 +224,8 @@ func TestRepository_parseTagRef(t *testing.T) { want: &Tag{ Name: "v1.9.1", - ID: sha1.MustIDFromString("ab23e4b7f4cd0caafe0174c0e7ef6d651ba72889"), - Object: sha1.MustIDFromString("ab23e4b7f4cd0caafe0174c0e7ef6d651ba72889"), + ID: MustIDFromString("ab23e4b7f4cd0caafe0174c0e7ef6d651ba72889"), + Object: MustIDFromString("ab23e4b7f4cd0caafe0174c0e7ef6d651ba72889"), Type: "commit", Tagger: parseAuthorLine(t, "Foo Bar 1565789218 +0300"), Message: "Add changelog of v1.9.1 (#7859)\n\n* add changelog of v1.9.1\n* Update CHANGELOG.md\n", @@ -253,8 +253,8 @@ func TestRepository_parseTagRef(t *testing.T) { want: &Tag{ Name: "v0.0.1", - ID: sha1.MustIDFromString("8c68a1f06fc59c655b7e3905b159d761e91c53c9"), - Object: sha1.MustIDFromString("3325fd8a973321fd59455492976c042dde3fd1ca"), + ID: MustIDFromString("8c68a1f06fc59c655b7e3905b159d761e91c53c9"), + Object: MustIDFromString("3325fd8a973321fd59455492976c042dde3fd1ca"), Type: "tag", Tagger: parseAuthorLine(t, "Foo Bar 1565789218 +0300"), Message: "Add changelog of v1.9.1 (#7859)\n\n* add changelog of v1.9.1\n* Update CHANGELOG.md\n", @@ -311,8 +311,8 @@ qbHDASXl want: &Tag{ Name: "v0.0.1", - ID: sha1.MustIDFromString("8c68a1f06fc59c655b7e3905b159d761e91c53c9"), - Object: sha1.MustIDFromString("3325fd8a973321fd59455492976c042dde3fd1ca"), + ID: MustIDFromString("8c68a1f06fc59c655b7e3905b159d761e91c53c9"), + Object: MustIDFromString("3325fd8a973321fd59455492976c042dde3fd1ca"), Type: "tag", Tagger: parseAuthorLine(t, "Foo Bar 1565789218 +0300"), Message: "Add changelog of v1.9.1 (#7859)\n\n* add changelog of v1.9.1\n* Update CHANGELOG.md", diff --git a/modules/git/repo_tree.go b/modules/git/repo_tree.go index 9ee80351f0f6..ab48d47d13c0 100644 --- a/modules/git/repo_tree.go +++ b/modules/git/repo_tree.go @@ -63,5 +63,5 @@ func (repo *Repository) CommitTree(author, committer *Signature, tree *Tree, opt if err != nil { return nil, ConcatenateError(err, stderr.String()) } - return repo.objectFormat.NewIDFromString(strings.TrimSpace(stdout.String())) + return NewIDFromString(strings.TrimSpace(stdout.String())) } diff --git a/modules/git/repo_tree_gogit.go b/modules/git/repo_tree_gogit.go index 415572e65a13..6391959e6acd 100644 --- a/modules/git/repo_tree_gogit.go +++ b/modules/git/repo_tree_gogit.go @@ -30,7 +30,7 @@ func (repo *Repository) GetTree(idStr string) (*Tree, error) { idStr = res[:len(res)-1] } } - id, err := repo.objectFormat.NewIDFromString(idStr) + id, err := NewIDFromString(idStr) if err != nil { return nil, err } diff --git a/modules/git/repo_tree_nogogit.go b/modules/git/repo_tree_nogogit.go index f502cc140b7f..20c92a79ed9b 100644 --- a/modules/git/repo_tree_nogogit.go +++ b/modules/git/repo_tree_nogogit.go @@ -75,7 +75,7 @@ func (repo *Repository) GetTree(idStr string) (*Tree, error) { idStr = res } } - id, err := repo.objectFormat.NewIDFromString(idStr) + id, err := NewIDFromString(idStr) if err != nil { return nil, err } diff --git a/modules/git/tag.go b/modules/git/tag.go index c7d0d8aef92b..01a8d6f6a552 100644 --- a/modules/git/tag.go +++ b/modules/git/tag.go @@ -50,7 +50,7 @@ l: reftype := line[:spacepos] switch string(reftype) { case "object": - id, err := objectFormat.NewIDFromString(string(line[spacepos+1:])) + id, err := NewIDFromString(string(line[spacepos+1:])) if err != nil { return nil, err } diff --git a/modules/lfs/http_client.go b/modules/lfs/http_client.go index de0b1e4fede4..417747336238 100644 --- a/modules/lfs/http_client.go +++ b/modules/lfs/http_client.go @@ -79,7 +79,10 @@ func (c *HTTPClient) batch(ctx context.Context, operation string, objects []Poin return nil, err } - req, err := createRequest(ctx, http.MethodPost, url, map[string]string{"Content-Type": MediaType}, payload) + req, err := createRequest(ctx, http.MethodPost, url, map[string]string{ + "Content-Type": MediaType, + "Accept": MediaType, + }, payload) if err != nil { return nil, err } diff --git a/modules/markup/html.go b/modules/markup/html.go index 774cbe1557e4..03168b694681 100644 --- a/modules/markup/html.go +++ b/modules/markup/html.go @@ -852,7 +852,9 @@ func fullIssuePatternProcessor(ctx *RenderContext, node *html.Node) { } func issueIndexPatternProcessor(ctx *RenderContext, node *html.Node) { - if ctx.Metas == nil || ctx.Metas["mode"] == "document" { + // FIXME: the use of "mode" is quite dirty and hacky, for example: what is a "document"? how should it be rendered? + // The "mode" approach should be refactored to some other more clear&reliable way. + if ctx.Metas == nil || (ctx.Metas["mode"] == "document" && !ctx.IsWiki) { return } var ( diff --git a/modules/repository/commits_test.go b/modules/repository/commits_test.go index afcb183d7237..248673a907d4 100644 --- a/modules/repository/commits_test.go +++ b/modules/repository/commits_test.go @@ -126,9 +126,10 @@ func TestPushCommits_AvatarLink(t *testing.T) { } setting.GravatarSource = "https://secure.gravatar.com/avatar" + setting.OfflineMode = true assert.Equal(t, - "https://secure.gravatar.com/avatar/ab53a2911ddf9b4817ac01ddcd3d975f?d=identicon&s="+strconv.Itoa(28*setting.Avatar.RenderedSizeFactor), + "/avatars/avatar2?size="+strconv.Itoa(28*setting.Avatar.RenderedSizeFactor), pushCommits.AvatarLink(db.DefaultContext, "user2@example.com")) assert.Equal(t, @@ -144,7 +145,7 @@ func TestCommitToPushCommit(t *testing.T) { When: now, } const hexString = "0123456789abcdef0123456789abcdef01234567" - sha1, err := git.IDFromString(hexString) + sha1, err := git.NewIDFromString(hexString) assert.NoError(t, err) pushCommit := CommitToPushCommit(&git.Commit{ ID: sha1, @@ -169,12 +170,11 @@ func TestListToPushCommits(t *testing.T) { When: now, } - hashType := git.Sha1ObjectFormat const hexString1 = "0123456789abcdef0123456789abcdef01234567" - hash1, err := hashType.NewIDFromString(hexString1) + hash1, err := git.NewIDFromString(hexString1) assert.NoError(t, err) const hexString2 = "fedcba9876543210fedcba9876543210fedcba98" - hash2, err := hashType.NewIDFromString(hexString2) + hash2, err := git.NewIDFromString(hexString2) assert.NoError(t, err) l := []*git.Commit{ diff --git a/modules/repository/push.go b/modules/repository/push.go index 25695336a52d..cf047847b6ca 100644 --- a/modules/repository/push.go +++ b/modules/repository/push.go @@ -20,13 +20,13 @@ type PushUpdateOptions struct { // IsNewRef return true if it's a first-time push to a branch, tag or etc. func (opts *PushUpdateOptions) IsNewRef() bool { - commitID, err := git.IDFromString(opts.OldCommitID) + commitID, err := git.NewIDFromString(opts.OldCommitID) return err == nil && commitID.IsZero() } // IsDelRef return true if it's a deletion to a branch or tag func (opts *PushUpdateOptions) IsDelRef() bool { - commitID, err := git.IDFromString(opts.NewCommitID) + commitID, err := git.NewIDFromString(opts.NewCommitID) return err == nil && commitID.IsZero() } diff --git a/modules/setting/cache.go b/modules/setting/cache.go index 783246077d90..bfa6ca0e6167 100644 --- a/modules/setting/cache.go +++ b/modules/setting/cache.go @@ -12,7 +12,6 @@ import ( // Cache represents cache settings type Cache struct { - Enabled bool Adapter string Interval int Conn string @@ -24,23 +23,19 @@ var CacheService = struct { Cache `ini:"cache"` LastCommit struct { - Enabled bool TTL time.Duration `ini:"ITEM_TTL"` CommitsCount int64 } `ini:"cache.last_commit"` }{ Cache: Cache{ - Enabled: true, Adapter: "memory", Interval: 60, TTL: 16 * time.Hour, }, LastCommit: struct { - Enabled bool TTL time.Duration `ini:"ITEM_TTL"` CommitsCount int64 }{ - Enabled: true, TTL: 8760 * time.Hour, CommitsCount: 1000, }, @@ -65,30 +60,12 @@ func loadCacheFrom(rootCfg ConfigProvider) { if CacheService.Conn == "" { CacheService.Conn = "50000" } - case "": // disable cache - CacheService.Enabled = false default: log.Fatal("Unknown cache adapter: %s", CacheService.Adapter) } - if CacheService.Enabled { - log.Info("Cache Service Enabled") - } else { - log.Warn("Cache Service Disabled so that captcha disabled too") - // captcha depends on cache service - Service.EnableCaptcha = false - } - sec = rootCfg.Section("cache.last_commit") - if !CacheService.Enabled { - CacheService.LastCommit.Enabled = false - } - CacheService.LastCommit.CommitsCount = sec.Key("COMMITS_COUNT").MustInt64(1000) - - if CacheService.LastCommit.Enabled { - log.Info("Last Commit Cache Service Enabled") - } } // TTLSeconds returns the TTLSeconds or unix timestamp for memcache diff --git a/modules/setting/server.go b/modules/setting/server.go index d053fee5e76b..80b85eeebdda 100644 --- a/modules/setting/server.go +++ b/modules/setting/server.go @@ -315,7 +315,7 @@ func loadServerFrom(rootCfg ConfigProvider) { RedirectOtherPort = sec.Key("REDIRECT_OTHER_PORT").MustBool(false) PortToRedirect = sec.Key("PORT_TO_REDIRECT").MustString("80") RedirectorUseProxyProtocol = sec.Key("REDIRECTOR_USE_PROXY_PROTOCOL").MustBool(UseProxyProtocol) - OfflineMode = sec.Key("OFFLINE_MODE").MustBool() + OfflineMode = sec.Key("OFFLINE_MODE").MustBool(true) if len(StaticRootPath) == 0 { StaticRootPath = AppWorkPath } diff --git a/options/locale/locale_ja-JP.ini b/options/locale/locale_ja-JP.ini index c2557b180e7c..871a9d6809e7 100644 --- a/options/locale/locale_ja-JP.ini +++ b/options/locale/locale_ja-JP.ini @@ -91,6 +91,7 @@ remove=除去 remove_all=すべて除去 remove_label_str=アイテム「%s」を削除 edit=編集 +view=表示 enabled=有効 disabled=無効 @@ -3531,6 +3532,9 @@ runs.status=ステータス runs.actors_no_select=すべてのアクター runs.status_no_select=すべてのステータス runs.no_results=一致する結果はありません。 +runs.no_workflows=ワークフローはまだありません。 +runs.no_workflows.quick_start=Gitea Action の始め方がわからない? クイックスタートガイドをご覧ください。 +runs.no_workflows.documentation=Gitea Action の詳細については、ドキュメントを参照してください。 runs.no_runs=ワークフローはまだ実行されていません。 runs.empty_commit_message=(空のコミットメッセージ) diff --git a/routers/api/actions/artifacts_chunks.go b/routers/api/actions/artifacts_chunks.go index c7ab70afa950..36432a0ca084 100644 --- a/routers/api/actions/artifacts_chunks.go +++ b/routers/api/actions/artifacts_chunks.go @@ -26,10 +26,11 @@ func saveUploadChunk(st storage.ObjectStorage, ctx *ArtifactContext, contentRange := ctx.Req.Header.Get("Content-Range") start, end, length := int64(0), int64(0), int64(0) if _, err := fmt.Sscanf(contentRange, "bytes %d-%d/%d", &start, &end, &length); err != nil { + log.Warn("parse content range error: %v, content-range: %s", err, contentRange) return -1, fmt.Errorf("parse content range error: %v", err) } // build chunk store path - storagePath := fmt.Sprintf("tmp%d/%d-%d-%d.chunk", runID, artifact.ID, start, end) + storagePath := fmt.Sprintf("tmp%d/%d-%d-%d-%d.chunk", runID, runID, artifact.ID, start, end) // use io.TeeReader to avoid reading all body to md5 sum. // it writes data to hasher after reading end // if hash is not matched, delete the read-end result @@ -58,6 +59,7 @@ func saveUploadChunk(st storage.ObjectStorage, ctx *ArtifactContext, } type chunkFileItem struct { + RunID int64 ArtifactID int64 Start int64 End int64 @@ -67,9 +69,12 @@ type chunkFileItem struct { func listChunksByRunID(st storage.ObjectStorage, runID int64) (map[int64][]*chunkFileItem, error) { storageDir := fmt.Sprintf("tmp%d", runID) var chunks []*chunkFileItem - if err := st.IterateObjects(storageDir, func(path string, obj storage.Object) error { - item := chunkFileItem{Path: path} - if _, err := fmt.Sscanf(path, filepath.Join(storageDir, "%d-%d-%d.chunk"), &item.ArtifactID, &item.Start, &item.End); err != nil { + if err := st.IterateObjects(storageDir, func(fpath string, obj storage.Object) error { + baseName := filepath.Base(fpath) + // when read chunks from storage, it only contains storage dir and basename, + // no matter the subdirectory setting in storage config + item := chunkFileItem{Path: storageDir + "/" + baseName} + if _, err := fmt.Sscanf(baseName, "%d-%d-%d-%d.chunk", &item.RunID, &item.ArtifactID, &item.Start, &item.End); err != nil { return fmt.Errorf("parse content range error: %v", err) } chunks = append(chunks, &item) diff --git a/routers/api/v1/misc/nodeinfo.go b/routers/api/v1/misc/nodeinfo.go index f0d8d80dd4e1..cc754f64a21a 100644 --- a/routers/api/v1/misc/nodeinfo.go +++ b/routers/api/v1/misc/nodeinfo.go @@ -29,10 +29,9 @@ func NodeInfo(ctx *context.APIContext) { nodeInfoUsage := structs.NodeInfoUsage{} if setting.Federation.ShareUserStatistics { - cached := false - if setting.CacheService.Enabled { - nodeInfoUsage, cached = ctx.Cache.Get(cacheKeyNodeInfoUsage).(structs.NodeInfoUsage) - } + var cached bool + nodeInfoUsage, cached = ctx.Cache.Get(cacheKeyNodeInfoUsage).(structs.NodeInfoUsage) + if !cached { usersTotal := int(user_model.CountUsers(ctx, nil)) now := time.Now() @@ -53,11 +52,10 @@ func NodeInfo(ctx *context.APIContext) { LocalPosts: int(allIssues), LocalComments: int(allComments), } - if setting.CacheService.Enabled { - if err := ctx.Cache.Put(cacheKeyNodeInfoUsage, nodeInfoUsage, 180); err != nil { - ctx.InternalServerError(err) - return - } + + if err := ctx.Cache.Put(cacheKeyNodeInfoUsage, nodeInfoUsage, 180); err != nil { + ctx.InternalServerError(err) + return } } } diff --git a/routers/api/v1/utils/git.go b/routers/api/v1/utils/git.go index dfb1a130c371..39714e343f01 100644 --- a/routers/api/v1/utils/git.go +++ b/routers/api/v1/utils/git.go @@ -73,7 +73,7 @@ func searchRefCommitByType(ctx *context.APIContext, refType, filter string) (str func ConvertToObjectID(ctx gocontext.Context, repo *context.Repository, commitID string) (git.ObjectID, error) { objectFormat, _ := repo.GitRepo.GetObjectFormat() if len(commitID) == objectFormat.FullLength() && objectFormat.IsValid(commitID) { - sha, err := objectFormat.NewIDFromString(commitID) + sha, err := git.NewIDFromString(commitID) if err == nil { return sha, nil } diff --git a/routers/init.go b/routers/init.go index c1cfe26bc4c6..ee98aedb1655 100644 --- a/routers/init.go +++ b/routers/init.go @@ -118,7 +118,7 @@ func InitWebInstalled(ctx context.Context) { mustInit(storage.Init) mailer.NewContext(ctx) - mustInit(cache.NewContext) + mustInit(cache.Init) mustInit(feed_service.Init) mustInit(uinotification.Init) mustInitCtx(ctx, archiver.Init) diff --git a/routers/private/hook_verification.go b/routers/private/hook_verification.go index 8b2d0dd848a9..42b8e5abed81 100644 --- a/routers/private/hook_verification.go +++ b/routers/private/hook_verification.go @@ -83,8 +83,8 @@ func readAndVerifyCommit(sha string, repo *git.Repository, env []string) error { _ = stdoutReader.Close() _ = stdoutWriter.Close() }() - objectFormat, _ := repo.GetObjectFormat() - commitID := objectFormat.MustIDFromString(sha) + + commitID := git.MustIDFromString(sha) return git.NewCommand(repo.Ctx, "cat-file", "commit").AddDynamicArguments(sha). Run(&git.RunOpts{ diff --git a/routers/web/auth/auth.go b/routers/web/auth/auth.go index 0ea91fc759a9..8f37d05fda0e 100644 --- a/routers/web/auth/auth.go +++ b/routers/web/auth/auth.go @@ -622,10 +622,8 @@ func handleUserCreated(ctx *context.Context, u *user_model.User, gothUser *goth. ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale) ctx.HTML(http.StatusOK, TplActivate) - if setting.CacheService.Enabled { - if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { - log.Error("Set cache(MailResendLimit) fail: %v", err) - } + if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { + log.Error("Set cache(MailResendLimit) fail: %v", err) } return false } @@ -645,16 +643,14 @@ func Activate(ctx *context.Context) { } // Resend confirmation email. if setting.Service.RegisterEmailConfirm { - if setting.CacheService.Enabled && ctx.Cache.IsExist("MailResendLimit_"+ctx.Doer.LowerName) { + if ctx.Cache.IsExist("MailResendLimit_" + ctx.Doer.LowerName) { ctx.Data["ResendLimited"] = true } else { ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale) mailer.SendActivateAccountMail(ctx.Locale, ctx.Doer) - if setting.CacheService.Enabled { - if err := ctx.Cache.Put("MailResendLimit_"+ctx.Doer.LowerName, ctx.Doer.LowerName, 180); err != nil { - log.Error("Set cache(MailResendLimit) fail: %v", err) - } + if err := ctx.Cache.Put("MailResendLimit_"+ctx.Doer.LowerName, ctx.Doer.LowerName, 180); err != nil { + log.Error("Set cache(MailResendLimit) fail: %v", err) } } } else { @@ -789,7 +785,7 @@ func ActivateEmail(ctx *context.Context) { if u, err := user_model.GetUserByID(ctx, email.UID); err != nil { log.Warn("GetUserByID: %d", email.UID) - } else if setting.CacheService.Enabled { + } else { // Allow user to validate more emails _ = ctx.Cache.Delete("MailResendLimit_" + u.LowerName) } diff --git a/routers/web/auth/password.go b/routers/web/auth/password.go index bdfa8c40258f..def9c2bcaac2 100644 --- a/routers/web/auth/password.go +++ b/routers/web/auth/password.go @@ -79,7 +79,7 @@ func ForgotPasswdPost(ctx *context.Context) { return } - if setting.CacheService.Enabled && ctx.Cache.IsExist("MailResendLimit_"+u.LowerName) { + if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) { ctx.Data["ResendLimited"] = true ctx.HTML(http.StatusOK, tplForgotPassword) return @@ -87,10 +87,8 @@ func ForgotPasswdPost(ctx *context.Context) { mailer.SendResetPasswordMail(u) - if setting.CacheService.Enabled { - if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { - log.Error("Set cache(MailResendLimit) fail: %v", err) - } + if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { + log.Error("Set cache(MailResendLimit) fail: %v", err) } ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale) diff --git a/routers/web/healthcheck/check.go b/routers/web/healthcheck/check.go index ecb73a928fd6..85f47613f0db 100644 --- a/routers/web/healthcheck/check.go +++ b/routers/web/healthcheck/check.go @@ -121,10 +121,6 @@ func checkDatabase(ctx context.Context, checks checks) status { // cache checks gitea cache status func checkCache(checks checks) status { - if !setting.CacheService.Enabled { - return pass - } - st := componentStatus{} if err := cache.GetCache().Ping(); err != nil { st.Status = fail diff --git a/routers/web/repo/blame.go b/routers/web/repo/blame.go index b2374e32c284..d414779a14ec 100644 --- a/routers/web/repo/blame.go +++ b/routers/web/repo/blame.go @@ -125,7 +125,7 @@ func RefBlame(ctx *context.Context) { } type blameResult struct { - Parts []git.BlamePart + Parts []*git.BlamePart UsesIgnoreRevs bool FaultyIgnoreRevsFile bool } @@ -175,7 +175,9 @@ func performBlame(ctx *context.Context, repoPath string, commit *git.Commit, fil func fillBlameResult(br *git.BlameReader, r *blameResult) error { r.UsesIgnoreRevs = br.UsesIgnoreRevs() - r.Parts = make([]git.BlamePart, 0, 5) + previousHelper := make(map[string]*git.BlamePart) + + r.Parts = make([]*git.BlamePart, 0, 5) for { blamePart, err := br.NextPart() if err != nil { @@ -184,13 +186,23 @@ func fillBlameResult(br *git.BlameReader, r *blameResult) error { if blamePart == nil { break } - r.Parts = append(r.Parts, *blamePart) + + if prev, ok := previousHelper[blamePart.Sha]; ok { + if blamePart.PreviousSha == "" { + blamePart.PreviousSha = prev.PreviousSha + blamePart.PreviousPath = prev.PreviousPath + } + } else { + previousHelper[blamePart.Sha] = blamePart + } + + r.Parts = append(r.Parts, blamePart) } return nil } -func processBlameParts(ctx *context.Context, blameParts []git.BlamePart) map[string]*user_model.UserCommit { +func processBlameParts(ctx *context.Context, blameParts []*git.BlamePart) map[string]*user_model.UserCommit { // store commit data by SHA to look up avatar info etc commitNames := make(map[string]*user_model.UserCommit) // and as blameParts can reference the same commits multiple @@ -232,7 +244,7 @@ func processBlameParts(ctx *context.Context, blameParts []git.BlamePart) map[str return commitNames } -func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames map[string]*user_model.UserCommit) { +func renderBlame(ctx *context.Context, blameParts []*git.BlamePart, commitNames map[string]*user_model.UserCommit) { repoLink := ctx.Repo.RepoLink language := "" diff --git a/routers/web/repo/setting/lfs.go b/routers/web/repo/setting/lfs.go index 230f1a2a608a..edf1298c2073 100644 --- a/routers/web/repo/setting/lfs.go +++ b/routers/web/repo/setting/lfs.go @@ -395,7 +395,7 @@ func LFSFileFind(ctx *context.Context) { objectID = git.ComputeBlobHash(objectFormat, []byte(pointer.StringContent())) sha = objectID.String() } else { - objectID = objectFormat.MustIDFromString(sha) + objectID = git.MustIDFromString(sha) } ctx.Data["LFSFilesLink"] = ctx.Repo.RepoLink + "/settings/lfs" ctx.Data["Oid"] = oid diff --git a/routers/web/user/setting/account.go b/routers/web/user/setting/account.go index 5c14f3ad4b52..6d61d8021cc3 100644 --- a/routers/web/user/setting/account.go +++ b/routers/web/user/setting/account.go @@ -105,7 +105,7 @@ func EmailPost(ctx *context.Context) { // Send activation Email if ctx.FormString("_method") == "SENDACTIVATION" { var address string - if setting.CacheService.Enabled && ctx.Cache.IsExist("MailResendLimit_"+ctx.Doer.LowerName) { + if ctx.Cache.IsExist("MailResendLimit_" + ctx.Doer.LowerName) { log.Error("Send activation: activation still pending") ctx.Redirect(setting.AppSubURL + "/user/settings/account") return @@ -141,11 +141,10 @@ func EmailPost(ctx *context.Context) { } address = email.Email - if setting.CacheService.Enabled { - if err := ctx.Cache.Put("MailResendLimit_"+ctx.Doer.LowerName, ctx.Doer.LowerName, 180); err != nil { - log.Error("Set cache(MailResendLimit) fail: %v", err) - } + if err := ctx.Cache.Put("MailResendLimit_"+ctx.Doer.LowerName, ctx.Doer.LowerName, 180); err != nil { + log.Error("Set cache(MailResendLimit) fail: %v", err) } + ctx.Flash.Info(ctx.Tr("settings.add_email_confirmation_sent", address, timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale))) ctx.Redirect(setting.AppSubURL + "/user/settings/account") return @@ -204,11 +203,10 @@ func EmailPost(ctx *context.Context) { // Send confirmation email if setting.Service.RegisterEmailConfirm { mailer.SendActivateEmailMail(ctx.Doer, email) - if setting.CacheService.Enabled { - if err := ctx.Cache.Put("MailResendLimit_"+ctx.Doer.LowerName, ctx.Doer.LowerName, 180); err != nil { - log.Error("Set cache(MailResendLimit) fail: %v", err) - } + if err := ctx.Cache.Put("MailResendLimit_"+ctx.Doer.LowerName, ctx.Doer.LowerName, 180); err != nil { + log.Error("Set cache(MailResendLimit) fail: %v", err) } + ctx.Flash.Info(ctx.Tr("settings.add_email_confirmation_sent", email.Email, timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale))) } else { ctx.Flash.Success(ctx.Tr("settings.add_email_success")) @@ -276,7 +274,7 @@ func loadAccountData(ctx *context.Context) { user_model.EmailAddress CanBePrimary bool } - pendingActivation := setting.CacheService.Enabled && ctx.Cache.IsExist("MailResendLimit_"+ctx.Doer.LowerName) + pendingActivation := ctx.Cache.IsExist("MailResendLimit_" + ctx.Doer.LowerName) emails := make([]*UserEmail, len(emlist)) for i, em := range emlist { var email UserEmail diff --git a/services/actions/commit_status.go b/services/actions/commit_status.go index c1fc1eda92aa..72a3ab7ac60e 100644 --- a/services/actions/commit_status.go +++ b/services/actions/commit_status.go @@ -115,7 +115,7 @@ func createCommitStatus(ctx context.Context, job *actions_model.ActionRunJob) er } creator := user_model.NewActionsUser() - commitID, err := git.IDFromString(sha) + commitID, err := git.NewIDFromString(sha) if err != nil { return fmt.Errorf("HashTypeInterfaceFromHashString: %w", err) } diff --git a/services/issue/assignee_test.go b/services/issue/assignee_test.go index e16b012a1742..da25da60ee17 100644 --- a/services/issue/assignee_test.go +++ b/services/issue/assignee_test.go @@ -18,8 +18,12 @@ func TestDeleteNotPassedAssignee(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // Fake issue with assignees - issue, err := issues_model.GetIssueWithAttrsByID(db.DefaultContext, 1) + issue, err := issues_model.GetIssueByID(db.DefaultContext, 1) assert.NoError(t, err) + + err = issue.LoadAttributes(db.DefaultContext) + assert.NoError(t, err) + assert.Len(t, issue.Assignees, 1) user1, err := user_model.GetUserByID(db.DefaultContext, 1) // This user is already assigned (see the definition in fixtures), so running UpdateAssignee should unassign him diff --git a/services/pull/patch.go b/services/pull/patch.go index 1dbbec373d16..acaff04bda47 100644 --- a/services/pull/patch.go +++ b/services/pull/patch.go @@ -130,8 +130,6 @@ func (e *errMergeConflict) Error() string { func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, gitRepo *git.Repository) error { log.Trace("Attempt to merge:\n%v", file) - objectFormat, _ := gitRepo.GetObjectFormat() - switch { case file.stage1 != nil && (file.stage2 == nil || file.stage3 == nil): // 1. Deleted in one or both: @@ -148,7 +146,7 @@ func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, g // 2. Added in ours but not in theirs or identical in both // // Not a genuine conflict just add to the index - if err := gitRepo.AddObjectToIndex(file.stage2.mode, objectFormat.MustIDFromString(file.stage2.sha), file.stage2.path); err != nil { + if err := gitRepo.AddObjectToIndex(file.stage2.mode, git.MustIDFromString(file.stage2.sha), file.stage2.path); err != nil { return err } return nil @@ -161,7 +159,7 @@ func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, g // 4. Added in theirs but not ours: // // Not a genuine conflict just add to the index - return gitRepo.AddObjectToIndex(file.stage3.mode, objectFormat.MustIDFromString(file.stage3.sha), file.stage3.path) + return gitRepo.AddObjectToIndex(file.stage3.mode, git.MustIDFromString(file.stage3.sha), file.stage3.path) case file.stage1 == nil: // 5. Created by new in both // @@ -222,7 +220,7 @@ func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, g return err } hash = strings.TrimSpace(hash) - return gitRepo.AddObjectToIndex(file.stage2.mode, objectFormat.MustIDFromString(hash), file.stage2.path) + return gitRepo.AddObjectToIndex(file.stage2.mode, git.MustIDFromString(hash), file.stage2.path) default: if file.stage1 != nil { return &errMergeConflict{file.stage1.path} diff --git a/services/repository/cache.go b/services/repository/cache.go index 91351cbf491a..b0811a99fc03 100644 --- a/services/repository/cache.go +++ b/services/repository/cache.go @@ -9,15 +9,10 @@ import ( repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/cache" "code.gitea.io/gitea/modules/git" - "code.gitea.io/gitea/modules/setting" ) // CacheRef cachhe last commit information of the branch or the tag func CacheRef(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, fullRefName git.RefName) error { - if !setting.CacheService.LastCommit.Enabled { - return nil - } - commit, err := gitRepo.GetCommit(fullRefName.String()) if err != nil { return err diff --git a/templates/code/searchresults.tmpl b/templates/code/searchresults.tmpl index 28c33a26de92..bb21a5e0dcad 100644 --- a/templates/code/searchresults.tmpl +++ b/templates/code/searchresults.tmpl @@ -31,7 +31,7 @@ {{.}} {{end}} - {{.FormattedLines | Safe}} + {{.FormattedLines}} diff --git a/templates/repo/search.tmpl b/templates/repo/search.tmpl index b6c90de32f63..b616b4de3231 100644 --- a/templates/repo/search.tmpl +++ b/templates/repo/search.tmpl @@ -53,7 +53,7 @@ {{.}} {{end}} - {{.FormattedLines | Safe}} + {{.FormattedLines}} diff --git a/tests/integration/api_actions_artifact_test.go b/tests/integration/api_actions_artifact_test.go index 101bedde0278..2597d103746e 100644 --- a/tests/integration/api_actions_artifact_test.go +++ b/tests/integration/api_actions_artifact_test.go @@ -30,8 +30,7 @@ func TestActionsArtifactUploadSingleFile(t *testing.T) { req := NewRequestWithJSON(t, "POST", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts", getUploadArtifactRequest{ Type: "actions_storage", Name: "artifact", - }) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + }).AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp := MakeRequest(t, req, http.StatusOK) var uploadResp uploadArtifactResponse DecodeJSON(t, resp, &uploadResp) @@ -43,18 +42,18 @@ func TestActionsArtifactUploadSingleFile(t *testing.T) { // upload artifact chunk body := strings.Repeat("A", 1024) - req = NewRequestWithBody(t, "PUT", url, strings.NewReader(body)) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") - req.Header.Add("Content-Range", "bytes 0-1023/1024") - req.Header.Add("x-tfs-filelength", "1024") - req.Header.Add("x-actions-results-md5", "1HsSe8LeLWh93ILaw1TEFQ==") // base64(md5(body)) + req = NewRequestWithBody(t, "PUT", url, strings.NewReader(body)). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a"). + SetHeader("Content-Range", "bytes 0-1023/1024"). + SetHeader("x-tfs-filelength", "1024"). + SetHeader("x-actions-results-md5", "1HsSe8LeLWh93ILaw1TEFQ==") // base64(md5(body)) MakeRequest(t, req, http.StatusOK) t.Logf("Create artifact confirm") // confirm artifact upload - req = NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts?artifactName=artifact") - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req = NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts?artifactName=artifact"). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") MakeRequest(t, req, http.StatusOK) } @@ -64,11 +63,11 @@ func TestActionsArtifactUploadInvalidHash(t *testing.T) { // artifact id 54321 not exist url := "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts/8e5b948a454515dbabfc7eb718ddddddd/upload?itemPath=artifact/abc.txt" body := strings.Repeat("A", 1024) - req := NewRequestWithBody(t, "PUT", url, strings.NewReader(body)) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") - req.Header.Add("Content-Range", "bytes 0-1023/1024") - req.Header.Add("x-tfs-filelength", "1024") - req.Header.Add("x-actions-results-md5", "1HsSe8LeLWh93ILaw1TEFQ==") // base64(md5(body)) + req := NewRequestWithBody(t, "PUT", url, strings.NewReader(body)). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a"). + SetHeader("Content-Range", "bytes 0-1023/1024"). + SetHeader("x-tfs-filelength", "1024"). + SetHeader("x-actions-results-md5", "1HsSe8LeLWh93ILaw1TEFQ==") // base64(md5(body)) resp := MakeRequest(t, req, http.StatusBadRequest) assert.Contains(t, resp.Body.String(), "Invalid artifact hash") } @@ -76,8 +75,8 @@ func TestActionsArtifactUploadInvalidHash(t *testing.T) { func TestActionsArtifactConfirmUploadWithoutName(t *testing.T) { defer tests.PrepareTestEnv(t)() - req := NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts") - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req := NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts"). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp := MakeRequest(t, req, http.StatusBadRequest) assert.Contains(t, resp.Body.String(), "artifact name is empty") } @@ -111,8 +110,8 @@ type ( func TestActionsArtifactDownload(t *testing.T) { defer tests.PrepareTestEnv(t)() - req := NewRequest(t, "GET", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts") - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req := NewRequest(t, "GET", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts"). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp := MakeRequest(t, req, http.StatusOK) var listResp listArtifactsResponse DecodeJSON(t, resp, &listResp) @@ -122,8 +121,8 @@ func TestActionsArtifactDownload(t *testing.T) { idx := strings.Index(listResp.Value[0].FileContainerResourceURL, "/api/actions_pipeline/_apis/pipelines/") url := listResp.Value[0].FileContainerResourceURL[idx+1:] + "?itemPath=artifact" - req = NewRequest(t, "GET", url) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req = NewRequest(t, "GET", url). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp = MakeRequest(t, req, http.StatusOK) var downloadResp downloadArtifactResponse DecodeJSON(t, resp, &downloadResp) @@ -134,8 +133,8 @@ func TestActionsArtifactDownload(t *testing.T) { idx = strings.Index(downloadResp.Value[0].ContentLocation, "/api/actions_pipeline/_apis/pipelines/") url = downloadResp.Value[0].ContentLocation[idx:] - req = NewRequest(t, "GET", url) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req = NewRequest(t, "GET", url). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp = MakeRequest(t, req, http.StatusOK) body := strings.Repeat("A", 1024) assert.Equal(t, resp.Body.String(), body) @@ -150,8 +149,7 @@ func TestActionsArtifactUploadMultipleFile(t *testing.T) { req := NewRequestWithJSON(t, "POST", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts", getUploadArtifactRequest{ Type: "actions_storage", Name: testArtifactName, - }) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + }).AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp := MakeRequest(t, req, http.StatusOK) var uploadResp uploadArtifactResponse DecodeJSON(t, resp, &uploadResp) @@ -182,19 +180,19 @@ func TestActionsArtifactUploadMultipleFile(t *testing.T) { url := uploadResp.FileContainerResourceURL[idx:] + "?itemPath=" + testArtifactName + "/" + f.Path // upload artifact chunk - req = NewRequestWithBody(t, "PUT", url, strings.NewReader(f.Content)) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") - req.Header.Add("Content-Range", "bytes 0-1023/1024") - req.Header.Add("x-tfs-filelength", "1024") - req.Header.Add("x-actions-results-md5", f.MD5) // base64(md5(body)) + req = NewRequestWithBody(t, "PUT", url, strings.NewReader(f.Content)). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a"). + SetHeader("Content-Range", "bytes 0-1023/1024"). + SetHeader("x-tfs-filelength", "1024"). + SetHeader("x-actions-results-md5", f.MD5) // base64(md5(body)) MakeRequest(t, req, http.StatusOK) } t.Logf("Create artifact confirm") // confirm artifact upload - req = NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts?artifactName="+testArtifactName) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req = NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts?artifactName="+testArtifactName). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") MakeRequest(t, req, http.StatusOK) } @@ -203,8 +201,8 @@ func TestActionsArtifactDownloadMultiFiles(t *testing.T) { const testArtifactName = "multi-files" - req := NewRequest(t, "GET", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts") - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req := NewRequest(t, "GET", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts"). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp := MakeRequest(t, req, http.StatusOK) var listResp listArtifactsResponse DecodeJSON(t, resp, &listResp) @@ -221,8 +219,8 @@ func TestActionsArtifactDownloadMultiFiles(t *testing.T) { idx := strings.Index(fileContainerResourceURL, "/api/actions_pipeline/_apis/pipelines/") url := fileContainerResourceURL[idx+1:] + "?itemPath=" + testArtifactName - req = NewRequest(t, "GET", url) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req = NewRequest(t, "GET", url). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp = MakeRequest(t, req, http.StatusOK) var downloadResp downloadArtifactResponse DecodeJSON(t, resp, &downloadResp) @@ -246,8 +244,8 @@ func TestActionsArtifactDownloadMultiFiles(t *testing.T) { idx = strings.Index(value.ContentLocation, "/api/actions_pipeline/_apis/pipelines/") url = value.ContentLocation[idx:] - req = NewRequest(t, "GET", url) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req = NewRequest(t, "GET", url). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp = MakeRequest(t, req, http.StatusOK) body := strings.Repeat(bodyChar, 1024) assert.Equal(t, resp.Body.String(), body) @@ -262,8 +260,7 @@ func TestActionsArtifactUploadWithRetentionDays(t *testing.T) { Type: "actions_storage", Name: "artifact-retention-days", RetentionDays: 9, - }) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + }).AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp := MakeRequest(t, req, http.StatusOK) var uploadResp uploadArtifactResponse DecodeJSON(t, resp, &uploadResp) @@ -276,17 +273,17 @@ func TestActionsArtifactUploadWithRetentionDays(t *testing.T) { // upload artifact chunk body := strings.Repeat("A", 1024) - req = NewRequestWithBody(t, "PUT", url, strings.NewReader(body)) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") - req.Header.Add("Content-Range", "bytes 0-1023/1024") - req.Header.Add("x-tfs-filelength", "1024") - req.Header.Add("x-actions-results-md5", "1HsSe8LeLWh93ILaw1TEFQ==") // base64(md5(body)) + req = NewRequestWithBody(t, "PUT", url, strings.NewReader(body)). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a"). + SetHeader("Content-Range", "bytes 0-1023/1024"). + SetHeader("x-tfs-filelength", "1024"). + SetHeader("x-actions-results-md5", "1HsSe8LeLWh93ILaw1TEFQ==") // base64(md5(body)) MakeRequest(t, req, http.StatusOK) t.Logf("Create artifact confirm") // confirm artifact upload - req = NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts?artifactName=artifact-retention-days") - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req = NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts?artifactName=artifact-retention-days"). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") MakeRequest(t, req, http.StatusOK) } diff --git a/tests/integration/api_activitypub_person_test.go b/tests/integration/api_activitypub_person_test.go index 3222dfc80713..42a2a0907276 100644 --- a/tests/integration/api_activitypub_person_test.go +++ b/tests/integration/api_activitypub_person_test.go @@ -32,7 +32,7 @@ func TestActivityPubPerson(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { userID := 2 username := "user2" - req := NewRequestf(t, "GET", fmt.Sprintf("/api/v1/activitypub/user-id/%v", userID)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/activitypub/user-id/%v", userID)) resp := MakeRequest(t, req, http.StatusOK) body := resp.Body.Bytes() assert.Contains(t, string(body), "@context") @@ -68,7 +68,7 @@ func TestActivityPubMissingPerson(t *testing.T) { }() onGiteaRun(t, func(*testing.T, *url.URL) { - req := NewRequestf(t, "GET", "/api/v1/activitypub/user-id/999999999") + req := NewRequest(t, "GET", "/api/v1/activitypub/user-id/999999999") resp := MakeRequest(t, req, http.StatusNotFound) assert.Contains(t, resp.Body.String(), "user does not exist") }) diff --git a/tests/integration/api_admin_org_test.go b/tests/integration/api_admin_org_test.go index 0bf4b1f7cba0..a29d0ba1d746 100644 --- a/tests/integration/api_admin_org_test.go +++ b/tests/integration/api_admin_org_test.go @@ -31,7 +31,8 @@ func TestAPIAdminOrgCreate(t *testing.T) { Location: "Shanghai", Visibility: "private", } - req := NewRequestWithJSON(t, "POST", "/api/v1/admin/users/user2/orgs?token="+token, &org) + req := NewRequestWithJSON(t, "POST", "/api/v1/admin/users/user2/orgs", &org). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var apiOrg api.Organization @@ -65,7 +66,8 @@ func TestAPIAdminOrgCreateBadVisibility(t *testing.T) { Location: "Shanghai", Visibility: "notvalid", } - req := NewRequestWithJSON(t, "POST", "/api/v1/admin/users/user2/orgs?token="+token, &org) + req := NewRequestWithJSON(t, "POST", "/api/v1/admin/users/user2/orgs", &org). + AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) }) } @@ -83,6 +85,7 @@ func TestAPIAdminOrgCreateNotAdmin(t *testing.T) { Location: "Shanghai", Visibility: "public", } - req := NewRequestWithJSON(t, "POST", "/api/v1/admin/users/user2/orgs?token="+token, &org) + req := NewRequestWithJSON(t, "POST", "/api/v1/admin/users/user2/orgs", &org). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) } diff --git a/tests/integration/api_admin_test.go b/tests/integration/api_admin_test.go index aae9ec4a24a2..ff7c2ddca39b 100644 --- a/tests/integration/api_admin_test.go +++ b/tests/integration/api_admin_test.go @@ -27,11 +27,11 @@ func TestAPIAdminCreateAndDeleteSSHKey(t *testing.T) { keyOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user2"}) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteAdmin) - urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys?token=%s", keyOwner.Name, token) + urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys", keyOwner.Name) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n", "title": "test-key", - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var newPublicKey api.PublicKey @@ -43,8 +43,8 @@ func TestAPIAdminCreateAndDeleteSSHKey(t *testing.T) { OwnerID: keyOwner.ID, }) - req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d?token=%s", - keyOwner.Name, newPublicKey.ID, token) + req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d", keyOwner.Name, newPublicKey.ID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &asymkey_model.PublicKey{ID: newPublicKey.ID}) } @@ -54,7 +54,8 @@ func TestAPIAdminDeleteMissingSSHKey(t *testing.T) { // user1 is an admin user token := getUserToken(t, "user1", auth_model.AccessTokenScopeWriteAdmin) - req := NewRequestf(t, "DELETE", "/api/v1/admin/users/user1/keys/%d?token=%s", unittest.NonexistentID, token) + req := NewRequestf(t, "DELETE", "/api/v1/admin/users/user1/keys/%d", unittest.NonexistentID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) } @@ -64,18 +65,18 @@ func TestAPIAdminDeleteUnauthorizedKey(t *testing.T) { normalUsername := "user2" token := getUserToken(t, adminUsername, auth_model.AccessTokenScopeWriteAdmin) - urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys?token=%s", adminUsername, token) + urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys", adminUsername) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n", "title": "test-key", - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var newPublicKey api.PublicKey DecodeJSON(t, resp, &newPublicKey) token = getUserToken(t, normalUsername) - req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d?token=%s", - adminUsername, newPublicKey.ID, token) + req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d", adminUsername, newPublicKey.ID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) } @@ -85,8 +86,8 @@ func TestAPISudoUser(t *testing.T) { normalUsername := "user2" token := getUserToken(t, adminUsername, auth_model.AccessTokenScopeReadUser) - urlStr := fmt.Sprintf("/api/v1/user?sudo=%s&token=%s", normalUsername, token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user?sudo=%s", normalUsername)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var user api.User DecodeJSON(t, resp, &user) @@ -100,8 +101,8 @@ func TestAPISudoUserForbidden(t *testing.T) { normalUsername := "user2" token := getUserToken(t, normalUsername, auth_model.AccessTokenScopeReadAdmin) - urlStr := fmt.Sprintf("/api/v1/user?sudo=%s&token=%s", adminUsername, token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user?sudo=%s", adminUsername)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) } @@ -110,8 +111,8 @@ func TestAPIListUsers(t *testing.T) { adminUsername := "user1" token := getUserToken(t, adminUsername, auth_model.AccessTokenScopeReadAdmin) - urlStr := fmt.Sprintf("/api/v1/admin/users?token=%s", token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", "/api/v1/admin/users"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var users []api.User DecodeJSON(t, resp, &users) @@ -137,7 +138,8 @@ func TestAPIListUsersNonAdmin(t *testing.T) { defer tests.PrepareTestEnv(t)() nonAdminUsername := "user2" token := getUserToken(t, nonAdminUsername) - req := NewRequestf(t, "GET", "/api/v1/admin/users?token=%s", token) + req := NewRequest(t, "GET", "/api/v1/admin/users"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) } @@ -145,8 +147,7 @@ func TestAPICreateUserInvalidEmail(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" token := getUserToken(t, adminUsername, auth_model.AccessTokenScopeWriteAdmin) - urlStr := fmt.Sprintf("/api/v1/admin/users?token=%s", token) - req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ + req := NewRequestWithValues(t, "POST", "/api/v1/admin/users", map[string]string{ "email": "invalid_email@domain.com\r\n", "full_name": "invalid user", "login_name": "invalidUser", @@ -155,7 +156,7 @@ func TestAPICreateUserInvalidEmail(t *testing.T) { "send_notify": "true", "source_id": "0", "username": "invalidUser", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) } @@ -167,7 +168,7 @@ func TestAPICreateAndDeleteUser(t *testing.T) { req := NewRequestWithValues( t, "POST", - fmt.Sprintf("/api/v1/admin/users?token=%s", token), + "/api/v1/admin/users", map[string]string{ "email": "deleteme@domain.com", "full_name": "delete me", @@ -178,10 +179,11 @@ func TestAPICreateAndDeleteUser(t *testing.T) { "source_id": "0", "username": "deleteme", }, - ) + ).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) - req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/admin/users/deleteme?token=%s", token)) + req = NewRequest(t, "DELETE", "/api/v1/admin/users/deleteme"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) } @@ -189,7 +191,7 @@ func TestAPIEditUser(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" token := getUserToken(t, adminUsername, auth_model.AccessTokenScopeWriteAdmin) - urlStr := fmt.Sprintf("/api/v1/admin/users/%s?token=%s", "user2", token) + urlStr := fmt.Sprintf("/api/v1/admin/users/%s", "user2") req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ // required @@ -197,7 +199,7 @@ func TestAPIEditUser(t *testing.T) { "source_id": "0", // to change "full_name": "Full Name User 2", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) empty := "" @@ -205,7 +207,7 @@ func TestAPIEditUser(t *testing.T) { LoginName: "user2", SourceID: 0, Email: &empty, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusUnprocessableEntity) errMap := make(map[string]any) @@ -221,7 +223,7 @@ func TestAPIEditUser(t *testing.T) { SourceID: 0, // to change Restricted: &bTrue, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) user2 = unittest.AssertExistsAndLoadBean(t, &user_model.User{LoginName: "user2"}) assert.True(t, user2.IsRestricted) @@ -235,11 +237,11 @@ func TestAPICreateRepoForUser(t *testing.T) { req := NewRequestWithJSON( t, "POST", - fmt.Sprintf("/api/v1/admin/users/%s/repos?token=%s", adminUsername, token), + fmt.Sprintf("/api/v1/admin/users/%s/repos", adminUsername), &api.CreateRepoOption{ Name: "admincreatedrepo", }, - ) + ).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) } @@ -247,40 +249,38 @@ func TestAPIRenameUser(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" token := getUserToken(t, adminUsername, auth_model.AccessTokenScopeWriteAdmin) - urlStr := fmt.Sprintf("/api/v1/admin/users/%s/rename?token=%s", "user2", token) + urlStr := fmt.Sprintf("/api/v1/admin/users/%s/rename", "user2") req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ // required "new_name": "User2", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) - urlStr = fmt.Sprintf("/api/v1/admin/users/%s/rename?token=%s", "User2", token) + urlStr = fmt.Sprintf("/api/v1/admin/users/%s/rename", "User2") req = NewRequestWithValues(t, "POST", urlStr, map[string]string{ // required "new_name": "User2-2-2", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) - urlStr = fmt.Sprintf("/api/v1/admin/users/%s/rename?token=%s", "User2", token) req = NewRequestWithValues(t, "POST", urlStr, map[string]string{ // required "new_name": "user1", - }) + }).AddTokenAuth(token) // the old user name still be used by with a redirect MakeRequest(t, req, http.StatusTemporaryRedirect) - urlStr = fmt.Sprintf("/api/v1/admin/users/%s/rename?token=%s", "User2-2-2", token) + urlStr = fmt.Sprintf("/api/v1/admin/users/%s/rename", "User2-2-2") req = NewRequestWithValues(t, "POST", urlStr, map[string]string{ // required "new_name": "user1", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) - urlStr = fmt.Sprintf("/api/v1/admin/users/%s/rename?token=%s", "User2-2-2", token) req = NewRequestWithValues(t, "POST", urlStr, map[string]string{ // required "new_name": "user2", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) } @@ -294,8 +294,9 @@ func TestAPICron(t *testing.T) { defer tests.PrintCurrentTest(t)() token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadAdmin) - urlStr := fmt.Sprintf("/api/v1/admin/cron?token=%s", token) - req := NewRequest(t, "GET", urlStr) + + req := NewRequest(t, "GET", "/api/v1/admin/cron"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "28", resp.Header().Get("X-Total-Count")) @@ -313,13 +314,13 @@ func TestAPICron(t *testing.T) { // Archive cleanup is harmless, because in the test environment there are none // and is thus an NOOP operation and therefore doesn't interfere with any other // tests. - urlStr := fmt.Sprintf("/api/v1/admin/cron/archive_cleanup?token=%s", token) - req := NewRequest(t, "POST", urlStr) + req := NewRequest(t, "POST", "/api/v1/admin/cron/archive_cleanup"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Check for the latest run time for this cron, to ensure it has been run. - urlStr = fmt.Sprintf("/api/v1/admin/cron?token=%s", token) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", "/api/v1/admin/cron"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var crons []api.Cron diff --git a/tests/integration/api_branch_test.go b/tests/integration/api_branch_test.go index bc026c117f66..28e690b35689 100644 --- a/tests/integration/api_branch_test.go +++ b/tests/integration/api_branch_test.go @@ -17,7 +17,8 @@ import ( func testAPIGetBranch(t *testing.T, branchName string, exists bool) { token := getUserToken(t, "user2", auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branches/%s?token=%s", branchName, token) + req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branches/%s", branchName). + AddTokenAuth(token) resp := MakeRequest(t, req, NoExpectedStatus) if !exists { assert.EqualValues(t, http.StatusNotFound, resp.Code) @@ -33,7 +34,8 @@ func testAPIGetBranch(t *testing.T, branchName string, exists bool) { func testAPIGetBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) *api.BranchProtection { token := getUserToken(t, "user2", auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branch_protections/%s?token=%s", branchName, token) + req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branch_protections/%s", branchName). + AddTokenAuth(token) resp := MakeRequest(t, req, expectedHTTPStatus) if resp.Code == http.StatusOK { @@ -47,9 +49,9 @@ func testAPIGetBranchProtection(t *testing.T, branchName string, expectedHTTPSta func testAPICreateBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/branch_protections?token="+token, &api.BranchProtection{ + req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/branch_protections", &api.BranchProtection{ RuleName: branchName, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, expectedHTTPStatus) if resp.Code == http.StatusCreated { @@ -61,7 +63,8 @@ func testAPICreateBranchProtection(t *testing.T, branchName string, expectedHTTP func testAPIEditBranchProtection(t *testing.T, branchName string, body *api.BranchProtection, expectedHTTPStatus int) { token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, "PATCH", "/api/v1/repos/user2/repo1/branch_protections/"+branchName+"?token="+token, body) + req := NewRequestWithJSON(t, "PATCH", "/api/v1/repos/user2/repo1/branch_protections/"+branchName, body). + AddTokenAuth(token) resp := MakeRequest(t, req, expectedHTTPStatus) if resp.Code == http.StatusOK { @@ -73,13 +76,15 @@ func testAPIEditBranchProtection(t *testing.T, branchName string, body *api.Bran func testAPIDeleteBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteRepository) - req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branch_protections/%s?token=%s", branchName, token) + req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branch_protections/%s", branchName). + AddTokenAuth(token) MakeRequest(t, req, expectedHTTPStatus) } func testAPIDeleteBranch(t *testing.T, branchName string, expectedHTTPStatus int) { token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteRepository) - req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branches/%s?token=%s", branchName, token) + req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branches/%s", branchName). + AddTokenAuth(token) MakeRequest(t, req, expectedHTTPStatus) } @@ -152,10 +157,10 @@ func testAPICreateBranches(t *testing.T, giteaURL *url.URL) { func testAPICreateBranch(t testing.TB, session *TestSession, user, repo, oldBranch, newBranch string, status int) bool { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, "POST", "/api/v1/repos/"+user+"/"+repo+"/branches?token="+token, &api.CreateBranchRepoOption{ + req := NewRequestWithJSON(t, "POST", "/api/v1/repos/"+user+"/"+repo+"/branches", &api.CreateBranchRepoOption{ BranchName: newBranch, OldBranchName: oldBranch, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, status) var branch api.Branch diff --git a/tests/integration/api_comment_attachment_test.go b/tests/integration/api_comment_attachment_test.go index 95a7a81eb404..e5e62a86b7be 100644 --- a/tests/integration/api_comment_attachment_test.go +++ b/tests/integration/api_comment_attachment_test.go @@ -39,15 +39,18 @@ func TestAPIGetCommentAttachment(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeWriteIssue) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d/assets/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, attachment.ID, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d/assets/%d", repoOwner.Name, repo.Name, comment.ID, attachment.ID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) }) session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadIssue) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d/assets/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, attachment.ID, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d/assets/%d", repoOwner.Name, repo.Name, comment.ID, attachment.ID). + AddTokenAuth(token) session.MakeRequest(t, req, http.StatusOK) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d/assets/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, attachment.ID, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d/assets/%d", repoOwner.Name, repo.Name, comment.ID, attachment.ID). + AddTokenAuth(token) resp := session.MakeRequest(t, req, http.StatusOK) var apiAttachment api.Attachment @@ -71,8 +74,8 @@ func TestAPIListCommentAttachments(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadIssue) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d/assets?token=%s", - repoOwner.Name, repo.Name, comment.ID, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d/assets", repoOwner.Name, repo.Name, comment.ID). + AddTokenAuth(token) resp := session.MakeRequest(t, req, http.StatusOK) var apiAttachments []*api.Attachment @@ -93,8 +96,6 @@ func TestAPICreateCommentAttachment(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/assets?token=%s", - repoOwner.Name, repo.Name, comment.ID, token) filename := "image.png" buff := generateImg() @@ -109,8 +110,9 @@ func TestAPICreateCommentAttachment(t *testing.T) { err = writer.Close() assert.NoError(t, err) - req := NewRequestWithBody(t, "POST", urlStr, body) - req.Header.Add("Content-Type", writer.FormDataContentType()) + req := NewRequestWithBody(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/assets", repoOwner.Name, repo.Name, comment.ID), body). + AddTokenAuth(token). + SetHeader("Content-Type", writer.FormDataContentType()) resp := session.MakeRequest(t, req, http.StatusCreated) apiAttachment := new(api.Attachment) @@ -132,11 +134,11 @@ func TestAPIEditCommentAttachment(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/assets/%d?token=%s", - repoOwner.Name, repo.Name, comment.ID, attachment.ID, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/assets/%d", + repoOwner.Name, repo.Name, comment.ID, attachment.ID) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ "name": newAttachmentName, - }) + }).AddTokenAuth(token) resp := session.MakeRequest(t, req, http.StatusCreated) apiAttachment := new(api.Attachment) DecodeJSON(t, resp, &apiAttachment) @@ -155,10 +157,9 @@ func TestAPIDeleteCommentAttachment(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/assets/%d?token=%s", - repoOwner.Name, repo.Name, comment.ID, attachment.ID, token) - req := NewRequestf(t, "DELETE", urlStr) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/assets/%d", repoOwner.Name, repo.Name, comment.ID, attachment.ID)). + AddTokenAuth(token) session.MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &repo_model.Attachment{ID: attachment.ID, CommentID: comment.ID}) diff --git a/tests/integration/api_comment_test.go b/tests/integration/api_comment_test.go index fe272cf92693..a9c5228a16c1 100644 --- a/tests/integration/api_comment_test.go +++ b/tests/integration/api_comment_test.go @@ -77,8 +77,8 @@ func TestAPIListIssueComments(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeReadIssue) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/comments?token=%s", - repoOwner.Name, repo.Name, issue.Index, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/comments", repoOwner.Name, repo.Name, issue.Index). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var comments []*api.Comment @@ -97,11 +97,11 @@ func TestAPICreateComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/comments?token=%s", - repoOwner.Name, repo.Name, issue.Index, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/comments", + repoOwner.Name, repo.Name, issue.Index) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "body": commentBody, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var updatedComment api.Comment @@ -121,7 +121,8 @@ func TestAPIGetComment(t *testing.T) { token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeReadIssue) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d", repoOwner.Name, repo.Name, comment.ID) MakeRequest(t, req, http.StatusOK) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d", repoOwner.Name, repo.Name, comment.ID). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiComment api.Comment @@ -188,20 +189,20 @@ func TestAPIEditComment(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d?token=%s", - repoOwner.Name, repo.Name, comment.ID, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d", + repoOwner.Name, repo.Name, comment.ID) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ "body": newCommentBody, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) }) token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d?token=%s", - repoOwner.Name, repo.Name, comment.ID, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d", + repoOwner.Name, repo.Name, comment.ID) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ "body": newCommentBody, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var updatedComment api.Comment @@ -225,14 +226,14 @@ func TestAPIDeleteComment(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeWriteIssue) - req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", - repoOwner.Name, repo.Name, comment.ID, token) + req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/comments/%d", repoOwner.Name, repo.Name, comment.ID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) }) token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeWriteIssue) - req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", - repoOwner.Name, repo.Name, comment.ID, token) + req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/comments/%d", repoOwner.Name, repo.Name, comment.ID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &issues_model.Comment{ID: comment.ID}) @@ -247,8 +248,7 @@ func TestAPIListIssueTimeline(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) // make request - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/timeline", - repoOwner.Name, repo.Name, issue.Index) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/timeline", repoOwner.Name, repo.Name, issue.Index) resp := MakeRequest(t, req, http.StatusOK) // check if lens of list returned by API and diff --git a/tests/integration/api_gpg_keys_test.go b/tests/integration/api_gpg_keys_test.go index a4545bd0bbd5..ec0dafc2d6dd 100644 --- a/tests/integration/api_gpg_keys_test.go +++ b/tests/integration/api_gpg_keys_test.go @@ -16,7 +16,7 @@ import ( "github.com/stretchr/testify/assert" ) -type makeRequestFunc func(testing.TB, *http.Request, int) *httptest.ResponseRecorder +type makeRequestFunc func(testing.TB, *RequestWrapper, int) *httptest.ResponseRecorder func TestGPGKeys(t *testing.T) { defer tests.PrepareTestEnv(t)() @@ -79,7 +79,8 @@ func TestGPGKeys(t *testing.T) { t.Run("CheckState", func(t *testing.T) { var keys []*api.GPGKey - req := NewRequest(t, "GET", "/api/v1/user/gpg_keys?token="+tokenWithGPGKeyScope) // GET all keys + req := NewRequest(t, "GET", "/api/v1/user/gpg_keys"). // GET all keys + AddTokenAuth(tokenWithGPGKeyScope) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &keys) assert.Len(t, keys, 1) @@ -95,7 +96,8 @@ func TestGPGKeys(t *testing.T) { assert.Empty(t, subKey.Emails) var key api.GPGKey - req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey1.ID, 10)+"?token="+tokenWithGPGKeyScope) // Primary key 1 + req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey1.ID, 10)). // Primary key 1 + AddTokenAuth(tokenWithGPGKeyScope) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &key) assert.EqualValues(t, "38EA3BCED732982C", key.KeyID) @@ -103,7 +105,8 @@ func TestGPGKeys(t *testing.T) { assert.EqualValues(t, "user2@example.com", key.Emails[0].Email) assert.True(t, key.Emails[0].Verified) - req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(subKey.ID, 10)+"?token="+tokenWithGPGKeyScope) // Subkey of 38EA3BCED732982C + req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(subKey.ID, 10)). // Subkey of 38EA3BCED732982C + AddTokenAuth(tokenWithGPGKeyScope) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &key) assert.EqualValues(t, "70D7C694D17D03AD", key.KeyID) @@ -114,7 +117,8 @@ func TestGPGKeys(t *testing.T) { t.Run("CheckCommits", func(t *testing.T) { t.Run("NotSigned", func(t *testing.T) { var branch api.Branch - req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/not-signed?token="+token) + req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/not-signed"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &branch) assert.False(t, branch.Commit.Verification.Verified) @@ -122,7 +126,8 @@ func TestGPGKeys(t *testing.T) { t.Run("SignedWithNotValidatedEmail", func(t *testing.T) { var branch api.Branch - req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/good-sign-not-yet-validated?token="+token) + req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/good-sign-not-yet-validated"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &branch) assert.False(t, branch.Commit.Verification.Verified) @@ -130,7 +135,8 @@ func TestGPGKeys(t *testing.T) { t.Run("SignedWithValidEmail", func(t *testing.T) { var branch api.Branch - req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/good-sign?token="+token) + req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/good-sign"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &branch) assert.True(t, branch.Commit.Verification.Verified) @@ -139,29 +145,33 @@ func TestGPGKeys(t *testing.T) { } func testViewOwnGPGKeys(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { - req := NewRequest(t, "GET", "/api/v1/user/gpg_keys?token="+token) + req := NewRequest(t, "GET", "/api/v1/user/gpg_keys"). + AddTokenAuth(token) makeRequest(t, req, expected) } func testViewGPGKeys(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { - req := NewRequest(t, "GET", "/api/v1/users/user2/gpg_keys?token="+token) + req := NewRequest(t, "GET", "/api/v1/users/user2/gpg_keys"). + AddTokenAuth(token) makeRequest(t, req, expected) } func testGetGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { - req := NewRequest(t, "GET", "/api/v1/user/gpg_keys/1?token="+token) + req := NewRequest(t, "GET", "/api/v1/user/gpg_keys/1"). + AddTokenAuth(token) makeRequest(t, req, expected) } func testDeleteGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { - req := NewRequest(t, "DELETE", "/api/v1/user/gpg_keys/1?token="+token) + req := NewRequest(t, "DELETE", "/api/v1/user/gpg_keys/1"). + AddTokenAuth(token) makeRequest(t, req, expected) } func testCreateGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int, publicKey string) { - req := NewRequestWithJSON(t, "POST", "/api/v1/user/gpg_keys?token="+token, api.CreateGPGKeyOption{ + req := NewRequestWithJSON(t, "POST", "/api/v1/user/gpg_keys", api.CreateGPGKeyOption{ ArmoredKey: publicKey, - }) + }).AddTokenAuth(token) makeRequest(t, req, expected) } diff --git a/tests/integration/api_helper_for_declarative_test.go b/tests/integration/api_helper_for_declarative_test.go index 3524ce9834ad..7755b9861ae3 100644 --- a/tests/integration/api_helper_for_declarative_test.go +++ b/tests/integration/api_helper_for_declarative_test.go @@ -59,7 +59,8 @@ func doAPICreateRepository(ctx APITestContext, empty bool, callback ...func(*tes License: "WTFPL", Readme: "Default", } - req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos?token="+ctx.Token, createRepoOption) + req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos", createRepoOption). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -76,7 +77,8 @@ func doAPICreateRepository(ctx APITestContext, empty bool, callback ...func(*tes func doAPIEditRepository(ctx APITestContext, editRepoOption *api.EditRepoOption, callback ...func(*testing.T, api.Repository)) func(*testing.T) { return func(t *testing.T) { - req := NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), ctx.Token), editRepoOption) + req := NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame)), editRepoOption). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -103,7 +105,8 @@ func doAPIAddCollaborator(ctx APITestContext, username string, mode perm.AccessM addCollaboratorOption := &api.AddCollaboratorOption{ Permission: &permission, } - req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/collaborators/%s?token=%s", ctx.Username, ctx.Reponame, username, ctx.Token), addCollaboratorOption) + req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/collaborators/%s", ctx.Username, ctx.Reponame, username), addCollaboratorOption). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -115,7 +118,8 @@ func doAPIAddCollaborator(ctx APITestContext, username string, mode perm.AccessM func doAPIForkRepository(ctx APITestContext, username string, callback ...func(*testing.T, api.Repository)) func(*testing.T) { return func(t *testing.T) { createForkOption := &api.CreateForkOption{} - req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/forks?token=%s", username, ctx.Reponame, ctx.Token), createForkOption) + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/forks", username, ctx.Reponame), createForkOption). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -131,9 +135,8 @@ func doAPIForkRepository(ctx APITestContext, username string, callback ...func(* func doAPIGetRepository(ctx APITestContext, callback ...func(*testing.T, api.Repository)) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", ctx.Username, ctx.Reponame, ctx.Token) - - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s", ctx.Username, ctx.Reponame)). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -150,9 +153,8 @@ func doAPIGetRepository(ctx APITestContext, callback ...func(*testing.T, api.Rep func doAPIDeleteRepository(ctx APITestContext) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", ctx.Username, ctx.Reponame, ctx.Token) - - req := NewRequest(t, "DELETE", urlStr) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s", ctx.Username, ctx.Reponame)). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -163,14 +165,12 @@ func doAPIDeleteRepository(ctx APITestContext) func(*testing.T) { func doAPICreateUserKey(ctx APITestContext, keyname, keyFile string, callback ...func(*testing.T, api.PublicKey)) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/user/keys?token=%s", ctx.Token) - dataPubKey, err := os.ReadFile(keyFile + ".pub") assert.NoError(t, err) - req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateKeyOption{ + req := NewRequestWithJSON(t, "POST", "/api/v1/user/keys", &api.CreateKeyOption{ Title: keyname, Key: string(dataPubKey), - }) + }).AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -186,9 +186,8 @@ func doAPICreateUserKey(ctx APITestContext, keyname, keyFile string, callback .. func doAPIDeleteUserKey(ctx APITestContext, keyID int64) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/user/keys/%d?token=%s", keyID, ctx.Token) - - req := NewRequest(t, "DELETE", urlStr) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/keys/%d", keyID)). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -199,15 +198,13 @@ func doAPIDeleteUserKey(ctx APITestContext, keyID int64) func(*testing.T) { func doAPICreateDeployKey(ctx APITestContext, keyname, keyFile string, readOnly bool) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", ctx.Username, ctx.Reponame, ctx.Token) - dataPubKey, err := os.ReadFile(keyFile + ".pub") assert.NoError(t, err) - req := NewRequestWithJSON(t, "POST", urlStr, api.CreateKeyOption{ + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/keys", ctx.Username, ctx.Reponame), api.CreateKeyOption{ Title: keyname, Key: string(dataPubKey), ReadOnly: readOnly, - }) + }).AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) @@ -219,13 +216,11 @@ func doAPICreateDeployKey(ctx APITestContext, keyname, keyFile string, readOnly func doAPICreatePullRequest(ctx APITestContext, owner, repo, baseBranch, headBranch string) func(*testing.T) (api.PullRequest, error) { return func(t *testing.T) (api.PullRequest, error) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", - owner, repo, ctx.Token) - req := NewRequestWithJSON(t, http.MethodPost, urlStr, &api.CreatePullRequestOption{ + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", owner, repo), &api.CreatePullRequestOption{ Head: headBranch, Base: baseBranch, Title: fmt.Sprintf("create a pr from %s to %s", headBranch, baseBranch), - }) + }).AddTokenAuth(ctx.Token) expected := http.StatusCreated if ctx.ExpectedCode != 0 { @@ -242,9 +237,8 @@ func doAPICreatePullRequest(ctx APITestContext, owner, repo, baseBranch, headBra func doAPIGetPullRequest(ctx APITestContext, owner, repo string, index int64) func(*testing.T) (api.PullRequest, error) { return func(t *testing.T) (api.PullRequest, error) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d?token=%s", - owner, repo, index, ctx.Token) - req := NewRequest(t, http.MethodGet, urlStr) + req := NewRequest(t, http.MethodGet, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d", owner, repo, index)). + AddTokenAuth(ctx.Token) expected := http.StatusOK if ctx.ExpectedCode != 0 { @@ -261,17 +255,16 @@ func doAPIGetPullRequest(ctx APITestContext, owner, repo string, index int64) fu func doAPIMergePullRequest(ctx APITestContext, owner, repo string, index int64) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s", - owner, repo, index, ctx.Token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge", owner, repo, index) - var req *http.Request + var req *RequestWrapper var resp *httptest.ResponseRecorder for i := 0; i < 6; i++ { req = NewRequestWithJSON(t, http.MethodPost, urlStr, &forms.MergePullRequestForm{ MergeMessageField: "doAPIMergePullRequest Merge", Do: string(repo_model.MergeStyleMerge), - }) + }).AddTokenAuth(ctx.Token) resp = ctx.Session.MakeRequest(t, req, NoExpectedStatus) @@ -299,12 +292,11 @@ func doAPIMergePullRequest(ctx APITestContext, owner, repo string, index int64) func doAPIManuallyMergePullRequest(ctx APITestContext, owner, repo, commitID string, index int64) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s", - owner, repo, index, ctx.Token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge", owner, repo, index) req := NewRequestWithJSON(t, http.MethodPost, urlStr, &forms.MergePullRequestForm{ Do: string(repo_model.MergeStyleManuallyMerged), MergeCommitID: commitID, - }) + }).AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) @@ -316,38 +308,37 @@ func doAPIManuallyMergePullRequest(ctx APITestContext, owner, repo, commitID str func doAPIAutoMergePullRequest(ctx APITestContext, owner, repo string, index int64) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s", - owner, repo, index, ctx.Token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge", owner, repo, index) req := NewRequestWithJSON(t, http.MethodPost, urlStr, &forms.MergePullRequestForm{ MergeMessageField: "doAPIMergePullRequest Merge", Do: string(repo_model.MergeStyleMerge), MergeWhenChecksSucceed: true, - }) + }).AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return } - ctx.Session.MakeRequest(t, req, 200) + ctx.Session.MakeRequest(t, req, http.StatusOK) } } func doAPICancelAutoMergePullRequest(ctx APITestContext, owner, repo string, index int64) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s", - owner, repo, index, ctx.Token) - req := NewRequest(t, http.MethodDelete, urlStr) + req := NewRequest(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge", owner, repo, index)). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return } - ctx.Session.MakeRequest(t, req, 204) + ctx.Session.MakeRequest(t, req, http.StatusNoContent) } } func doAPIGetBranch(ctx APITestContext, branch string, callback ...func(*testing.T, api.Branch)) func(*testing.T) { return func(t *testing.T) { - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/branches/%s?token=%s", ctx.Username, ctx.Reponame, branch, ctx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/branches/%s", ctx.Username, ctx.Reponame, branch). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -364,8 +355,8 @@ func doAPIGetBranch(ctx APITestContext, branch string, callback ...func(*testing func doAPICreateFile(ctx APITestContext, treepath string, options *api.CreateFileOptions, callback ...func(*testing.T, api.FileResponse)) func(*testing.T) { return func(t *testing.T) { - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", ctx.Username, ctx.Reponame, treepath, ctx.Token) - req := NewRequestWithJSON(t, "POST", url, &options) + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", ctx.Username, ctx.Reponame, treepath), &options). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -382,9 +373,8 @@ func doAPICreateFile(ctx APITestContext, treepath string, options *api.CreateFil func doAPICreateOrganization(ctx APITestContext, options *api.CreateOrgOption, callback ...func(*testing.T, api.Organization)) func(t *testing.T) { return func(t *testing.T) { - url := fmt.Sprintf("/api/v1/orgs?token=%s", ctx.Token) - - req := NewRequestWithJSON(t, "POST", url, &options) + req := NewRequestWithJSON(t, "POST", "/api/v1/orgs", &options). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -401,9 +391,8 @@ func doAPICreateOrganization(ctx APITestContext, options *api.CreateOrgOption, c func doAPICreateOrganizationRepository(ctx APITestContext, orgName string, options *api.CreateRepoOption, callback ...func(*testing.T, api.Repository)) func(t *testing.T) { return func(t *testing.T) { - url := fmt.Sprintf("/api/v1/orgs/%s/repos?token=%s", orgName, ctx.Token) - - req := NewRequestWithJSON(t, "POST", url, &options) + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/repos", orgName), &options). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -420,9 +409,8 @@ func doAPICreateOrganizationRepository(ctx APITestContext, orgName string, optio func doAPICreateOrganizationTeam(ctx APITestContext, orgName string, options *api.CreateTeamOption, callback ...func(*testing.T, api.Team)) func(t *testing.T) { return func(t *testing.T) { - url := fmt.Sprintf("/api/v1/orgs/%s/teams?token=%s", orgName, ctx.Token) - - req := NewRequestWithJSON(t, "POST", url, &options) + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams", orgName), &options). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -439,9 +427,8 @@ func doAPICreateOrganizationTeam(ctx APITestContext, orgName string, options *ap func doAPIAddUserToOrganizationTeam(ctx APITestContext, teamID int64, username string) func(t *testing.T) { return func(t *testing.T) { - url := fmt.Sprintf("/api/v1/teams/%d/members/%s?token=%s", teamID, username, ctx.Token) - - req := NewRequest(t, "PUT", url) + req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/teams/%d/members/%s", teamID, username)). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -452,9 +439,8 @@ func doAPIAddUserToOrganizationTeam(ctx APITestContext, teamID int64, username s func doAPIAddRepoToOrganizationTeam(ctx APITestContext, teamID int64, orgName, repoName string) func(t *testing.T) { return func(t *testing.T) { - url := fmt.Sprintf("/api/v1/teams/%d/repos/%s/%s?token=%s", teamID, orgName, repoName, ctx.Token) - - req := NewRequest(t, "PUT", url) + req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/teams/%d/repos/%s/%s", teamID, orgName, repoName)). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return diff --git a/tests/integration/api_httpsig_test.go b/tests/integration/api_httpsig_test.go index 675ec54ff58f..30aed3cacceb 100644 --- a/tests/integration/api_httpsig_test.go +++ b/tests/integration/api_httpsig_test.go @@ -5,7 +5,6 @@ package integration import ( "encoding/base64" - "fmt" "net/http" "net/url" "testing" @@ -57,14 +56,14 @@ func TestHTTPSigPubKey(t *testing.T) { defer test.MockVariableValue(&setting.SSH.MinimumKeySizeCheck, false)() session := loginUser(t, "user1") token := url.QueryEscape(getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteUser)) - keysURL := fmt.Sprintf("/api/v1/user/keys?token=%s", token) keyType := "ssh-rsa" keyContent := "AAAAB3NzaC1yc2EAAAADAQABAAABAQCqOZB5vkRvXFXups1/0StDRdG8plbNSwsWEnNnP4Bvurxa0+z3W9B8GLKnDiLw5MbpbMNyBlpXw13GfuIeciy10DWTz0xUbiy3J3KabCaT36asIw2y7k6Z0jL0UBnrVENwq5/lUbZYqSZ4rRU744wkhh8TULpzM14npQCZwg6aEbG+MwjzddQ72fR+3BPBrKn5dTmmu8rH99O+U+Nuto81Tg7PA+NUupcHOmhdiEGq49plgVFXK98Vks5tiybL4GuzFyWgyX73Dg/QBMn2eMHt1EMv5Gs3i6GFhKKGo4rjDi9qI6PX5oDR4LTNe6cR8td8YhVD8WFZwLLl/vaYyIqd" rawKeyBody := api.CreateKeyOption{ Title: "test-key", Key: keyType + " " + keyContent, } - req := NewRequestWithJSON(t, "POST", keysURL, rawKeyBody) + req := NewRequestWithJSON(t, "POST", "/api/v1/user/keys", rawKeyBody). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) // parse our private key and create the httpsig request @@ -73,7 +72,8 @@ func TestHTTPSigPubKey(t *testing.T) { // create the request token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadAdmin) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/admin/users?token=%s", token)) + req = NewRequest(t, "GET", "/api/v1/admin/users"). + AddTokenAuth(token) signer, _, err := httpsig.NewSSHSigner(sshSigner, httpsig.DigestSha512, []string{httpsig.RequestTarget, "(created)", "(expires)"}, httpsig.Signature, 10) if err != nil { @@ -81,7 +81,7 @@ func TestHTTPSigPubKey(t *testing.T) { } // sign the request - err = signer.SignRequest(keyID, req, nil) + err = signer.SignRequest(keyID, req.Request, nil) if err != nil { t.Fatal(err) } @@ -124,7 +124,7 @@ func TestHTTPSigCert(t *testing.T) { // add our cert to the request certString := base64.RawStdEncoding.EncodeToString(pkcert.(*ssh.Certificate).Marshal()) - req.Header.Add("x-ssh-certificate", certString) + req.SetHeader("x-ssh-certificate", certString) signer, _, err := httpsig.NewSSHSigner(certSigner, httpsig.DigestSha512, []string{httpsig.RequestTarget, "(created)", "(expires)", "x-ssh-certificate"}, httpsig.Signature, 10) if err != nil { @@ -132,7 +132,7 @@ func TestHTTPSigCert(t *testing.T) { } // sign the request - err = signer.SignRequest(keyID, req, nil) + err = signer.SignRequest(keyID, req.Request, nil) if err != nil { t.Fatal(err) } diff --git a/tests/integration/api_issue_attachment_test.go b/tests/integration/api_issue_attachment_test.go index 3b43ba2c412c..4b57d387d875 100644 --- a/tests/integration/api_issue_attachment_test.go +++ b/tests/integration/api_issue_attachment_test.go @@ -33,10 +33,9 @@ func TestAPIGetIssueAttachment(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets/%d?token=%s", - repoOwner.Name, repo.Name, issue.Index, attachment.ID, token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets/%d", repoOwner.Name, repo.Name, issue.Index, attachment.ID)). + AddTokenAuth(token) resp := session.MakeRequest(t, req, http.StatusOK) apiAttachment := new(api.Attachment) DecodeJSON(t, resp, &apiAttachment) @@ -54,10 +53,9 @@ func TestAPIListIssueAttachments(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets?token=%s", - repoOwner.Name, repo.Name, issue.Index, token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets", repoOwner.Name, repo.Name, issue.Index)). + AddTokenAuth(token) resp := session.MakeRequest(t, req, http.StatusOK) apiAttachment := new([]api.Attachment) DecodeJSON(t, resp, &apiAttachment) @@ -74,8 +72,6 @@ func TestAPICreateIssueAttachment(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets?token=%s", - repoOwner.Name, repo.Name, issue.Index, token) filename := "image.png" buff := generateImg() @@ -90,7 +86,8 @@ func TestAPICreateIssueAttachment(t *testing.T) { err = writer.Close() assert.NoError(t, err) - req := NewRequestWithBody(t, "POST", urlStr, body) + req := NewRequestWithBody(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets", repoOwner.Name, repo.Name, issue.Index), body). + AddTokenAuth(token) req.Header.Add("Content-Type", writer.FormDataContentType()) resp := session.MakeRequest(t, req, http.StatusCreated) @@ -112,11 +109,11 @@ func TestAPIEditIssueAttachment(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets/%d?token=%s", - repoOwner.Name, repo.Name, issue.Index, attachment.ID, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets/%d", + repoOwner.Name, repo.Name, issue.Index, attachment.ID) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ "name": newAttachmentName, - }) + }).AddTokenAuth(token) resp := session.MakeRequest(t, req, http.StatusCreated) apiAttachment := new(api.Attachment) DecodeJSON(t, resp, &apiAttachment) @@ -134,10 +131,9 @@ func TestAPIDeleteIssueAttachment(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets/%d?token=%s", - repoOwner.Name, repo.Name, issue.Index, attachment.ID, token) - req := NewRequest(t, "DELETE", urlStr) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets/%d", repoOwner.Name, repo.Name, issue.Index, attachment.ID)). + AddTokenAuth(token) session.MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &repo_model.Attachment{ID: attachment.ID, IssueID: issue.ID}) diff --git a/tests/integration/api_issue_label_test.go b/tests/integration/api_issue_label_test.go index d2d8af102b3b..35c07182634e 100644 --- a/tests/integration/api_issue_label_test.go +++ b/tests/integration/api_issue_label_test.go @@ -26,14 +26,14 @@ func TestAPIModifyLabels(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/labels?token=%s", owner.Name, repo.Name, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/labels", owner.Name, repo.Name) // CreateLabel req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateLabelOption{ Name: "TestL 1", Color: "abcdef", Description: "test label", - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) apiLabel := new(api.Label) DecodeJSON(t, resp, &apiLabel) @@ -45,24 +45,26 @@ func TestAPIModifyLabels(t *testing.T) { Name: "TestL 2", Color: "#123456", Description: "jet another test label", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) req = NewRequestWithJSON(t, "POST", urlStr, &api.CreateLabelOption{ Name: "WrongTestL", Color: "#12345g", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) // ListLabels - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", urlStr). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var apiLabels []*api.Label DecodeJSON(t, resp, &apiLabels) assert.Len(t, apiLabels, 2) // GetLabel - singleURLStr := fmt.Sprintf("/api/v1/repos/%s/%s/labels/%d?token=%s", owner.Name, repo.Name, dbLabel.ID, token) - req = NewRequest(t, "GET", singleURLStr) + singleURLStr := fmt.Sprintf("/api/v1/repos/%s/%s/labels/%d", owner.Name, repo.Name, dbLabel.ID) + req = NewRequest(t, "GET", singleURLStr). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiLabel) assert.EqualValues(t, strings.TrimLeft(dbLabel.Color, "#"), apiLabel.Color) @@ -74,17 +76,18 @@ func TestAPIModifyLabels(t *testing.T) { req = NewRequestWithJSON(t, "PATCH", singleURLStr, &api.EditLabelOption{ Name: &newName, Color: &newColor, - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiLabel) assert.EqualValues(t, newColor, apiLabel.Color) req = NewRequestWithJSON(t, "PATCH", singleURLStr, &api.EditLabelOption{ Color: &newColorWrong, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) // DeleteLabel - req = NewRequest(t, "DELETE", singleURLStr) + req = NewRequest(t, "DELETE", singleURLStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) } @@ -98,11 +101,11 @@ func TestAPIAddIssueLabels(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels?token=%s", - repo.OwnerName, repo.Name, issue.Index, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels", + repo.OwnerName, repo.Name, issue.Index) req := NewRequestWithJSON(t, "POST", urlStr, &api.IssueLabelsOption{ Labels: []int64{1, 2}, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiLabels []*api.Label DecodeJSON(t, resp, &apiLabels) @@ -121,11 +124,11 @@ func TestAPIReplaceIssueLabels(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels?token=%s", - owner.Name, repo.Name, issue.Index, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels", + owner.Name, repo.Name, issue.Index) req := NewRequestWithJSON(t, "PUT", urlStr, &api.IssueLabelsOption{ Labels: []int64{label.ID}, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiLabels []*api.Label DecodeJSON(t, resp, &apiLabels) @@ -145,14 +148,14 @@ func TestAPIModifyOrgLabels(t *testing.T) { user := "user1" session := loginUser(t, user) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteOrganization) - urlStr := fmt.Sprintf("/api/v1/orgs/%s/labels?token=%s", owner.Name, token) + urlStr := fmt.Sprintf("/api/v1/orgs/%s/labels", owner.Name) // CreateLabel req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateLabelOption{ Name: "TestL 1", Color: "abcdef", Description: "test label", - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) apiLabel := new(api.Label) DecodeJSON(t, resp, &apiLabel) @@ -164,24 +167,26 @@ func TestAPIModifyOrgLabels(t *testing.T) { Name: "TestL 2", Color: "#123456", Description: "jet another test label", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) req = NewRequestWithJSON(t, "POST", urlStr, &api.CreateLabelOption{ Name: "WrongTestL", Color: "#12345g", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) // ListLabels - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", urlStr). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var apiLabels []*api.Label DecodeJSON(t, resp, &apiLabels) assert.Len(t, apiLabels, 4) // GetLabel - singleURLStr := fmt.Sprintf("/api/v1/orgs/%s/labels/%d?token=%s", owner.Name, dbLabel.ID, token) - req = NewRequest(t, "GET", singleURLStr) + singleURLStr := fmt.Sprintf("/api/v1/orgs/%s/labels/%d", owner.Name, dbLabel.ID) + req = NewRequest(t, "GET", singleURLStr). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiLabel) assert.EqualValues(t, strings.TrimLeft(dbLabel.Color, "#"), apiLabel.Color) @@ -193,16 +198,17 @@ func TestAPIModifyOrgLabels(t *testing.T) { req = NewRequestWithJSON(t, "PATCH", singleURLStr, &api.EditLabelOption{ Name: &newName, Color: &newColor, - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiLabel) assert.EqualValues(t, newColor, apiLabel.Color) req = NewRequestWithJSON(t, "PATCH", singleURLStr, &api.EditLabelOption{ Color: &newColorWrong, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) // DeleteLabel - req = NewRequest(t, "DELETE", singleURLStr) + req = NewRequest(t, "DELETE", singleURLStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) } diff --git a/tests/integration/api_issue_milestone_test.go b/tests/integration/api_issue_milestone_test.go index 3bd763f4b52c..32ac56298fab 100644 --- a/tests/integration/api_issue_milestone_test.go +++ b/tests/integration/api_issue_milestone_test.go @@ -34,48 +34,53 @@ func TestAPIIssuesMilestone(t *testing.T) { // update values of issue milestoneState := "closed" - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/milestones/%d?token=%s", owner.Name, repo.Name, milestone.ID, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/milestones/%d", owner.Name, repo.Name, milestone.ID) req := NewRequestWithJSON(t, "PATCH", urlStr, structs.EditMilestoneOption{ State: &milestoneState, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiMilestone structs.Milestone DecodeJSON(t, resp, &apiMilestone) assert.EqualValues(t, "closed", apiMilestone.State) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", urlStr). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var apiMilestone2 structs.Milestone DecodeJSON(t, resp, &apiMilestone2) assert.EqualValues(t, "closed", apiMilestone2.State) - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/milestones?token=%s", owner.Name, repo.Name, token), structs.CreateMilestoneOption{ + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/milestones", owner.Name, repo.Name), structs.CreateMilestoneOption{ Title: "wow", Description: "closed one", State: "closed", - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, &apiMilestone) assert.Equal(t, "wow", apiMilestone.Title) assert.Equal(t, structs.StateClosed, apiMilestone.State) var apiMilestones []structs.Milestone - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/milestones?state=%s&token=%s", owner.Name, repo.Name, "all", token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/milestones?state=%s", owner.Name, repo.Name, "all")). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiMilestones) assert.Len(t, apiMilestones, 4) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/milestones/%s?token=%s", owner.Name, repo.Name, apiMilestones[2].Title, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/milestones/%s", owner.Name, repo.Name, apiMilestones[2].Title)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiMilestone) assert.EqualValues(t, apiMilestones[2], apiMilestone) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/milestones?state=%s&name=%s&token=%s", owner.Name, repo.Name, "all", "milestone2", token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/milestones?state=%s&name=%s", owner.Name, repo.Name, "all", "milestone2")). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiMilestones) assert.Len(t, apiMilestones, 1) assert.Equal(t, int64(2), apiMilestones[0].ID) - req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/milestones/%d?token=%s", owner.Name, repo.Name, apiMilestone.ID, token)) + req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/milestones/%d", owner.Name, repo.Name, apiMilestone.ID)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) } diff --git a/tests/integration/api_issue_pin_test.go b/tests/integration/api_issue_pin_test.go index 5a9efc058bfb..1cff937254b8 100644 --- a/tests/integration/api_issue_pin_test.go +++ b/tests/integration/api_issue_pin_test.go @@ -32,14 +32,12 @@ func TestAPIPinIssue(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) // Pin the Issue - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin?token=%s", - repo.OwnerName, repo.Name, issue.Index, token) - req := NewRequest(t, "POST", urlStr) + req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin", repo.OwnerName, repo.Name, issue.Index)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Check if the Issue is pinned - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index)) resp := MakeRequest(t, req, http.StatusOK) var issueAPI api.Issue DecodeJSON(t, resp, &issueAPI) @@ -59,28 +57,24 @@ func TestAPIUnpinIssue(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) // Pin the Issue - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin?token=%s", - repo.OwnerName, repo.Name, issue.Index, token) - req := NewRequest(t, "POST", urlStr) + req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin", repo.OwnerName, repo.Name, issue.Index)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Check if the Issue is pinned - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index)) resp := MakeRequest(t, req, http.StatusOK) var issueAPI api.Issue DecodeJSON(t, resp, &issueAPI) assert.Equal(t, 1, issueAPI.PinOrder) // Unpin the Issue - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin?token=%s", - repo.OwnerName, repo.Name, issue.Index, token) - req = NewRequest(t, "DELETE", urlStr) + req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin", repo.OwnerName, repo.Name, issue.Index)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Check if the Issue is no longer pinned - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index)) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &issueAPI) assert.Equal(t, 0, issueAPI.PinOrder) @@ -100,42 +94,36 @@ func TestAPIMoveIssuePin(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) // Pin the first Issue - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin?token=%s", - repo.OwnerName, repo.Name, issue.Index, token) - req := NewRequest(t, "POST", urlStr) + req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin", repo.OwnerName, repo.Name, issue.Index)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Check if the first Issue is pinned at position 1 - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index)) resp := MakeRequest(t, req, http.StatusOK) var issueAPI api.Issue DecodeJSON(t, resp, &issueAPI) assert.Equal(t, 1, issueAPI.PinOrder) // Pin the second Issue - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin?token=%s", - repo.OwnerName, repo.Name, issue2.Index, token) - req = NewRequest(t, "POST", urlStr) + req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin", repo.OwnerName, repo.Name, issue2.Index)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Move the first Issue to position 2 - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin/2?token=%s", - repo.OwnerName, repo.Name, issue.Index, token) - req = NewRequest(t, "PATCH", urlStr) + req = NewRequest(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin/2", repo.OwnerName, repo.Name, issue.Index)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Check if the first Issue is pinned at position 2 - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index)) resp = MakeRequest(t, req, http.StatusOK) var issueAPI3 api.Issue DecodeJSON(t, resp, &issueAPI3) assert.Equal(t, 2, issueAPI3.PinOrder) // Check if the second Issue is pinned at position 1 - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue2.Index) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue2.Index)) resp = MakeRequest(t, req, http.StatusOK) var issueAPI4 api.Issue DecodeJSON(t, resp, &issueAPI4) @@ -155,14 +143,12 @@ func TestAPIListPinnedIssues(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) // Pin the Issue - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin?token=%s", - repo.OwnerName, repo.Name, issue.Index, token) - req := NewRequest(t, "POST", urlStr) + req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin", repo.OwnerName, repo.Name, issue.Index)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Check if the Issue is in the List - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/pinned", repo.OwnerName, repo.Name) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/pinned", repo.OwnerName, repo.Name)) resp := MakeRequest(t, req, http.StatusOK) var issueList []api.Issue DecodeJSON(t, resp, &issueList) @@ -178,8 +164,7 @@ func TestAPIListPinnedPullrequests(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/pinned", repo.OwnerName, repo.Name) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/pulls/pinned", repo.OwnerName, repo.Name)) resp := MakeRequest(t, req, http.StatusOK) var prList []api.PullRequest DecodeJSON(t, resp, &prList) @@ -193,8 +178,7 @@ func TestAPINewPinAllowed(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/new_pin_allowed", owner.Name, repo.Name) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/new_pin_allowed", owner.Name, repo.Name)) resp := MakeRequest(t, req, http.StatusOK) var newPinsAllowed api.NewIssuePinsAllowed diff --git a/tests/integration/api_issue_reaction_test.go b/tests/integration/api_issue_reaction_test.go index 124d729353ca..4ca909f2812b 100644 --- a/tests/integration/api_issue_reaction_test.go +++ b/tests/integration/api_issue_reaction_test.go @@ -33,25 +33,24 @@ func TestAPIIssuesReactions(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/reactions?token=%s", - owner.Name, issue.Repo.Name, issue.Index, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/reactions", owner.Name, issue.Repo.Name, issue.Index) // Try to add not allowed reaction req := NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "wrong", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) // Delete not allowed reaction req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{ Reaction: "zzz", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) // Add allowed reaction req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "rocket", - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var apiNewReaction api.Reaction DecodeJSON(t, resp, &apiNewReaction) @@ -60,7 +59,8 @@ func TestAPIIssuesReactions(t *testing.T) { MakeRequest(t, req, http.StatusForbidden) // Get end result of reaction list of issue #1 - req = NewRequestf(t, "GET", urlStr) + req = NewRequest(t, "GET", urlStr). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var apiReactions []*api.Reaction DecodeJSON(t, resp, &apiReactions) @@ -93,19 +93,18 @@ func TestAPICommentReactions(t *testing.T) { user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/reactions?token=%s", - owner.Name, issue.Repo.Name, comment.ID, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/reactions", owner.Name, issue.Repo.Name, comment.ID) // Try to add not allowed reaction req := NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "wrong", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) // Delete none existing reaction req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{ Reaction: "eyes", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) t.Run("UnrelatedCommentID", func(t *testing.T) { @@ -113,25 +112,25 @@ func TestAPICommentReactions(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/reactions?token=%s", - repoOwner.Name, repo.Name, comment.ID, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/reactions", repoOwner.Name, repo.Name, comment.ID) req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "+1", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{ Reaction: "+1", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequestf(t, "GET", urlStr) + req = NewRequest(t, "GET", urlStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) }) // Add allowed reaction req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "+1", - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var apiNewReaction api.Reaction DecodeJSON(t, resp, &apiNewReaction) @@ -140,7 +139,8 @@ func TestAPICommentReactions(t *testing.T) { MakeRequest(t, req, http.StatusForbidden) // Get end result of reaction list of issue #1 - req = NewRequestf(t, "GET", urlStr) + req = NewRequest(t, "GET", urlStr). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var apiReactions []*api.Reaction DecodeJSON(t, resp, &apiReactions) diff --git a/tests/integration/api_issue_stopwatch_test.go b/tests/integration/api_issue_stopwatch_test.go index 09d404ce4e23..23066782173a 100644 --- a/tests/integration/api_issue_stopwatch_test.go +++ b/tests/integration/api_issue_stopwatch_test.go @@ -27,7 +27,8 @@ func TestAPIListStopWatches(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository, auth_model.AccessTokenScopeReadUser) - req := NewRequestf(t, "GET", "/api/v1/user/stopwatches?token=%s", token) + req := NewRequest(t, "GET", "/api/v1/user/stopwatches"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiWatches []*api.StopWatch DecodeJSON(t, resp, &apiWatches) @@ -54,7 +55,8 @@ func TestAPIStopStopWatches(t *testing.T) { session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/issues/%d/stopwatch/stop?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) + req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/issues/%d/stopwatch/stop", owner.Name, issue.Repo.Name, issue.Index). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) MakeRequest(t, req, http.StatusConflict) } @@ -70,7 +72,8 @@ func TestAPICancelStopWatches(t *testing.T) { session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/stopwatch/delete?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) + req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/stopwatch/delete", owner.Name, issue.Repo.Name, issue.Index). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) MakeRequest(t, req, http.StatusConflict) } @@ -86,7 +89,8 @@ func TestAPIStartStopWatches(t *testing.T) { session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/issues/%d/stopwatch/start?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) + req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/issues/%d/stopwatch/start", owner.Name, issue.Repo.Name, issue.Index). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) MakeRequest(t, req, http.StatusConflict) } diff --git a/tests/integration/api_issue_subscription_test.go b/tests/integration/api_issue_subscription_test.go index 28650a337523..7a716301c466 100644 --- a/tests/integration/api_issue_subscription_test.go +++ b/tests/integration/api_issue_subscription_test.go @@ -37,8 +37,8 @@ func TestAPIIssueSubscriptions(t *testing.T) { testSubscription := func(issue *issues_model.Issue, isWatching bool) { issueRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/check?token=%s", issueRepo.OwnerName, issueRepo.Name, issue.Index, token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/check", issueRepo.OwnerName, issueRepo.Name, issue.Index)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) wi := new(api.WatchInfo) DecodeJSON(t, resp, wi) @@ -57,22 +57,26 @@ func TestAPIIssueSubscriptions(t *testing.T) { testSubscription(issue5, false) issue1Repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue1.RepoID}) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/%s?token=%s", issue1Repo.OwnerName, issue1Repo.Name, issue1.Index, owner.Name, token) - req := NewRequest(t, "DELETE", urlStr) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/%s", issue1Repo.OwnerName, issue1Repo.Name, issue1.Index, owner.Name) + req := NewRequest(t, "DELETE", urlStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) testSubscription(issue1, false) - req = NewRequest(t, "DELETE", urlStr) + req = NewRequest(t, "DELETE", urlStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) testSubscription(issue1, false) issue5Repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue5.RepoID}) - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/%s?token=%s", issue5Repo.OwnerName, issue5Repo.Name, issue5.Index, owner.Name, token) - req = NewRequest(t, "PUT", urlStr) + urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/%s", issue5Repo.OwnerName, issue5Repo.Name, issue5.Index, owner.Name) + req = NewRequest(t, "PUT", urlStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) testSubscription(issue5, true) - req = NewRequest(t, "PUT", urlStr) + req = NewRequest(t, "PUT", urlStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) testSubscription(issue5, true) } diff --git a/tests/integration/api_issue_test.go b/tests/integration/api_issue_test.go index 29f09fa09e74..dcccafb0f29b 100644 --- a/tests/integration/api_issue_test.go +++ b/tests/integration/api_issue_test.go @@ -84,12 +84,12 @@ func TestAPICreateIssue(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all&token=%s", owner.Name, repoBefore.Name, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all", owner.Name, repoBefore.Name) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateIssueOption{ Body: body, Title: title, Assignee: owner.Name, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var apiIssue api.Issue DecodeJSON(t, resp, &apiIssue) @@ -117,7 +117,7 @@ func TestAPICreateIssueParallel(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all&token=%s", owner.Name, repoBefore.Name, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all", owner.Name, repoBefore.Name) var wg sync.WaitGroup for i := 0; i < 10; i++ { @@ -130,7 +130,7 @@ func TestAPICreateIssueParallel(t *testing.T) { Body: newBody, Title: newTitle, Assignee: owner.Name, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var apiIssue api.Issue DecodeJSON(t, resp, &apiIssue) @@ -171,7 +171,7 @@ func TestAPIEditIssue(t *testing.T) { body := "new content!" title := "new title from api set" - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d?token=%s", owner.Name, repoBefore.Name, issueBefore.Index, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", owner.Name, repoBefore.Name, issueBefore.Index) req := NewRequestWithJSON(t, "PATCH", urlStr, api.EditIssueOption{ State: &issueState, RemoveDeadline: &removeDeadline, @@ -180,7 +180,7 @@ func TestAPIEditIssue(t *testing.T) { Title: title, // ToDo change more - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var apiIssue api.Issue DecodeJSON(t, resp, &apiIssue) diff --git a/tests/integration/api_issue_tracked_time_test.go b/tests/integration/api_issue_tracked_time_test.go index d3e45456a6c6..fd2c452b2068 100644 --- a/tests/integration/api_issue_tracked_time_test.go +++ b/tests/integration/api_issue_tracked_time_test.go @@ -30,7 +30,8 @@ func TestAPIGetTrackedTimes(t *testing.T) { session := loginUser(t, user2.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadIssue) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/times?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/times", user2.Name, issue2.Repo.Name, issue2.Index). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiTimes api.TrackedTimeList DecodeJSON(t, resp, &apiTimes) @@ -53,7 +54,8 @@ func TestAPIGetTrackedTimes(t *testing.T) { since := "2000-01-01T00%3A00%3A02%2B00%3A00" // 946684802 before := "2000-01-01T00%3A00%3A12%2B00%3A00" // 946684812 - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/times?since=%s&before=%s&token=%s", user2.Name, issue2.Repo.Name, issue2.Index, since, before, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/times?since=%s&before=%s", user2.Name, issue2.Repo.Name, issue2.Index, since, before). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var filterAPITimes api.TrackedTimeList DecodeJSON(t, resp, &filterAPITimes) @@ -74,11 +76,13 @@ func TestAPIDeleteTrackedTime(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) // Deletion not allowed - req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time6.ID, token) + req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d", user2.Name, issue2.Repo.Name, issue2.Index, time6.ID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) time3 := unittest.AssertExistsAndLoadBean(t, &issues_model.TrackedTime{ID: 3}) - req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time3.ID, token) + req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d", user2.Name, issue2.Repo.Name, issue2.Index, time3.ID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Delete non existing time MakeRequest(t, req, http.StatusNotFound) @@ -88,7 +92,8 @@ func TestAPIDeleteTrackedTime(t *testing.T) { assert.NoError(t, err) assert.Equal(t, int64(3661), trackedSeconds) - req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, token) + req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times", user2.Name, issue2.Repo.Name, issue2.Index). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) MakeRequest(t, req, http.StatusNotFound) @@ -108,13 +113,13 @@ func TestAPIAddTrackedTimes(t *testing.T) { session := loginUser(t, admin.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/times?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/times", user2.Name, issue2.Repo.Name, issue2.Index) req := NewRequestWithJSON(t, "POST", urlStr, &api.AddTimeOption{ Time: 33, User: user2.Name, Created: time.Unix(947688818, 0), - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiNewTime api.TrackedTime DecodeJSON(t, resp, &apiNewTime) diff --git a/tests/integration/api_keys_test.go b/tests/integration/api_keys_test.go index 03d28c912665..89ad1ec0df51 100644 --- a/tests/integration/api_keys_test.go +++ b/tests/integration/api_keys_test.go @@ -55,13 +55,14 @@ func TestCreateReadOnlyDeployKey(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", repoOwner.Name, repo.Name, token) + keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys", repoOwner.Name, repo.Name) rawKeyBody := api.CreateKeyOption{ Title: "read-only", Key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n", ReadOnly: true, } - req := NewRequestWithJSON(t, "POST", keysURL, rawKeyBody) + req := NewRequestWithJSON(t, "POST", keysURL, rawKeyBody). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var newDeployKey api.DeployKey @@ -75,12 +76,14 @@ func TestCreateReadOnlyDeployKey(t *testing.T) { // Using the ID of a key that does not belong to the repository must fail { - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/keys/%d?token=%s", repoOwner.Name, repo.Name, newDeployKey.ID, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/keys/%d", repoOwner.Name, repo.Name, newDeployKey.ID)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) session5 := loginUser(t, "user5") token5 := getTokenForLoggedInUser(t, session5, auth_model.AccessTokenScopeWriteRepository) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/user5/repo4/keys/%d?token=%s", newDeployKey.ID, token5)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/user5/repo4/keys/%d", newDeployKey.ID)). + AddTokenAuth(token5) MakeRequest(t, req, http.StatusNotFound) } } @@ -92,12 +95,13 @@ func TestCreateReadWriteDeployKey(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", repoOwner.Name, repo.Name, token) + keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys", repoOwner.Name, repo.Name) rawKeyBody := api.CreateKeyOption{ Title: "read-write", Key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n", } - req := NewRequestWithJSON(t, "POST", keysURL, rawKeyBody) + req := NewRequestWithJSON(t, "POST", keysURL, rawKeyBody). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var newDeployKey api.DeployKey @@ -116,14 +120,14 @@ func TestCreateUserKey(t *testing.T) { session := loginUser(t, "user1") token := url.QueryEscape(getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteUser)) - keysURL := fmt.Sprintf("/api/v1/user/keys?token=%s", token) keyType := "ssh-rsa" keyContent := "AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM=" rawKeyBody := api.CreateKeyOption{ Title: "test-key", Key: keyType + " " + keyContent, } - req := NewRequestWithJSON(t, "POST", keysURL, rawKeyBody) + req := NewRequestWithJSON(t, "POST", "/api/v1/user/keys", rawKeyBody). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var newPublicKey api.PublicKey @@ -139,9 +143,8 @@ func TestCreateUserKey(t *testing.T) { }) // Search by fingerprint - fingerprintURL := fmt.Sprintf("/api/v1/user/keys?token=%s&fingerprint=%s", token, newPublicKey.Fingerprint) - - req = NewRequest(t, "GET", fingerprintURL) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/keys?fingerprint=%s", newPublicKey.Fingerprint)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var fingerprintPublicKeys []api.PublicKey @@ -150,9 +153,8 @@ func TestCreateUserKey(t *testing.T) { assert.Equal(t, newPublicKey.ID, fingerprintPublicKeys[0].ID) assert.Equal(t, user.ID, fingerprintPublicKeys[0].Owner.ID) - fingerprintURL = fmt.Sprintf("/api/v1/users/%s/keys?token=%s&fingerprint=%s", user.Name, token, newPublicKey.Fingerprint) - - req = NewRequest(t, "GET", fingerprintURL) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/keys?fingerprint=%s", user.Name, newPublicKey.Fingerprint)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fingerprintPublicKeys) @@ -161,17 +163,16 @@ func TestCreateUserKey(t *testing.T) { assert.Equal(t, user.ID, fingerprintPublicKeys[0].Owner.ID) // Fail search by fingerprint - fingerprintURL = fmt.Sprintf("/api/v1/user/keys?token=%s&fingerprint=%sA", token, newPublicKey.Fingerprint) - - req = NewRequest(t, "GET", fingerprintURL) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/keys?fingerprint=%sA", newPublicKey.Fingerprint)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fingerprintPublicKeys) assert.Len(t, fingerprintPublicKeys, 0) // Fail searching for wrong users key - fingerprintURL = fmt.Sprintf("/api/v1/users/%s/keys?token=%s&fingerprint=%s", "user2", token, newPublicKey.Fingerprint) - req = NewRequest(t, "GET", fingerprintURL) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/keys?fingerprint=%s", "user2", newPublicKey.Fingerprint)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fingerprintPublicKeys) @@ -179,11 +180,11 @@ func TestCreateUserKey(t *testing.T) { // Now login as user 2 session2 := loginUser(t, "user2") - token2 := url.QueryEscape(getTokenForLoggedInUser(t, session2, auth_model.AccessTokenScopeWriteUser)) + token2 := getTokenForLoggedInUser(t, session2, auth_model.AccessTokenScopeWriteUser) // Should find key even though not ours, but we shouldn't know whose it is - fingerprintURL = fmt.Sprintf("/api/v1/user/keys?token=%s&fingerprint=%s", token2, newPublicKey.Fingerprint) - req = NewRequest(t, "GET", fingerprintURL) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/keys?fingerprint=%s", newPublicKey.Fingerprint)). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fingerprintPublicKeys) @@ -192,9 +193,8 @@ func TestCreateUserKey(t *testing.T) { assert.Nil(t, fingerprintPublicKeys[0].Owner) // Should find key even though not ours, but we shouldn't know whose it is - fingerprintURL = fmt.Sprintf("/api/v1/users/%s/keys?token=%s&fingerprint=%s", user.Name, token2, newPublicKey.Fingerprint) - - req = NewRequest(t, "GET", fingerprintURL) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/keys?fingerprint=%s", user.Name, newPublicKey.Fingerprint)). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fingerprintPublicKeys) @@ -203,8 +203,8 @@ func TestCreateUserKey(t *testing.T) { assert.Nil(t, fingerprintPublicKeys[0].Owner) // Fail when searching for key if it is not ours - fingerprintURL = fmt.Sprintf("/api/v1/users/%s/keys?token=%s&fingerprint=%s", "user2", token2, newPublicKey.Fingerprint) - req = NewRequest(t, "GET", fingerprintURL) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/keys?fingerprint=%s", "user2", newPublicKey.Fingerprint)). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fingerprintPublicKeys) diff --git a/tests/integration/api_nodeinfo_test.go b/tests/integration/api_nodeinfo_test.go index fb35d72ac2ff..a727aea3ce8d 100644 --- a/tests/integration/api_nodeinfo_test.go +++ b/tests/integration/api_nodeinfo_test.go @@ -24,7 +24,7 @@ func TestNodeinfo(t *testing.T) { }() onGiteaRun(t, func(*testing.T, *url.URL) { - req := NewRequestf(t, "GET", "/api/v1/nodeinfo") + req := NewRequest(t, "GET", "/api/v1/nodeinfo") resp := MakeRequest(t, req, http.StatusOK) VerifyJSONSchema(t, resp, "nodeinfo_2.1.json") diff --git a/tests/integration/api_notification_test.go b/tests/integration/api_notification_test.go index c6ee576e5921..528890ca22bd 100644 --- a/tests/integration/api_notification_test.go +++ b/tests/integration/api_notification_test.go @@ -35,7 +35,8 @@ func TestAPINotification(t *testing.T) { // -- GET /notifications -- // test filter since := "2000-01-01T00%3A50%3A01%2B00%3A00" // 946687801 - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?since=%s&token=%s", since, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?since=%s", since)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiNL []api.NotificationThread DecodeJSON(t, resp, &apiNL) @@ -46,7 +47,8 @@ func TestAPINotification(t *testing.T) { // test filter before := "2000-01-01T01%3A06%3A59%2B00%3A00" // 946688819 - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?all=%s&before=%s&token=%s", "true", before, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?all=%s&before=%s", "true", before)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiNL) @@ -62,7 +64,8 @@ func TestAPINotification(t *testing.T) { assert.False(t, apiNL[2].Pinned) // -- GET /repos/{owner}/{repo}/notifications -- - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?status-types=unread&token=%s", user2.Name, repo1.Name, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?status-types=unread", user2.Name, repo1.Name)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiNL) @@ -70,7 +73,8 @@ func TestAPINotification(t *testing.T) { assert.EqualValues(t, 4, apiNL[0].ID) // -- GET /repos/{owner}/{repo}/notifications -- multiple status-types - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?status-types=unread&status-types=pinned&token=%s", user2.Name, repo1.Name, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?status-types=unread&status-types=pinned", user2.Name, repo1.Name)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiNL) @@ -86,11 +90,13 @@ func TestAPINotification(t *testing.T) { // -- GET /notifications/threads/{id} -- // get forbidden - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications/threads/%d?token=%s", 1, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications/threads/%d", 1)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) // get own - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications/threads/%d?token=%s", thread5.ID, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications/threads/%d", thread5.ID)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var apiN api.NotificationThread DecodeJSON(t, resp, &apiN) @@ -110,28 +116,33 @@ func TestAPINotification(t *testing.T) { }{} // -- check notifications -- - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications/new?token=%s", token)) + req = NewRequest(t, "GET", "/api/v1/notifications/new"). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &new) assert.True(t, new.New > 0) // -- mark notifications as read -- - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?status-types=unread&token=%s", token)) + req = NewRequest(t, "GET", "/api/v1/notifications?status-types=unread"). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiNL) assert.Len(t, apiNL, 2) lastReadAt := "2000-01-01T00%3A50%3A01%2B00%3A00" // 946687801 <- only Notification 4 is in this filter ... - req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?last_read_at=%s&token=%s", user2.Name, repo1.Name, lastReadAt, token)) + req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?last_read_at=%s", user2.Name, repo1.Name, lastReadAt)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusResetContent) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?status-types=unread&token=%s", token)) + req = NewRequest(t, "GET", "/api/v1/notifications?status-types=unread"). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiNL) assert.Len(t, apiNL, 1) // -- PATCH /notifications/threads/{id} -- - req = NewRequest(t, "PATCH", fmt.Sprintf("/api/v1/notifications/threads/%d?token=%s", thread5.ID, token)) + req = NewRequest(t, "PATCH", fmt.Sprintf("/api/v1/notifications/threads/%d", thread5.ID)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusResetContent) assert.Equal(t, activities_model.NotificationStatusUnread, thread5.Status) @@ -139,7 +150,8 @@ func TestAPINotification(t *testing.T) { assert.Equal(t, activities_model.NotificationStatusRead, thread5.Status) // -- check notifications -- - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications/new?token=%s", token)) + req = NewRequest(t, "GET", "/api/v1/notifications/new"). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &new) assert.True(t, new.New == 0) @@ -155,7 +167,8 @@ func TestAPINotificationPUT(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteNotification) // Check notifications are as expected - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?all=true&token=%s", token)) + req := NewRequest(t, "GET", "/api/v1/notifications?all=true"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiNL []api.NotificationThread DecodeJSON(t, resp, &apiNL) @@ -178,7 +191,8 @@ func TestAPINotificationPUT(t *testing.T) { // Notification ID 2 is the only one with status-type read & pinned // change it to unread. // - req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/notifications?status-types=read&status-type=pinned&to-status=unread&token=%s", token)) + req = NewRequest(t, "PUT", "/api/v1/notifications?status-types=read&status-type=pinned&to-status=unread"). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusResetContent) DecodeJSON(t, resp, &apiNL) assert.Len(t, apiNL, 1) @@ -189,7 +203,8 @@ func TestAPINotificationPUT(t *testing.T) { // // Now nofication ID 2 is the first in the list and is unread. // - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?all=true&token=%s", token)) + req = NewRequest(t, "GET", "/api/v1/notifications?all=true"). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiNL) diff --git a/tests/integration/api_oauth2_apps_test.go b/tests/integration/api_oauth2_apps_test.go index 72cdba2ea2f6..0ea3dc72ff98 100644 --- a/tests/integration/api_oauth2_apps_test.go +++ b/tests/integration/api_oauth2_apps_test.go @@ -36,8 +36,8 @@ func testAPICreateOAuth2Application(t *testing.T) { ConfidentialClient: true, } - req := NewRequestWithJSON(t, "POST", "/api/v1/user/applications/oauth2", &appBody) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithJSON(t, "POST", "/api/v1/user/applications/oauth2", &appBody). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusCreated) var createdApp *api.OAuth2Application @@ -66,8 +66,8 @@ func testAPIListOAuth2Applications(t *testing.T) { ConfidentialClient: true, }) - urlStr := fmt.Sprintf("/api/v1/user/applications/oauth2?token=%s", token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", "/api/v1/user/applications/oauth2"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var appList api.OAuth2ApplicationList @@ -93,14 +93,16 @@ func testAPIDeleteOAuth2Application(t *testing.T) { Name: "test-app-1", }) - urlStr := fmt.Sprintf("/api/v1/user/applications/oauth2/%d?token=%s", oldApp.ID, token) - req := NewRequest(t, "DELETE", urlStr) + urlStr := fmt.Sprintf("/api/v1/user/applications/oauth2/%d", oldApp.ID) + req := NewRequest(t, "DELETE", urlStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &auth_model.OAuth2Application{UID: oldApp.UID, Name: oldApp.Name}) // Delete again will return not found - req = NewRequest(t, "DELETE", urlStr) + req = NewRequest(t, "DELETE", urlStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) } @@ -118,8 +120,8 @@ func testAPIGetOAuth2Application(t *testing.T) { ConfidentialClient: true, }) - urlStr := fmt.Sprintf("/api/v1/user/applications/oauth2/%d?token=%s", existApp.ID, token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/applications/oauth2/%d", existApp.ID)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var app api.OAuth2Application @@ -157,8 +159,8 @@ func testAPIUpdateOAuth2Application(t *testing.T) { } urlStr := fmt.Sprintf("/api/v1/user/applications/oauth2/%d", existApp.ID) - req := NewRequestWithJSON(t, "PATCH", urlStr, &appBody) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithJSON(t, "PATCH", urlStr, &appBody). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var app api.OAuth2Application diff --git a/tests/integration/api_org_avatar_test.go b/tests/integration/api_org_avatar_test.go index 91100c8eb783..cc1452c1535d 100644 --- a/tests/integration/api_org_avatar_test.go +++ b/tests/integration/api_org_avatar_test.go @@ -34,7 +34,8 @@ func TestAPIUpdateOrgAvatar(t *testing.T) { Image: base64.StdEncoding.EncodeToString(avatar), } - req := NewRequestWithJSON(t, "POST", "/api/v1/orgs/org3/avatar?token="+token, &opts) + req := NewRequestWithJSON(t, "POST", "/api/v1/orgs/org3/avatar", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Test what happens if you don't have a valid Base64 string @@ -42,7 +43,8 @@ func TestAPIUpdateOrgAvatar(t *testing.T) { Image: "Invalid", } - req = NewRequestWithJSON(t, "POST", "/api/v1/orgs/org3/avatar?token="+token, &opts) + req = NewRequestWithJSON(t, "POST", "/api/v1/orgs/org3/avatar", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusBadRequest) // Test what happens if you use a file that is not an image @@ -56,7 +58,8 @@ func TestAPIUpdateOrgAvatar(t *testing.T) { Image: base64.StdEncoding.EncodeToString(text), } - req = NewRequestWithJSON(t, "POST", "/api/v1/orgs/org3/avatar?token="+token, &opts) + req = NewRequestWithJSON(t, "POST", "/api/v1/orgs/org3/avatar", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusInternalServerError) } @@ -67,6 +70,7 @@ func TestAPIDeleteOrgAvatar(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteOrganization) - req := NewRequest(t, "DELETE", "/api/v1/orgs/org3/avatar?token="+token) + req := NewRequest(t, "DELETE", "/api/v1/orgs/org3/avatar"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) } diff --git a/tests/integration/api_org_test.go b/tests/integration/api_org_test.go index f19b46c2f449..1cd82fe4e09c 100644 --- a/tests/integration/api_org_test.go +++ b/tests/integration/api_org_test.go @@ -36,7 +36,8 @@ func TestAPIOrgCreate(t *testing.T) { Location: "Shanghai", Visibility: "limited", } - req := NewRequestWithJSON(t, "POST", "/api/v1/orgs?token="+token, &org) + req := NewRequestWithJSON(t, "POST", "/api/v1/orgs", &org). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var apiOrg api.Organization @@ -71,12 +72,14 @@ func TestAPIOrgCreate(t *testing.T) { }) } - req = NewRequestf(t, "GET", "/api/v1/orgs/%s?token=%s", org.UserName, token) + req = NewRequestf(t, "GET", "/api/v1/orgs/%s", org.UserName). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiOrg) assert.EqualValues(t, org.UserName, apiOrg.Name) - req = NewRequestf(t, "GET", "/api/v1/orgs/%s/repos?token=%s", org.UserName, token) + req = NewRequestf(t, "GET", "/api/v1/orgs/%s/repos", org.UserName). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var repos []*api.Repository @@ -85,7 +88,8 @@ func TestAPIOrgCreate(t *testing.T) { assert.False(t, repo.Private) } - req = NewRequestf(t, "GET", "/api/v1/orgs/%s/members?token=%s", org.UserName, token) + req = NewRequestf(t, "GET", "/api/v1/orgs/%s/members", org.UserName). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) // user1 on this org is public @@ -108,7 +112,8 @@ func TestAPIOrgEdit(t *testing.T) { Location: "Beijing", Visibility: "private", } - req := NewRequestWithJSON(t, "PATCH", "/api/v1/orgs/org3?token="+token, &org) + req := NewRequestWithJSON(t, "PATCH", "/api/v1/orgs/org3", &org). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiOrg api.Organization @@ -135,7 +140,8 @@ func TestAPIOrgEditBadVisibility(t *testing.T) { Location: "Beijing", Visibility: "badvisibility", } - req := NewRequestWithJSON(t, "PATCH", "/api/v1/orgs/org3?token="+token, &org) + req := NewRequestWithJSON(t, "PATCH", "/api/v1/orgs/org3", &org). + AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) }) } @@ -165,7 +171,8 @@ func TestAPIGetAll(t *testing.T) { token := getUserToken(t, "user1", auth_model.AccessTokenScopeReadOrganization) // accessing with a token will return all orgs - req := NewRequestf(t, "GET", "/api/v1/orgs?token=%s", token) + req := NewRequest(t, "GET", "/api/v1/orgs"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiOrgList []*api.Organization @@ -175,7 +182,7 @@ func TestAPIGetAll(t *testing.T) { assert.Equal(t, "limited", apiOrgList[1].Visibility) // accessing without a token will return only public orgs - req = NewRequestf(t, "GET", "/api/v1/orgs") + req = NewRequest(t, "GET", "/api/v1/orgs") resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiOrgList) @@ -190,22 +197,23 @@ func TestAPIOrgSearchEmptyTeam(t *testing.T) { orgName := "org_with_empty_team" // create org - req := NewRequestWithJSON(t, "POST", "/api/v1/orgs?token="+token, &api.CreateOrgOption{ + req := NewRequestWithJSON(t, "POST", "/api/v1/orgs", &api.CreateOrgOption{ UserName: orgName, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) // create team with no member - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams?token=%s", orgName, token), &api.CreateTeamOption{ + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams", orgName), &api.CreateTeamOption{ Name: "Empty", IncludesAllRepositories: true, Permission: "read", Units: []string{"repo.code", "repo.issues", "repo.ext_issues", "repo.wiki", "repo.pulls"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) // case-insensitive search for teams that have no members - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/orgs/%s/teams/search?q=%s&token=%s", orgName, "empty", token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/orgs/%s/teams/search?q=%s", orgName, "empty")). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) data := struct { Ok bool diff --git a/tests/integration/api_packages_alpine_test.go b/tests/integration/api_packages_alpine_test.go index 9a2acf854c4d..3cc7178e028b 100644 --- a/tests/integration/api_packages_alpine_test.go +++ b/tests/integration/api_packages_alpine_test.go @@ -85,12 +85,12 @@ Djfa/2q5bH4699v++uMAAAAAAAAAAAAAAAAAAAAAAHbgA/eXQh8AKAAA` req := NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader([]byte{})) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader([]byte{})) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader([]byte{})). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) - req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeAlpine) @@ -216,8 +216,8 @@ Djfa/2q5bH4699v++uMAAAAAAAAAAAAAAAAAAAAAAHbgA/eXQh8AKAAA` req := NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s/x86_64/%s-%s.apk", rootURL, branch, repository, packageName, packageVersion)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s/x86_64/%s-%s.apk", rootURL, branch, repository, packageName, packageVersion)) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s/x86_64/%s-%s.apk", rootURL, branch, repository, packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) // Deleting the last file of an architecture should remove that index diff --git a/tests/integration/api_packages_cargo_test.go b/tests/integration/api_packages_cargo_test.go index 03d8e0c5207e..6b8154af457a 100644 --- a/tests/integration/api_packages_cargo_test.go +++ b/tests/integration/api_packages_cargo_test.go @@ -132,8 +132,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { content := createPackage("0test", "1.0.0") - req := NewRequestWithBody(t, "PUT", url+"/new", content) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url+"/new", content). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusBadRequest) var status cargo_router.StatusResponse @@ -142,8 +142,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { content = createPackage("test", "-1.0.0") - req = NewRequestWithBody(t, "PUT", url+"/new", content) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url+"/new", content). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusBadRequest) DecodeJSON(t, resp, &status) @@ -161,8 +161,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { binary.Write(&buf, binary.LittleEndian, uint32(4)) buf.WriteString("te") - req := NewRequestWithBody(t, "PUT", url+"/new", &buf) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url+"/new", &buf). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) }) @@ -172,8 +172,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { req := NewRequestWithBody(t, "PUT", url+"/new", createPackage(packageName, packageVersion)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", url+"/new", createPackage(packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url+"/new", createPackage(packageName, packageVersion)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var status cargo_router.StatusResponse @@ -201,8 +201,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { assert.NoError(t, err) assert.EqualValues(t, 4, pb.Size) - req = NewRequestWithBody(t, "PUT", url+"/new", createPackage(packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url+"/new", createPackage(packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) t.Run("Index", func(t *testing.T) { @@ -288,8 +288,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { assert.NoError(t, err) assert.Len(t, pfs, 1) - req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s/download", url, neturl.PathEscape(packageName), neturl.PathEscape(pv.Version))) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s/download", url, neturl.PathEscape(packageName), neturl.PathEscape(pv.Version))). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "test", resp.Body.String()) @@ -318,8 +318,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { } for i, c := range cases { - req := NewRequest(t, "GET", fmt.Sprintf("%s?q=%s&page=%d&per_page=%d", url, c.Query, c.Page, c.PerPage)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s?q=%s&page=%d&per_page=%d", url, c.Query, c.Page, c.PerPage)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result cargo_router.SearchResult @@ -333,8 +333,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { t.Run("Yank", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s/yank", url, neturl.PathEscape(packageName), neturl.PathEscape(packageVersion))) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s/yank", url, neturl.PathEscape(packageName), neturl.PathEscape(packageVersion))). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var status cargo_router.StatusResponse @@ -353,8 +353,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { t.Run("Unyank", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "PUT", fmt.Sprintf("%s/%s/%s/unyank", url, neturl.PathEscape(packageName), neturl.PathEscape(packageVersion))) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "PUT", fmt.Sprintf("%s/%s/%s/unyank", url, neturl.PathEscape(packageName), neturl.PathEscape(packageVersion))). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var status cargo_router.StatusResponse diff --git a/tests/integration/api_packages_chef_test.go b/tests/integration/api_packages_chef_test.go index 7f55a84f0919..4123c7216c4d 100644 --- a/tests/integration/api_packages_chef_test.go +++ b/tests/integration/api_packages_chef_test.go @@ -93,7 +93,7 @@ nwIDAQAB defer tests.PrintCurrentTest(t)() req := NewRequest(t, "POST", "/dummy") - u, err := auth.Verify(req, nil, nil, nil) + u, err := auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.NoError(t, err) }) @@ -101,9 +101,9 @@ nwIDAQAB t.Run("NotExistingUser", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "POST", "/dummy") - req.Header.Set("X-Ops-Userid", "not-existing-user") - u, err := auth.Verify(req, nil, nil, nil) + req := NewRequest(t, "POST", "/dummy"). + SetHeader("X-Ops-Userid", "not-existing-user") + u, err := auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) }) @@ -111,14 +111,14 @@ nwIDAQAB t.Run("Timestamp", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "POST", "/dummy") - req.Header.Set("X-Ops-Userid", user.Name) - u, err := auth.Verify(req, nil, nil, nil) + req := NewRequest(t, "POST", "/dummy"). + SetHeader("X-Ops-Userid", user.Name) + u, err := auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) - req.Header.Set("X-Ops-Timestamp", "2023-01-01T00:00:00Z") - u, err = auth.Verify(req, nil, nil, nil) + req.SetHeader("X-Ops-Timestamp", "2023-01-01T00:00:00Z") + u, err = auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) }) @@ -126,30 +126,30 @@ nwIDAQAB t.Run("SigningVersion", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "POST", "/dummy") - req.Header.Set("X-Ops-Userid", user.Name) - req.Header.Set("X-Ops-Timestamp", time.Now().UTC().Format(time.RFC3339)) - u, err := auth.Verify(req, nil, nil, nil) + req := NewRequest(t, "POST", "/dummy"). + SetHeader("X-Ops-Userid", user.Name). + SetHeader("X-Ops-Timestamp", time.Now().UTC().Format(time.RFC3339)) + u, err := auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) - req.Header.Set("X-Ops-Sign", "version=none") - u, err = auth.Verify(req, nil, nil, nil) + req.SetHeader("X-Ops-Sign", "version=none") + u, err = auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) - req.Header.Set("X-Ops-Sign", "version=1.4") - u, err = auth.Verify(req, nil, nil, nil) + req.SetHeader("X-Ops-Sign", "version=1.4") + u, err = auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) - req.Header.Set("X-Ops-Sign", "version=1.0;algorithm=sha2") - u, err = auth.Verify(req, nil, nil, nil) + req.SetHeader("X-Ops-Sign", "version=1.0;algorithm=sha2") + u, err = auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) - req.Header.Set("X-Ops-Sign", "version=1.0;algorithm=sha256") - u, err = auth.Verify(req, nil, nil, nil) + req.SetHeader("X-Ops-Sign", "version=1.0;algorithm=sha256") + u, err = auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) }) @@ -159,17 +159,18 @@ nwIDAQAB ts := time.Now().UTC().Format(time.RFC3339) - req := NewRequest(t, "POST", "/dummy") - req.Header.Set("X-Ops-Userid", user.Name) - req.Header.Set("X-Ops-Timestamp", ts) - req.Header.Set("X-Ops-Sign", "version=1.0;algorithm=sha1") - req.Header.Set("X-Ops-Content-Hash", "unused") - req.Header.Set("X-Ops-Authorization-4", "dummy") - u, err := auth.Verify(req, nil, nil, nil) + req := NewRequest(t, "POST", "/dummy"). + SetHeader("X-Ops-Userid", user.Name). + SetHeader("X-Ops-Timestamp", ts). + SetHeader("X-Ops-Sign", "version=1.0;algorithm=sha1"). + SetHeader("X-Ops-Content-Hash", "unused"). + SetHeader("X-Ops-Authorization-4", "dummy") + u, err := auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) - signRequest := func(t *testing.T, req *http.Request, version string) { + signRequest := func(t *testing.T, rw *RequestWrapper, version string) { + req := rw.Request username := req.Header.Get("X-Ops-Userid") if version != "1.0" && version != "1.3" { sum := sha1.Sum([]byte(username)) @@ -255,7 +256,7 @@ nwIDAQAB defer tests.PrintCurrentTest(t)() signRequest(t, req, v) - u, err = auth.Verify(req, nil, nil, nil) + u, err = auth.Verify(req.Request, nil, nil, nil) assert.NotNil(t, u) assert.NoError(t, err) }) @@ -291,9 +292,9 @@ nwIDAQAB zw.Close() mpw.Close() - req := NewRequestWithBody(t, "POST", root+"/cookbooks", &body) - req.Header.Add("Content-Type", mpw.FormDataContentType()) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "POST", root+"/cookbooks", &body). + SetHeader("Content-Type", mpw.FormDataContentType()). + AddBasicAuth(user.Name) MakeRequest(t, req, expectedStatus) } @@ -394,8 +395,8 @@ nwIDAQAB } for i, c := range cases { - req := NewRequest(t, "GET", fmt.Sprintf("%s/search?q=%s&start=%d&items=%d", root, c.Query, c.Start, c.Items)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/search?q=%s&start=%d&items=%d", root, c.Query, c.Start, c.Items)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result Result @@ -445,8 +446,8 @@ nwIDAQAB } for i, c := range cases { - req := NewRequest(t, "GET", fmt.Sprintf("%s/cookbooks?start=%d&items=%d&sort=%s", root, c.Start, c.Items, c.Sort)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/cookbooks?start=%d&items=%d&sort=%s", root, c.Start, c.Items, c.Sort)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result Result @@ -533,8 +534,8 @@ nwIDAQAB req := NewRequest(t, "DELETE", fmt.Sprintf("%s/cookbooks/%s/versions/%s", root, packageName, "1.0.2")) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/cookbooks/%s/versions/%s", root, packageName, "1.0.2")) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/cookbooks/%s/versions/%s", root, packageName, "1.0.2")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeChef, packageName, "1.0.2") @@ -548,8 +549,8 @@ nwIDAQAB req := NewRequest(t, "DELETE", fmt.Sprintf("%s/cookbooks/%s", root, packageName)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/cookbooks/%s", root, packageName)) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/cookbooks/%s", root, packageName)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeChef) diff --git a/tests/integration/api_packages_composer_test.go b/tests/integration/api_packages_composer_test.go index 896462d9a9fd..6e0d2eee1b34 100644 --- a/tests/integration/api_packages_composer_test.go +++ b/tests/integration/api_packages_composer_test.go @@ -59,8 +59,8 @@ func TestPackageComposer(t *testing.T) { t.Run("ServiceIndex", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/packages.json", url)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/packages.json", url)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result composer.ServiceIndexResponse @@ -75,8 +75,8 @@ func TestPackageComposer(t *testing.T) { t.Run("MissingVersion", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) }) @@ -85,8 +85,8 @@ func TestPackageComposer(t *testing.T) { uploadURL := url + "?version=" + packageVersion - req := NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeComposer) @@ -110,8 +110,8 @@ func TestPackageComposer(t *testing.T) { assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) - req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) }) }) @@ -128,8 +128,8 @@ func TestPackageComposer(t *testing.T) { assert.NoError(t, err) assert.Len(t, pfs, 1) - req := NewRequest(t, "GET", fmt.Sprintf("%s/files/%s/%s/%s", url, neturl.PathEscape(packageName), neturl.PathEscape(pvs[0].LowerVersion), neturl.PathEscape(pfs[0].LowerName))) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/files/%s/%s/%s", url, neturl.PathEscape(packageName), neturl.PathEscape(pvs[0].LowerVersion), neturl.PathEscape(pfs[0].LowerName))). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, content, resp.Body.Bytes()) @@ -162,8 +162,8 @@ func TestPackageComposer(t *testing.T) { } for i, c := range cases { - req := NewRequest(t, "GET", fmt.Sprintf("%s/search.json?q=%s&type=%s&page=%d&per_page=%d", url, c.Query, c.Type, c.Page, c.PerPage)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/search.json?q=%s&type=%s&page=%d&per_page=%d", url, c.Query, c.Type, c.Page, c.PerPage)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result composer.SearchResultResponse @@ -177,8 +177,8 @@ func TestPackageComposer(t *testing.T) { t.Run("EnumeratePackages", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", url+"/list.json") - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", url+"/list.json"). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result map[string][]string @@ -193,8 +193,8 @@ func TestPackageComposer(t *testing.T) { t.Run("PackageMetadata", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/p2/%s/%s.json", url, vendorName, projectName)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/p2/%s/%s.json", url, vendorName, projectName)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result composer.PackageMetadataResponse diff --git a/tests/integration/api_packages_conan_test.go b/tests/integration/api_packages_conan_test.go index ab128bf4a5eb..a25713f039ff 100644 --- a/tests/integration/api_packages_conan_test.go +++ b/tests/integration/api_packages_conan_test.go @@ -62,11 +62,6 @@ const ( CC=gcc-10` ) -func addTokenAuthHeader(request *http.Request, token string) *http.Request { - request.Header.Set("Authorization", token) - return request -} - func buildConanfileContent(name, version string) string { return `from conans import ConanFile, CMake, tools @@ -90,16 +85,16 @@ func uploadConanPackageV1(t *testing.T, baseURL, token, name, version, user, cha recipeURL := fmt.Sprintf("%s/v1/conans/%s/%s/%s/%s", baseURL, name, version, user, channel) - req := NewRequest(t, "GET", recipeURL) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "GET", recipeURL). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("%s/digest", recipeURL)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", fmt.Sprintf("%s/digest", recipeURL)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("%s/download_urls", recipeURL)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", fmt.Sprintf("%s/download_urls", recipeURL)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) req = NewRequest(t, "POST", fmt.Sprintf("%s/upload_urls", recipeURL)) @@ -108,8 +103,7 @@ func uploadConanPackageV1(t *testing.T, baseURL, token, name, version, user, cha req = NewRequestWithJSON(t, "POST", fmt.Sprintf("%s/upload_urls", recipeURL), map[string]int64{ conanfileName: int64(len(contentConanfile)), "removed.txt": 0, - }) - req = addTokenAuthHeader(req, token) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) uploadURLs := make(map[string]string) @@ -121,22 +115,22 @@ func uploadConanPackageV1(t *testing.T, baseURL, token, name, version, user, cha uploadURL := uploadURLs[conanfileName] assert.NotEmpty(t, uploadURL) - req = NewRequestWithBody(t, "PUT", uploadURL, strings.NewReader(contentConanfile)) - req = addTokenAuthHeader(req, token) + req = NewRequestWithBody(t, "PUT", uploadURL, strings.NewReader(contentConanfile)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) packageURL := fmt.Sprintf("%s/packages/%s", recipeURL, conanPackageReference) - req = NewRequest(t, "GET", packageURL) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", packageURL). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("%s/digest", packageURL)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", fmt.Sprintf("%s/digest", packageURL)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("%s/download_urls", packageURL)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", fmt.Sprintf("%s/download_urls", packageURL)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) req = NewRequest(t, "POST", fmt.Sprintf("%s/upload_urls", packageURL)) @@ -145,8 +139,7 @@ func uploadConanPackageV1(t *testing.T, baseURL, token, name, version, user, cha req = NewRequestWithJSON(t, "POST", fmt.Sprintf("%s/upload_urls", packageURL), map[string]int64{ conaninfoName: int64(len(contentConaninfo)), "removed.txt": 0, - }) - req = addTokenAuthHeader(req, token) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) uploadURLs = make(map[string]string) @@ -158,8 +151,8 @@ func uploadConanPackageV1(t *testing.T, baseURL, token, name, version, user, cha uploadURL = uploadURLs[conaninfoName] assert.NotEmpty(t, uploadURL) - req = NewRequestWithBody(t, "PUT", uploadURL, strings.NewReader(contentConaninfo)) - req = addTokenAuthHeader(req, token) + req = NewRequestWithBody(t, "PUT", uploadURL, strings.NewReader(contentConaninfo)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) } @@ -168,12 +161,12 @@ func uploadConanPackageV2(t *testing.T, baseURL, token, name, version, user, cha recipeURL := fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s", baseURL, name, version, user, channel, recipeRevision) - req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/files/%s", recipeURL, conanfileName), strings.NewReader(contentConanfile)) - req = addTokenAuthHeader(req, token) + req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/files/%s", recipeURL, conanfileName), strings.NewReader(contentConanfile)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) - req = NewRequest(t, "GET", fmt.Sprintf("%s/files", recipeURL)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", fmt.Sprintf("%s/files", recipeURL)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var list *struct { @@ -185,16 +178,16 @@ func uploadConanPackageV2(t *testing.T, baseURL, token, name, version, user, cha packageURL := fmt.Sprintf("%s/packages/%s/revisions/%s", recipeURL, conanPackageReference, packageRevision) - req = NewRequest(t, "GET", fmt.Sprintf("%s/files", packageURL)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", fmt.Sprintf("%s/files", packageURL)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/files/%s", packageURL, conaninfoName), strings.NewReader(contentConaninfo)) - req = addTokenAuthHeader(req, token) + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/files/%s", packageURL, conaninfoName), strings.NewReader(contentConaninfo)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) - req = NewRequest(t, "GET", fmt.Sprintf("%s/files", packageURL)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", fmt.Sprintf("%s/files", packageURL)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) list = nil @@ -235,21 +228,19 @@ func TestPackageConan(t *testing.T) { t.Run("Authenticate", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/v1/users/authenticate", url)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/v1/users/authenticate", url)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) - body := resp.Body.String() - assert.NotEmpty(t, body) - - token = fmt.Sprintf("Bearer %s", body) + token = resp.Body.String() + assert.NotEmpty(t, token) }) t.Run("CheckCredentials", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/v1/users/check_credentials", url)) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "GET", fmt.Sprintf("%s/v1/users/check_credentials", url)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) }) @@ -440,8 +431,7 @@ func TestPackageConan(t *testing.T) { req := NewRequestWithJSON(t, "POST", fmt.Sprintf("%s/v1/conans/%s/%s/%s/%s/packages/delete", url, name, version1, user1, c.Channel), map[string][]string{ "package_ids": c.References, - }) - req = addTokenAuthHeader(req, token) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) references, err = conan_model.GetPackageReferences(db.DefaultContext, user.ID, rref) @@ -466,8 +456,8 @@ func TestPackageConan(t *testing.T) { assert.NoError(t, err) assert.NotEmpty(t, revisions) - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/v1/conans/%s/%s/%s/%s", url, name, version1, user1, c.Channel)) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/v1/conans/%s/%s/%s/%s", url, name, version1, user1, c.Channel)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) revisions, err = conan_model.GetRecipeRevisions(db.DefaultContext, user.ID, rref) @@ -493,8 +483,8 @@ func TestPackageConan(t *testing.T) { t.Run("Authenticate", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/v2/users/authenticate", url)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/v2/users/authenticate", url)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) body := resp.Body.String() @@ -506,8 +496,8 @@ func TestPackageConan(t *testing.T) { t.Run("CheckCredentials", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/v2/users/check_credentials", url)) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "GET", fmt.Sprintf("%s/v2/users/check_credentials", url)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) }) @@ -672,14 +662,14 @@ func TestPackageConan(t *testing.T) { checkPackageRevisionCount(2) - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s/packages/%s/revisions/%s", url, name, version1, user1, channel1, revision1, conanPackageReference, revision1)) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s/packages/%s/revisions/%s", url, name, version1, user1, channel1, revision1, conanPackageReference, revision1)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) checkPackageRevisionCount(1) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s/packages/%s", url, name, version1, user1, channel1, revision1, conanPackageReference)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s/packages/%s", url, name, version1, user1, channel1, revision1, conanPackageReference)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) checkPackageRevisionCount(0) @@ -688,8 +678,8 @@ func TestPackageConan(t *testing.T) { checkPackageReferenceCount(1) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s/packages", url, name, version1, user1, channel1, revision2)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s/packages", url, name, version1, user1, channel1, revision2)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) checkPackageReferenceCount(0) @@ -708,14 +698,14 @@ func TestPackageConan(t *testing.T) { checkRecipeRevisionCount(2) - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s", url, name, version1, user1, channel1, revision1)) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s", url, name, version1, user1, channel1, revision1)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) checkRecipeRevisionCount(1) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s", url, name, version1, user1, channel1)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s", url, name, version1, user1, channel1)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) checkRecipeRevisionCount(0) diff --git a/tests/integration/api_packages_conda_test.go b/tests/integration/api_packages_conda_test.go index daa7dca55fa2..bb269e82d603 100644 --- a/tests/integration/api_packages_conda_test.go +++ b/tests/integration/api_packages_conda_test.go @@ -66,12 +66,12 @@ func TestPackageConda(t *testing.T) { req := NewRequestWithBody(t, "PUT", root+"/"+filename, bytes.NewReader(buf.Bytes())) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", root+"/"+filename, bytes.NewReader(buf.Bytes())) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", root+"/"+filename, bytes.NewReader(buf.Bytes())). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - req = NewRequestWithBody(t, "PUT", root+"/"+filename, bytes.NewReader(buf.Bytes())) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", root+"/"+filename, bytes.NewReader(buf.Bytes())). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeConda) @@ -107,12 +107,12 @@ func TestPackageConda(t *testing.T) { req := NewRequestWithBody(t, "PUT", root+"/"+channel+"/"+filename, bytes.NewReader(buf.Bytes())) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", root+"/"+channel+"/"+filename, bytes.NewReader(buf.Bytes())) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", root+"/"+channel+"/"+filename, bytes.NewReader(buf.Bytes())). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - req = NewRequestWithBody(t, "PUT", root+"/"+channel+"/"+filename, bytes.NewReader(buf.Bytes())) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", root+"/"+channel+"/"+filename, bytes.NewReader(buf.Bytes())). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeConda) diff --git a/tests/integration/api_packages_container_test.go b/tests/integration/api_packages_container_test.go index 93b4ff46241a..f32d33888b40 100644 --- a/tests/integration/api_packages_container_test.go +++ b/tests/integration/api_packages_container_test.go @@ -103,8 +103,8 @@ func TestPackageContainer(t *testing.T) { anonymousToken = fmt.Sprintf("Bearer %s", tokenResponse.Token) - req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)) - addTokenAuthHeader(req, anonymousToken) + req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)). + AddTokenAuth(anonymousToken) MakeRequest(t, req, http.StatusOK) }) @@ -116,8 +116,8 @@ func TestPackageContainer(t *testing.T) { assert.ElementsMatch(t, authenticate, resp.Header().Values("WWW-Authenticate")) - req = NewRequest(t, "GET", fmt.Sprintf("%sv2/token", setting.AppURL)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%sv2/token", setting.AppURL)). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) tokenResponse := &TokenResponse{} @@ -127,8 +127,8 @@ func TestPackageContainer(t *testing.T) { userToken = fmt.Sprintf("Bearer %s", tokenResponse.Token) - req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusOK) }) }) @@ -136,8 +136,8 @@ func TestPackageContainer(t *testing.T) { t.Run("DetermineSupport", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "registry/2.0", resp.Header().Get("Docker-Distribution-Api-Version")) }) @@ -149,16 +149,16 @@ func TestPackageContainer(t *testing.T) { t.Run("UploadBlob/Monolithic", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)) - addTokenAuthHeader(req, anonymousToken) + req := NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)). + AddTokenAuth(anonymousToken) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "POST", fmt.Sprintf("%s/blobs/uploads?digest=%s", url, unknownDigest), bytes.NewReader(blobContent)) - addTokenAuthHeader(req, userToken) + req = NewRequestWithBody(t, "POST", fmt.Sprintf("%s/blobs/uploads?digest=%s", url, unknownDigest), bytes.NewReader(blobContent)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusBadRequest) - req = NewRequestWithBody(t, "POST", fmt.Sprintf("%s/blobs/uploads?digest=%s", url, blobDigest), bytes.NewReader(blobContent)) - addTokenAuthHeader(req, userToken) + req = NewRequestWithBody(t, "POST", fmt.Sprintf("%s/blobs/uploads?digest=%s", url, blobDigest), bytes.NewReader(blobContent)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusCreated) assert.Equal(t, fmt.Sprintf("/v2/%s/%s/blobs/%s", user.Name, image, blobDigest), resp.Header().Get("Location")) @@ -179,8 +179,8 @@ func TestPackageContainer(t *testing.T) { t.Run("UploadBlob/Chunked", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusAccepted) uuid := resp.Header().Get("Docker-Upload-Uuid") @@ -193,18 +193,17 @@ func TestPackageContainer(t *testing.T) { uploadURL := resp.Header().Get("Location") assert.NotEmpty(t, uploadURL) - req = NewRequestWithBody(t, "PATCH", setting.AppURL+uploadURL[1:]+"000", bytes.NewReader(blobContent)) - addTokenAuthHeader(req, userToken) + req = NewRequestWithBody(t, "PATCH", setting.AppURL+uploadURL[1:]+"000", bytes.NewReader(blobContent)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) - req = NewRequestWithBody(t, "PATCH", setting.AppURL+uploadURL[1:], bytes.NewReader(blobContent)) - addTokenAuthHeader(req, userToken) - - req.Header.Set("Content-Range", "1-10") + req = NewRequestWithBody(t, "PATCH", setting.AppURL+uploadURL[1:], bytes.NewReader(blobContent)). + AddTokenAuth(userToken). + SetHeader("Content-Range", "1-10") MakeRequest(t, req, http.StatusRequestedRangeNotSatisfiable) contentRange := fmt.Sprintf("0-%d", len(blobContent)-1) - req.Header.Set("Content-Range", contentRange) + req.SetHeader("Content-Range", contentRange) resp = MakeRequest(t, req, http.StatusAccepted) assert.Equal(t, uuid, resp.Header().Get("Docker-Upload-Uuid")) @@ -212,8 +211,8 @@ func TestPackageContainer(t *testing.T) { uploadURL = resp.Header().Get("Location") - req = NewRequest(t, "GET", setting.AppURL+uploadURL[1:]) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "GET", setting.AppURL+uploadURL[1:]). + AddTokenAuth(userToken) resp = MakeRequest(t, req, http.StatusNoContent) assert.Equal(t, uuid, resp.Header().Get("Docker-Upload-Uuid")) @@ -223,8 +222,8 @@ func TestPackageContainer(t *testing.T) { assert.NoError(t, err) assert.EqualValues(t, len(blobContent), pbu.BytesReceived) - req = NewRequest(t, "PUT", fmt.Sprintf("%s?digest=%s", setting.AppURL+uploadURL[1:], blobDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "PUT", fmt.Sprintf("%s?digest=%s", setting.AppURL+uploadURL[1:], blobDigest)). + AddTokenAuth(userToken) resp = MakeRequest(t, req, http.StatusCreated) assert.Equal(t, fmt.Sprintf("/v2/%s/%s/blobs/%s", user.Name, image, blobDigest), resp.Header().Get("Location")) @@ -233,8 +232,8 @@ func TestPackageContainer(t *testing.T) { t.Run("Cancel", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusAccepted) uuid := resp.Header().Get("Docker-Upload-Uuid") @@ -243,19 +242,19 @@ func TestPackageContainer(t *testing.T) { uploadURL := resp.Header().Get("Location") assert.NotEmpty(t, uploadURL) - req = NewRequest(t, "GET", setting.AppURL+uploadURL[1:]) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "GET", setting.AppURL+uploadURL[1:]). + AddTokenAuth(userToken) resp = MakeRequest(t, req, http.StatusNoContent) assert.Equal(t, uuid, resp.Header().Get("Docker-Upload-Uuid")) assert.Equal(t, "0-0", resp.Header().Get("Range")) - req = NewRequest(t, "DELETE", setting.AppURL+uploadURL[1:]) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "DELETE", setting.AppURL+uploadURL[1:]). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "GET", setting.AppURL+uploadURL[1:]) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "GET", setting.AppURL+uploadURL[1:]). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) }) }) @@ -264,31 +263,31 @@ func TestPackageContainer(t *testing.T) { defer tests.PrintCurrentTest(t)() privateBlobDigest := "sha256:6ccce4863b70f258d691f59609d31b4502e1ba5199942d3bc5d35d17a4ce771d" - req := NewRequestWithBody(t, "POST", fmt.Sprintf("%sv2/%s/%s/blobs/uploads?digest=%s", setting.AppURL, privateUser.Name, image, privateBlobDigest), strings.NewReader("gitea")) - req = AddBasicAuthHeader(req, privateUser.Name) + req := NewRequestWithBody(t, "POST", fmt.Sprintf("%sv2/%s/%s/blobs/uploads?digest=%s", setting.AppURL, privateUser.Name, image, privateBlobDigest), strings.NewReader("gitea")). + AddBasicAuth(privateUser.Name) MakeRequest(t, req, http.StatusCreated) - req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s", url, unknownDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s", url, unknownDigest)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusAccepted) - req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s", url, privateBlobDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s", url, privateBlobDigest)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusAccepted) - req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s", url, blobDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s", url, blobDigest)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusCreated) assert.Equal(t, fmt.Sprintf("/v2/%s/%s/blobs/%s", user.Name, image, blobDigest), resp.Header().Get("Location")) assert.Equal(t, blobDigest, resp.Header().Get("Docker-Content-Digest")) - req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s&from=%s", url, unknownDigest, "unknown/image")) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s&from=%s", url, unknownDigest, "unknown/image")). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusAccepted) - req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s&from=%s/%s", url, blobDigest, user.Name, image)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s&from=%s/%s", url, blobDigest, user.Name, image)). + AddTokenAuth(userToken) resp = MakeRequest(t, req, http.StatusCreated) assert.Equal(t, fmt.Sprintf("/v2/%s/%s/blobs/%s", user.Name, image, blobDigest), resp.Header().Get("Location")) @@ -300,18 +299,18 @@ func TestPackageContainer(t *testing.T) { t.Run("UploadManifest", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "POST", fmt.Sprintf("%s/blobs/uploads?digest=%s", url, configDigest), strings.NewReader(configContent)) - addTokenAuthHeader(req, userToken) + req := NewRequestWithBody(t, "POST", fmt.Sprintf("%s/blobs/uploads?digest=%s", url, configDigest), strings.NewReader(configContent)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusCreated) - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, tag), strings.NewReader(manifestContent)) - addTokenAuthHeader(req, anonymousToken) - req.Header.Set("Content-Type", "application/vnd.docker.distribution.manifest.v2+json") + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, tag), strings.NewReader(manifestContent)). + AddTokenAuth(anonymousToken). + SetHeader("Content-Type", "application/vnd.docker.distribution.manifest.v2+json") MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, tag), strings.NewReader(manifestContent)) - addTokenAuthHeader(req, userToken) - req.Header.Set("Content-Type", "application/vnd.docker.distribution.manifest.v2+json") + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, tag), strings.NewReader(manifestContent)). + AddTokenAuth(userToken). + SetHeader("Content-Type", "application/vnd.docker.distribution.manifest.v2+json") resp := MakeRequest(t, req, http.StatusCreated) assert.Equal(t, manifestDigest, resp.Header().Get("Docker-Content-Digest")) @@ -353,8 +352,8 @@ func TestPackageContainer(t *testing.T) { } } - req = NewRequest(t, "GET", fmt.Sprintf("%s/manifests/%s", url, tag)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "GET", fmt.Sprintf("%s/manifests/%s", url, tag)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusOK) pv, err = packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, tag) @@ -362,9 +361,9 @@ func TestPackageContainer(t *testing.T) { assert.EqualValues(t, 1, pv.DownloadCount) // Overwrite existing tag should keep the download count - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, tag), strings.NewReader(manifestContent)) - addTokenAuthHeader(req, userToken) - req.Header.Set("Content-Type", oci.MediaTypeImageManifest) + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, tag), strings.NewReader(manifestContent)). + AddTokenAuth(userToken). + SetHeader("Content-Type", oci.MediaTypeImageManifest) MakeRequest(t, req, http.StatusCreated) pv, err = packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, tag) @@ -375,12 +374,12 @@ func TestPackageContainer(t *testing.T) { t.Run("HeadManifest", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/unknown-tag", url)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/unknown-tag", url)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/%s", url, tag)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/%s", url, tag)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, fmt.Sprintf("%d", len(manifestContent)), resp.Header().Get("Content-Length")) @@ -390,12 +389,12 @@ func TestPackageContainer(t *testing.T) { t.Run("GetManifest", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/manifests/unknown-tag", url)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "GET", fmt.Sprintf("%s/manifests/unknown-tag", url)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("%s/manifests/%s", url, tag)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "GET", fmt.Sprintf("%s/manifests/%s", url, tag)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, fmt.Sprintf("%d", len(manifestContent)), resp.Header().Get("Content-Length")) @@ -409,15 +408,15 @@ func TestPackageContainer(t *testing.T) { t.Run("UploadUntaggedManifest", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, untaggedManifestDigest), strings.NewReader(untaggedManifestContent)) - addTokenAuthHeader(req, userToken) - req.Header.Set("Content-Type", oci.MediaTypeImageManifest) + req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, untaggedManifestDigest), strings.NewReader(untaggedManifestContent)). + AddTokenAuth(userToken). + SetHeader("Content-Type", oci.MediaTypeImageManifest) resp := MakeRequest(t, req, http.StatusCreated) assert.Equal(t, untaggedManifestDigest, resp.Header().Get("Docker-Content-Digest")) - req = NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/%s", url, untaggedManifestDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/%s", url, untaggedManifestDigest)). + AddTokenAuth(userToken) resp = MakeRequest(t, req, http.StatusOK) assert.Equal(t, fmt.Sprintf("%d", len(untaggedManifestContent)), resp.Header().Get("Content-Length")) @@ -449,9 +448,9 @@ func TestPackageContainer(t *testing.T) { t.Run("UploadIndexManifest", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, multiTag), strings.NewReader(indexManifestContent)) - addTokenAuthHeader(req, userToken) - req.Header.Set("Content-Type", oci.MediaTypeImageIndex) + req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, multiTag), strings.NewReader(indexManifestContent)). + AddTokenAuth(userToken). + SetHeader("Content-Type", oci.MediaTypeImageIndex) resp := MakeRequest(t, req, http.StatusCreated) assert.Equal(t, indexManifestDigest, resp.Header().Get("Docker-Content-Digest")) @@ -498,31 +497,31 @@ func TestPackageContainer(t *testing.T) { t.Run("HeadBlob", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "HEAD", fmt.Sprintf("%s/blobs/%s", url, unknownDigest)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "HEAD", fmt.Sprintf("%s/blobs/%s", url, unknownDigest)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "HEAD", fmt.Sprintf("%s/blobs/%s", url, blobDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "HEAD", fmt.Sprintf("%s/blobs/%s", url, blobDigest)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, fmt.Sprintf("%d", len(blobContent)), resp.Header().Get("Content-Length")) assert.Equal(t, blobDigest, resp.Header().Get("Docker-Content-Digest")) - req = NewRequest(t, "HEAD", fmt.Sprintf("%s/blobs/%s", url, blobDigest)) - addTokenAuthHeader(req, anonymousToken) + req = NewRequest(t, "HEAD", fmt.Sprintf("%s/blobs/%s", url, blobDigest)). + AddTokenAuth(anonymousToken) MakeRequest(t, req, http.StatusOK) }) t.Run("GetBlob", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/blobs/%s", url, unknownDigest)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "GET", fmt.Sprintf("%s/blobs/%s", url, unknownDigest)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("%s/blobs/%s", url, blobDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "GET", fmt.Sprintf("%s/blobs/%s", url, blobDigest)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, fmt.Sprintf("%d", len(blobContent)), resp.Header().Get("Content-Length")) @@ -566,8 +565,8 @@ func TestPackageContainer(t *testing.T) { } for _, c := range cases { - req := NewRequest(t, "GET", c.URL) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "GET", c.URL). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusOK) type TagList struct { @@ -583,7 +582,8 @@ func TestPackageContainer(t *testing.T) { assert.Equal(t, c.ExpectedLink, resp.Header().Get("Link")) } - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s?type=container&q=%s&token=%s", user.Name, image, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s?type=container&q=%s", user.Name, image)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiPackages []*api.Package @@ -595,36 +595,36 @@ func TestPackageContainer(t *testing.T) { t.Run("Blob", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/blobs/%s", url, blobDigest)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/blobs/%s", url, blobDigest)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusAccepted) - req = NewRequest(t, "HEAD", fmt.Sprintf("%s/blobs/%s", url, blobDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "HEAD", fmt.Sprintf("%s/blobs/%s", url, blobDigest)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) }) t.Run("ManifestByDigest", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/manifests/%s", url, untaggedManifestDigest)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/manifests/%s", url, untaggedManifestDigest)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusAccepted) - req = NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/%s", url, untaggedManifestDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/%s", url, untaggedManifestDigest)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) }) t.Run("ManifestByTag", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/manifests/%s", url, multiTag)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/manifests/%s", url, multiTag)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusAccepted) - req = NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/%s", url, multiTag)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/%s", url, multiTag)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) }) }) @@ -647,8 +647,8 @@ func TestPackageContainer(t *testing.T) { go func() { defer wg.Done() - req := NewRequestWithBody(t, "POST", fmt.Sprintf("%s/blobs/uploads?digest=%s", url, digest), bytes.NewReader(content)) - addTokenAuthHeader(req, userToken) + req := NewRequestWithBody(t, "POST", fmt.Sprintf("%s/blobs/uploads?digest=%s", url, digest), bytes.NewReader(content)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusCreated) assert.Equal(t, digest, resp.Header().Get("Docker-Content-Digest")) @@ -664,8 +664,8 @@ func TestPackageContainer(t *testing.T) { return func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%sv2/_catalog", setting.AppURL)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "GET", fmt.Sprintf("%sv2/_catalog", setting.AppURL)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusOK) type RepositoryList struct { diff --git a/tests/integration/api_packages_cran_test.go b/tests/integration/api_packages_cran_test.go index 9ef23226db07..d307e87d4e0f 100644 --- a/tests/integration/api_packages_cran_test.go +++ b/tests/integration/api_packages_cran_test.go @@ -74,15 +74,13 @@ func TestPackageCran(t *testing.T) { req = NewRequestWithBody(t, "PUT", uploadURL, createArchive( "dummy.txt", []byte{}, - )) - req = AddBasicAuthHeader(req, user.Name) + )).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) req = NewRequestWithBody(t, "PUT", uploadURL, createArchive( "package/DESCRIPTION", createDescription(packageName, packageVersion), - )) - req = AddBasicAuthHeader(req, user.Name) + )).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeCran) @@ -105,24 +103,23 @@ func TestPackageCran(t *testing.T) { req = NewRequestWithBody(t, "PUT", uploadURL, createArchive( "package/DESCRIPTION", createDescription(packageName, packageVersion), - )) - req = AddBasicAuthHeader(req, user.Name) + )).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) }) t.Run("Download", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/src/contrib/%s_%s.tar.gz", url, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/src/contrib/%s_%s.tar.gz", url, packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) }) t.Run("Enumerate", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", url+"/src/contrib/PACKAGES") - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", url+"/src/contrib/PACKAGES"). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Contains(t, resp.Header().Get("Content-Type"), "text/plain") @@ -131,8 +128,8 @@ func TestPackageCran(t *testing.T) { assert.Contains(t, body, fmt.Sprintf("Package: %s", packageName)) assert.Contains(t, body, fmt.Sprintf("Version: %s", packageVersion)) - req = NewRequest(t, "GET", url+"/src/contrib/PACKAGES.gz") - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", url+"/src/contrib/PACKAGES.gz"). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) assert.Contains(t, resp.Header().Get("Content-Type"), "application/x-gzip") @@ -160,15 +157,13 @@ func TestPackageCran(t *testing.T) { req = NewRequestWithBody(t, "PUT", uploadURL, createArchive( "dummy.txt", []byte{}, - )) - req = AddBasicAuthHeader(req, user.Name) + )).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) req = NewRequestWithBody(t, "PUT", uploadURL+"?platform=&rversion=", createArchive( "package/DESCRIPTION", createDescription(packageName, packageVersion), - )) - req = AddBasicAuthHeader(req, user.Name) + )).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) uploadURL += "?platform=windows&rversion=4.2" @@ -176,8 +171,7 @@ func TestPackageCran(t *testing.T) { req = NewRequestWithBody(t, "PUT", uploadURL, createArchive( "package/DESCRIPTION", createDescription(packageName, packageVersion), - )) - req = AddBasicAuthHeader(req, user.Name) + )).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeCran) @@ -191,8 +185,7 @@ func TestPackageCran(t *testing.T) { req = NewRequestWithBody(t, "PUT", uploadURL, createArchive( "package/DESCRIPTION", createDescription(packageName, packageVersion), - )) - req = AddBasicAuthHeader(req, user.Name) + )).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) }) @@ -210,8 +203,8 @@ func TestPackageCran(t *testing.T) { } for _, c := range cases { - req := NewRequest(t, "GET", fmt.Sprintf("%s/bin/%s/contrib/%s/%s_%s.zip", url, c.Platform, c.RVersion, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/bin/%s/contrib/%s/%s_%s.zip", url, c.Platform, c.RVersion, packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, c.ExpectedStatus) } }) @@ -222,8 +215,8 @@ func TestPackageCran(t *testing.T) { req := NewRequest(t, "GET", url+"/bin/windows/contrib/4.1/PACKAGES") MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", url+"/bin/windows/contrib/4.2/PACKAGES") - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", url+"/bin/windows/contrib/4.2/PACKAGES"). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Contains(t, resp.Header().Get("Content-Type"), "text/plain") @@ -232,8 +225,8 @@ func TestPackageCran(t *testing.T) { assert.Contains(t, body, fmt.Sprintf("Package: %s", packageName)) assert.Contains(t, body, fmt.Sprintf("Version: %s", packageVersion)) - req = NewRequest(t, "GET", url+"/bin/windows/contrib/4.2/PACKAGES.gz") - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", url+"/bin/windows/contrib/4.2/PACKAGES.gz"). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) assert.Contains(t, resp.Header().Get("Content-Type"), "application/x-gzip") diff --git a/tests/integration/api_packages_debian_test.go b/tests/integration/api_packages_debian_test.go index 6c43f72a71da..05979fccb546 100644 --- a/tests/integration/api_packages_debian_test.go +++ b/tests/integration/api_packages_debian_test.go @@ -89,16 +89,16 @@ func TestPackageDebian(t *testing.T) { req := NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader([]byte{})) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader([]byte{})) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader([]byte{})). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) - req = NewRequestWithBody(t, "PUT", uploadURL, createArchive("", "", "")) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", uploadURL, createArchive("", "", "")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) - req = NewRequestWithBody(t, "PUT", uploadURL, createArchive(packageName, packageVersion, architecture)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", uploadURL, createArchive(packageName, packageVersion, architecture)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeDebian, packageName, packageVersion) @@ -145,8 +145,8 @@ func TestPackageDebian(t *testing.T) { return seen }) - req = NewRequestWithBody(t, "PUT", uploadURL, createArchive(packageName, packageVersion, architecture)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", uploadURL, createArchive(packageName, packageVersion, architecture)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) }) @@ -162,8 +162,8 @@ func TestPackageDebian(t *testing.T) { t.Run("Packages", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", uploadURL, createArchive(packageName, packageVersion2, architecture)) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", uploadURL, createArchive(packageName, packageVersion2, architecture)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) url := fmt.Sprintf("%s/dists/%s/%s/binary-%s/Packages", rootURL, distribution, component, architecture) @@ -243,12 +243,12 @@ func TestPackageDebian(t *testing.T) { req := NewRequest(t, "DELETE", fmt.Sprintf("%s/pool/%s/%s/%s/%s/%s", rootURL, distribution, component, packageName, packageVersion, architecture)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/pool/%s/%s/%s/%s/%s", rootURL, distribution, component, packageName, packageVersion, architecture)) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/pool/%s/%s/%s/%s/%s", rootURL, distribution, component, packageName, packageVersion, architecture)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/pool/%s/%s/%s/%s/%s", rootURL, distribution, component, packageName, packageVersion2, architecture)) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/pool/%s/%s/%s/%s/%s", rootURL, distribution, component, packageName, packageVersion2, architecture)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) req = NewRequest(t, "GET", fmt.Sprintf("%s/dists/%s/%s/binary-%s/Packages", rootURL, distribution, component, architecture)) diff --git a/tests/integration/api_packages_generic_test.go b/tests/integration/api_packages_generic_test.go index f5d8def0f337..93525ac4b19c 100644 --- a/tests/integration/api_packages_generic_test.go +++ b/tests/integration/api_packages_generic_test.go @@ -35,8 +35,8 @@ func TestPackageGeneric(t *testing.T) { t.Run("Upload", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", url+"/"+filename, bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url+"/"+filename, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) @@ -62,16 +62,16 @@ func TestPackageGeneric(t *testing.T) { t.Run("Exists", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", url+"/"+filename, bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url+"/"+filename, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) }) t.Run("Additional", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", url+"/dummy.bin", bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url+"/dummy.bin", bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) // Check deduplication @@ -84,16 +84,16 @@ func TestPackageGeneric(t *testing.T) { t.Run("InvalidParameter", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", fmt.Sprintf("/api/packages/%s/generic/%s/%s/%s", user.Name, "invalid+package name", packageVersion, filename), bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", fmt.Sprintf("/api/packages/%s/generic/%s/%s/%s", user.Name, "invalid+package name", packageVersion, filename), bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("/api/packages/%s/generic/%s/%s/%s", user.Name, packageName, "%20test ", filename), bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("/api/packages/%s/generic/%s/%s/%s", user.Name, packageName, "%20test ", filename), bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("/api/packages/%s/generic/%s/%s/%s", user.Name, packageName, packageVersion, "inval+id.na me"), bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("/api/packages/%s/generic/%s/%s/%s", user.Name, packageName, packageVersion, "inval+id.na me"), bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) }) }) @@ -187,15 +187,15 @@ func TestPackageGeneric(t *testing.T) { req := NewRequest(t, "DELETE", url+"/"+filename) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", url+"/"+filename) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", url+"/"+filename). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) req = NewRequest(t, "GET", url+"/"+filename) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "DELETE", url+"/"+filename) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", url+"/"+filename). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) @@ -205,8 +205,8 @@ func TestPackageGeneric(t *testing.T) { t.Run("RemovesVersion", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req = NewRequest(t, "DELETE", url+"/dummy.bin") - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", url+"/dummy.bin"). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) @@ -218,15 +218,15 @@ func TestPackageGeneric(t *testing.T) { t.Run("Version", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", url+"/"+filename, bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url+"/"+filename, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) req = NewRequest(t, "DELETE", url) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", url) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", url). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) @@ -236,8 +236,8 @@ func TestPackageGeneric(t *testing.T) { req = NewRequest(t, "GET", url+"/"+filename) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "DELETE", url) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", url). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) }) }) diff --git a/tests/integration/api_packages_goproxy_test.go b/tests/integration/api_packages_goproxy_test.go index 08c1ca54f140..dab9fefc5e17 100644 --- a/tests/integration/api_packages_goproxy_test.go +++ b/tests/integration/api_packages_goproxy_test.go @@ -51,16 +51,16 @@ func TestPackageGo(t *testing.T) { req := NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) content = createArchive(map[string][]byte{ packageName + "@" + packageVersion + "/go.mod": []byte(goModContent), }) - req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGo) @@ -83,8 +83,8 @@ func TestPackageGo(t *testing.T) { assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) - req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) time.Sleep(time.Second) @@ -93,8 +93,8 @@ func TestPackageGo(t *testing.T) { packageName + "@" + packageVersion2 + "/go.mod": []byte(goModContent), }) - req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) }) diff --git a/tests/integration/api_packages_helm_test.go b/tests/integration/api_packages_helm_test.go index 4f61452071b6..76285add1179 100644 --- a/tests/integration/api_packages_helm_test.go +++ b/tests/integration/api_packages_helm_test.go @@ -68,8 +68,8 @@ dependencies: uploadURL := url + "/api/charts" - req := NewRequestWithBody(t, "POST", uploadURL, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "POST", uploadURL, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeHelm) @@ -93,8 +93,8 @@ dependencies: assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) - req = NewRequestWithBody(t, "POST", uploadURL, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "POST", uploadURL, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) }) @@ -110,8 +110,8 @@ dependencies: checkDownloadCount(0) - req := NewRequest(t, "GET", fmt.Sprintf("%s/%s", url, filename)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/%s", url, filename)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, content, resp.Body.Bytes()) @@ -122,8 +122,8 @@ dependencies: t.Run("Index", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/index.yaml", url)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/index.yaml", url)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) type ChartVersion struct { diff --git a/tests/integration/api_packages_maven_test.go b/tests/integration/api_packages_maven_test.go index c78024563f4d..c7ed554a9d7f 100644 --- a/tests/integration/api_packages_maven_test.go +++ b/tests/integration/api_packages_maven_test.go @@ -35,8 +35,8 @@ func TestPackageMaven(t *testing.T) { filename := fmt.Sprintf("%s-%s.jar", packageName, packageVersion) putFile := func(t *testing.T, path, content string, expectedStatus int) { - req := NewRequestWithBody(t, "PUT", root+path, strings.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", root+path, strings.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, expectedStatus) } @@ -84,14 +84,14 @@ func TestPackageMaven(t *testing.T) { t.Run("Download", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "HEAD", fmt.Sprintf("%s/%s/%s", root, packageVersion, filename)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "HEAD", fmt.Sprintf("%s/%s/%s", root, packageVersion, filename)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) checkHeaders(t, resp.Header(), "application/java-archive", 4) - req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s", root, packageVersion, filename)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s", root, packageVersion, filename)). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) checkHeaders(t, resp.Header(), "application/java-archive", 4) @@ -165,14 +165,14 @@ func TestPackageMaven(t *testing.T) { t.Run("DownloadPOM", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "HEAD", fmt.Sprintf("%s/%s/%s.pom", root, packageVersion, filename)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "HEAD", fmt.Sprintf("%s/%s/%s.pom", root, packageVersion, filename)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) checkHeaders(t, resp.Header(), "text/xml", int64(len(pomContent))) - req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s.pom", root, packageVersion, filename)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s.pom", root, packageVersion, filename)). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) checkHeaders(t, resp.Header(), "text/xml", int64(len(pomContent))) @@ -188,8 +188,8 @@ func TestPackageMaven(t *testing.T) { t.Run("DownloadChecksums", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/1.2.3/%s", root, filename)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/1.2.3/%s", root, filename)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) for key, checksum := range map[string]string{ @@ -198,8 +198,8 @@ func TestPackageMaven(t *testing.T) { "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", "sha512": "ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff", } { - req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s.%s", root, packageVersion, filename, key)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s.%s", root, packageVersion, filename, key)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, checksum, resp.Body.String()) @@ -209,8 +209,8 @@ func TestPackageMaven(t *testing.T) { t.Run("DownloadMetadata", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", root+"/maven-metadata.xml") - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", root+"/maven-metadata.xml"). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) expectedMetadata := `` + "\ncom.giteatest-project1.0.11.0.11.0.1" @@ -225,8 +225,8 @@ func TestPackageMaven(t *testing.T) { "sha256": "3f48322f81c4b2c3bb8649ae1e5c9801476162b520e1c2734ac06b2c06143208", "sha512": "cb075aa2e2ef1a83cdc14dd1e08c505b72d633399b39e73a21f00f0deecb39a3e2c79f157c1163f8a3854828750706e0dec3a0f5e4778e91f8ec2cf351a855f2", } { - req := NewRequest(t, "GET", fmt.Sprintf("%s/maven-metadata.xml.%s", root, key)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/maven-metadata.xml.%s", root, key)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, checksum, resp.Body.String()) diff --git a/tests/integration/api_packages_npm_test.go b/tests/integration/api_packages_npm_test.go index bd3bfeeff067..9c888972ffb4 100644 --- a/tests/integration/api_packages_npm_test.go +++ b/tests/integration/api_packages_npm_test.go @@ -87,8 +87,8 @@ func TestPackageNpm(t *testing.T) { t.Run("Upload", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", root, strings.NewReader(buildUpload(packageVersion))) - req = addTokenAuthHeader(req, token) + req := NewRequestWithBody(t, "PUT", root, strings.NewReader(buildUpload(packageVersion))). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) @@ -119,23 +119,23 @@ func TestPackageNpm(t *testing.T) { t.Run("UploadExists", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", root, strings.NewReader(buildUpload(packageVersion))) - req = addTokenAuthHeader(req, token) + req := NewRequestWithBody(t, "PUT", root, strings.NewReader(buildUpload(packageVersion))). + AddTokenAuth(token) MakeRequest(t, req, http.StatusConflict) }) t.Run("Download", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/-/%s/%s", root, packageVersion, filename)) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "GET", fmt.Sprintf("%s/-/%s/%s", root, packageVersion, filename)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) b, _ := base64.StdEncoding.DecodeString(data) assert.Equal(t, b, resp.Body.Bytes()) - req = NewRequest(t, "GET", fmt.Sprintf("%s/-/%s", root, filename)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", fmt.Sprintf("%s/-/%s", root, filename)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) assert.Equal(t, b, resp.Body.Bytes()) @@ -149,12 +149,12 @@ func TestPackageNpm(t *testing.T) { t.Run("PackageMetadata", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/packages/%s/npm/%s", user.Name, "does-not-exist")) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "GET", fmt.Sprintf("/api/packages/%s/npm/%s", user.Name, "does-not-exist")). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", root) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", root). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var result npm.PackageMetadata @@ -184,8 +184,8 @@ func TestPackageNpm(t *testing.T) { defer tests.PrintCurrentTest(t)() test := func(t *testing.T, status int, tag, version string) { - req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/%s", tagsRoot, tag), strings.NewReader(`"`+version+`"`)) - req = addTokenAuthHeader(req, token) + req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/%s", tagsRoot, tag), strings.NewReader(`"`+version+`"`)). + AddTokenAuth(token) MakeRequest(t, req, status) } @@ -199,8 +199,8 @@ func TestPackageNpm(t *testing.T) { t.Run("ListTags", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", tagsRoot) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "GET", tagsRoot). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var result map[string]string @@ -216,8 +216,8 @@ func TestPackageNpm(t *testing.T) { t.Run("PackageMetadataDistTags", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", root) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "GET", root). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var result npm.PackageMetadata @@ -234,8 +234,8 @@ func TestPackageNpm(t *testing.T) { defer tests.PrintCurrentTest(t)() test := func(t *testing.T, status int, tag string) { - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/%s", tagsRoot, tag)) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/%s", tagsRoot, tag)). + AddTokenAuth(token) MakeRequest(t, req, status) } @@ -279,15 +279,15 @@ func TestPackageNpm(t *testing.T) { t.Run("Delete", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", root, strings.NewReader(buildUpload(packageVersion+"-dummy"))) - req = addTokenAuthHeader(req, token) + req := NewRequestWithBody(t, "PUT", root, strings.NewReader(buildUpload(packageVersion+"-dummy"))). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) req = NewRequest(t, "PUT", root+"/-rev/dummy") MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "PUT", root+"/-rev/dummy") - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "PUT", root+"/-rev/dummy"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) t.Run("Version", func(t *testing.T) { @@ -300,8 +300,8 @@ func TestPackageNpm(t *testing.T) { req := NewRequest(t, "DELETE", fmt.Sprintf("%s/-/%s/%s/-rev/dummy", root, packageVersion, filename)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/-/%s/%s/-rev/dummy", root, packageVersion, filename)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/-/%s/%s/-rev/dummy", root, packageVersion, filename)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) pvs, err = packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) @@ -319,8 +319,8 @@ func TestPackageNpm(t *testing.T) { req := NewRequest(t, "DELETE", root+"/-rev/dummy") MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", root+"/-rev/dummy") - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "DELETE", root+"/-rev/dummy"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) pvs, err = packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) diff --git a/tests/integration/api_packages_nuget_test.go b/tests/integration/api_packages_nuget_test.go index 04c2fbce0ec5..20dafd5cc799 100644 --- a/tests/integration/api_packages_nuget_test.go +++ b/tests/integration/api_packages_nuget_test.go @@ -31,9 +31,8 @@ import ( "github.com/stretchr/testify/assert" ) -func addNuGetAPIKeyHeader(request *http.Request, token string) *http.Request { - request.Header.Set("X-NuGet-ApiKey", token) - return request +func addNuGetAPIKeyHeader(req *RequestWrapper, token string) { + req.SetHeader("X-NuGet-ApiKey", token) } func decodeXML(t testing.TB, resp *httptest.ResponseRecorder, v any) { @@ -141,9 +140,9 @@ func TestPackageNuGet(t *testing.T) { req := NewRequest(t, "GET", url) if c.UseBasicAuth { - req = AddBasicAuthHeader(req, user.Name) + req.AddBasicAuth(user.Name) } else if c.UseTokenAuth { - req = addNuGetAPIKeyHeader(req, token) + addNuGetAPIKeyHeader(req, token) } resp := MakeRequest(t, req, http.StatusOK) @@ -178,9 +177,9 @@ func TestPackageNuGet(t *testing.T) { req := NewRequest(t, "GET", fmt.Sprintf("%s/index.json", url)) if c.UseBasicAuth { - req = AddBasicAuthHeader(req, user.Name) + req.AddBasicAuth(user.Name) } else if c.UseTokenAuth { - req = addNuGetAPIKeyHeader(req, token) + addNuGetAPIKeyHeader(req, token) } resp := MakeRequest(t, req, http.StatusOK) @@ -219,8 +218,8 @@ func TestPackageNuGet(t *testing.T) { t.Run("DependencyPackage", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNuGet) @@ -244,8 +243,8 @@ func TestPackageNuGet(t *testing.T) { assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) - req = NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) }) @@ -278,16 +277,16 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) return &buf } - req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage("unknown-package", "SymbolsPackage")) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage("unknown-package", "SymbolsPackage")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage(packageName, "DummyPackage")) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage(packageName, "DummyPackage")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage(packageName, "SymbolsPackage")) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage(packageName, "SymbolsPackage")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNuGet) @@ -330,8 +329,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) } } - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage(packageName, "SymbolsPackage")) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage(packageName, "SymbolsPackage")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) }) }) @@ -348,16 +347,16 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) checkDownloadCount(0) - req := NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/%s/%s.%s.nupkg", url, packageName, packageVersion, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/%s/%s.%s.nupkg", url, packageName, packageVersion, packageName, packageVersion)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, content, resp.Body.Bytes()) checkDownloadCount(1) - req = NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/%s/%s.%s.snupkg", url, packageName, packageVersion, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/%s/%s.%s.snupkg", url, packageName, packageVersion, packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) checkDownloadCount(1) @@ -368,12 +367,12 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) req := NewRequest(t, "GET", fmt.Sprintf("%s/symbols/%s/%sFFFFFFFF/gitea.pdb", url, symbolFilename, symbolID)) MakeRequest(t, req, http.StatusBadRequest) - req = NewRequest(t, "GET", fmt.Sprintf("%s/symbols/%s/%sFFFFFFFF/%s", url, symbolFilename, "00000000000000000000000000000000", symbolFilename)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/symbols/%s/%sFFFFFFFF/%s", url, symbolFilename, "00000000000000000000000000000000", symbolFilename)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("%s/symbols/%s/%sFFFFffff/%s", url, symbolFilename, symbolID, symbolFilename)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/symbols/%s/%sFFFFffff/%s", url, symbolFilename, symbolID, symbolFilename)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) checkDownloadCount(1) @@ -414,8 +413,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) {"test", 1, 10, 1, 0}, } - req := NewRequestWithBody(t, "PUT", url, createPackage(packageName, "1.0.99")) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url, createPackage(packageName, "1.0.99")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) t.Run("v2", func(t *testing.T) { @@ -423,8 +422,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) defer tests.PrintCurrentTest(t)() for i, c := range cases { - req := NewRequest(t, "GET", fmt.Sprintf("%s/Search()?searchTerm='%s'&$skip=%d&$top=%d", url, c.Query, c.Skip, c.Take)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/Search()?searchTerm='%s'&$skip=%d&$top=%d", url, c.Query, c.Skip, c.Take)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result FeedResponse @@ -433,8 +432,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) assert.Equal(t, c.ExpectedTotal, result.Count, "case %d: unexpected total hits", i) assert.Len(t, result.Entries, c.ExpectedResults, "case %d: unexpected result count", i) - req = NewRequest(t, "GET", fmt.Sprintf("%s/Search()/$count?searchTerm='%s'&$skip=%d&$top=%d", url, c.Query, c.Skip, c.Take)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/Search()/$count?searchTerm='%s'&$skip=%d&$top=%d", url, c.Query, c.Skip, c.Take)). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) assert.Equal(t, strconv.FormatInt(c.ExpectedTotal, 10), resp.Body.String(), "case %d: unexpected total hits", i) @@ -445,8 +444,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) defer tests.PrintCurrentTest(t)() for i, c := range cases { - req := NewRequest(t, "GET", fmt.Sprintf("%s/Packages()?$filter=substringof('%s',tolower(Id))&$skip=%d&$top=%d", url, c.Query, c.Skip, c.Take)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/Packages()?$filter=substringof('%s',tolower(Id))&$skip=%d&$top=%d", url, c.Query, c.Skip, c.Take)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result FeedResponse @@ -455,8 +454,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) assert.Equal(t, c.ExpectedTotal, result.Count, "case %d: unexpected total hits", i) assert.Len(t, result.Entries, c.ExpectedResults, "case %d: unexpected result count", i) - req = NewRequest(t, "GET", fmt.Sprintf("%s/Packages()/$count?$filter=substringof('%s',tolower(Id))&$skip=%d&$top=%d", url, c.Query, c.Skip, c.Take)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/Packages()/$count?$filter=substringof('%s',tolower(Id))&$skip=%d&$top=%d", url, c.Query, c.Skip, c.Take)). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) assert.Equal(t, strconv.FormatInt(c.ExpectedTotal, 10), resp.Body.String(), "case %d: unexpected total hits", i) @@ -464,8 +463,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) }) t.Run("Next", func(t *testing.T) { - req := NewRequest(t, "GET", fmt.Sprintf("%s/Search()?searchTerm='test'&$skip=0&$top=1", url)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/Search()?searchTerm='test'&$skip=0&$top=1", url)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result FeedResponse @@ -479,8 +478,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) defer tests.PrintCurrentTest(t)() for i, c := range cases { - req := NewRequest(t, "GET", fmt.Sprintf("%s/query?q=%s&skip=%d&take=%d", url, c.Query, c.Skip, c.Take)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/query?q=%s&skip=%d&take=%d", url, c.Query, c.Skip, c.Take)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result nuget.SearchResultResponse @@ -493,12 +492,12 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) t.Run("EnforceGrouped", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", url, createPackage(packageName+".dummy", "1.0.0")) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url, createPackage(packageName+".dummy", "1.0.0")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - req = NewRequest(t, "GET", fmt.Sprintf("%s/query?q=%s", url, packageName)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/query?q=%s", url, packageName)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result nuget.SearchResultResponse @@ -514,14 +513,14 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) } } - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s", url, packageName+".dummy", "1.0.0")) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s", url, packageName+".dummy", "1.0.0")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) }) }) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s", url, packageName, "1.0.99")) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s", url, packageName, "1.0.99")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) }) @@ -533,8 +532,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) t.Run("RegistrationIndex", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/registration/%s/index.json", url, packageName)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/registration/%s/index.json", url, packageName)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result nuget.RegistrationIndexResponse @@ -560,8 +559,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) t.Run("v2", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/Packages(Id='%s',Version='%s')", url, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/Packages(Id='%s',Version='%s')", url, packageName, packageVersion)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result FeedEntry @@ -577,8 +576,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) t.Run("v3", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/registration/%s/%s.json", url, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/registration/%s/%s.json", url, packageName, packageVersion)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result nuget.RegistrationLeafResponse @@ -595,8 +594,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) t.Run("v2", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/FindPackagesById()?id='%s'&$top=1", url, packageName)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/FindPackagesById()?id='%s'&$top=1", url, packageName)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result FeedResponse @@ -606,8 +605,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) assert.Equal(t, packageVersion, result.Entries[0].Properties.Version) assert.Condition(t, containsOneNextLink(t, result.Links)) - req = NewRequest(t, "GET", fmt.Sprintf("%s/FindPackagesById()/$count?id='%s'", url, packageName)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/FindPackagesById()/$count?id='%s'", url, packageName)). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Body.String()) @@ -616,8 +615,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) t.Run("v3", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/index.json", url, packageName)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/index.json", url, packageName)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result nuget.PackageVersionsResponse @@ -631,8 +630,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) t.Run("Delete", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s", url, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s", url, packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNuGet) @@ -643,20 +642,20 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) t.Run("DownloadNotExists", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/%s/%s.%s.nupkg", url, packageName, packageVersion, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/%s/%s.%s.nupkg", url, packageName, packageVersion, packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/%s/%s.%s.snupkg", url, packageName, packageVersion, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/%s/%s.%s.snupkg", url, packageName, packageVersion, packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) }) t.Run("DeleteNotExists", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/package/%s/%s", url, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/package/%s/%s", url, packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) }) } diff --git a/tests/integration/api_packages_pub_test.go b/tests/integration/api_packages_pub_test.go index 6e9d8742f472..11da894ddf3d 100644 --- a/tests/integration/api_packages_pub_test.go +++ b/tests/integration/api_packages_pub_test.go @@ -66,8 +66,8 @@ description: ` + packageDescription req := NewRequest(t, "GET", uploadURL) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "GET", uploadURL) - addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", uploadURL). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) type UploadRequest struct { @@ -88,16 +88,16 @@ description: ` + packageDescription _ = writer.Close() - req := NewRequestWithBody(t, "POST", url, body) - req.Header.Add("Content-Type", writer.FormDataContentType()) - addTokenAuthHeader(req, token) + req := NewRequestWithBody(t, "POST", url, body). + SetHeader("Content-Type", writer.FormDataContentType()). + AddTokenAuth(token) return MakeRequest(t, req, expectedStatus) } resp = uploadFile(t, result.URL, content, http.StatusNoContent) - req = NewRequest(t, "GET", resp.Header().Get("Location")) - addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", resp.Header().Get("Location")). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypePub) diff --git a/tests/integration/api_packages_pypi_test.go b/tests/integration/api_packages_pypi_test.go index 76013b79c840..a090b31e2064 100644 --- a/tests/integration/api_packages_pypi_test.go +++ b/tests/integration/api_packages_pypi_test.go @@ -54,9 +54,9 @@ func TestPackagePyPI(t *testing.T) { _ = writer.Close() - req := NewRequestWithBody(t, "POST", root, body) - req.Header.Add("Content-Type", writer.FormDataContentType()) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "POST", root, body). + SetHeader("Content-Type", writer.FormDataContentType()). + AddBasicAuth(user.Name) MakeRequest(t, req, expectedStatus) } @@ -137,8 +137,8 @@ func TestPackagePyPI(t *testing.T) { defer tests.PrintCurrentTest(t)() downloadFile := func(filename string) { - req := NewRequest(t, "GET", fmt.Sprintf("%s/files/%s/%s/%s", root, packageName, packageVersion, filename)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/files/%s/%s/%s", root, packageName, packageVersion, filename)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, []byte(content), resp.Body.Bytes()) @@ -156,8 +156,8 @@ func TestPackagePyPI(t *testing.T) { t.Run("PackageMetadata", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/simple/%s", root, packageName)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/simple/%s", root, packageName)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) htmlDoc := NewHTMLParser(t, resp.Body) diff --git a/tests/integration/api_packages_rpm_test.go b/tests/integration/api_packages_rpm_test.go index 6d3b0688f2a3..caf6f86381e2 100644 --- a/tests/integration/api_packages_rpm_test.go +++ b/tests/integration/api_packages_rpm_test.go @@ -105,8 +105,8 @@ gpgkey=%sapi/packages/%s/rpm/repository.key`, user.Name, user.Name, setting.AppN req := NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRpm) @@ -130,8 +130,8 @@ gpgkey=%sapi/packages/%s/rpm/repository.key`, user.Name, user.Name, setting.AppN assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) - req = NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) }) @@ -404,16 +404,16 @@ gpgkey=%sapi/packages/%s/rpm/repository.key`, user.Name, user.Name, setting.AppN req := NewRequest(t, "DELETE", fmt.Sprintf("%s/package/%s/%s/%s", rootURL, packageName, packageVersion, packageArchitecture)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/package/%s/%s/%s", rootURL, packageName, packageVersion, packageArchitecture)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/package/%s/%s/%s", rootURL, packageName, packageVersion, packageArchitecture)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRpm) assert.NoError(t, err) assert.Empty(t, pvs) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/package/%s/%s/%s", rootURL, packageName, packageVersion, packageArchitecture)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/package/%s/%s/%s", rootURL, packageName, packageVersion, packageArchitecture)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) }) } diff --git a/tests/integration/api_packages_rubygems_test.go b/tests/integration/api_packages_rubygems_test.go index a3df143209a5..5670731c4926 100644 --- a/tests/integration/api_packages_rubygems_test.go +++ b/tests/integration/api_packages_rubygems_test.go @@ -115,8 +115,8 @@ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`) root := fmt.Sprintf("/api/packages/%s/rubygems", user.Name) uploadFile := func(t *testing.T, expectedStatus int) { - req := NewRequestWithBody(t, "POST", fmt.Sprintf("%s/api/v1/gems", root), bytes.NewReader(gemContent)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "POST", fmt.Sprintf("%s/api/v1/gems", root), bytes.NewReader(gemContent)). + AddBasicAuth(user.Name) MakeRequest(t, req, expectedStatus) } @@ -156,8 +156,8 @@ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`) t.Run("Download", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/gems/%s", root, packageFilename)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/gems/%s", root, packageFilename)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, gemContent, resp.Body.Bytes()) @@ -171,8 +171,8 @@ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`) t.Run("DownloadGemspec", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/quick/Marshal.4.8/%sspec.rz", root, packageFilename)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/quick/Marshal.4.8/%sspec.rz", root, packageFilename)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) b, _ := base64.StdEncoding.DecodeString(`eJxi4Si1EndPzbWyCi5ITc5My0xOLMnMz2M8zMIRLeGpxGWsZ6RnzGbF5hqSyempxJWeWZKayGbN @@ -191,8 +191,8 @@ gAAAAP//MS06Gw==`) defer tests.PrintCurrentTest(t)() enumeratePackages := func(t *testing.T, endpoint string, expectedContent []byte) { - req := NewRequest(t, "GET", fmt.Sprintf("%s/%s", root, endpoint)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/%s", root, endpoint)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, expectedContent, resp.Body.Bytes()) @@ -215,9 +215,9 @@ gAAAAP//MS06Gw==`) writer.WriteField("version", packageVersion) writer.Close() - req := NewRequestWithBody(t, "DELETE", fmt.Sprintf("%s/api/v1/gems/yank", root), &body) - req.Header.Add("Content-Type", writer.FormDataContentType()) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "DELETE", fmt.Sprintf("%s/api/v1/gems/yank", root), &body). + SetHeader("Content-Type", writer.FormDataContentType()). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRubyGems) diff --git a/tests/integration/api_packages_swift_test.go b/tests/integration/api_packages_swift_test.go index a3035ea60485..7d4ff954e227 100644 --- a/tests/integration/api_packages_swift_test.go +++ b/tests/integration/api_packages_swift_test.go @@ -62,9 +62,9 @@ func TestPackageSwift(t *testing.T) { assert.Equal(t, "application/problem+json", resp.Header().Get("Content-Type")) } - req := NewRequestWithBody(t, "PUT", url+"/scope/package/1.0.0", strings.NewReader("")) - req = AddBasicAuthHeader(req, user.Name) - req.Header.Add("Accept", "application/unknown") + req := NewRequestWithBody(t, "PUT", url+"/scope/package/1.0.0", strings.NewReader("")). + AddBasicAuth(user.Name). + SetHeader("Accept", "application/unknown") resp := MakeRequest(t, req, http.StatusBadRequest) assert.Equal(t, "1", resp.Header().Get("Content-Version")) @@ -87,10 +87,10 @@ func TestPackageSwift(t *testing.T) { mpw.Close() - req := NewRequestWithBody(t, "PUT", url, &body) - req.Header.Add("Content-Type", mpw.FormDataContentType()) - req.Header.Add("Accept", swift_router.AcceptJSON) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url, &body). + SetHeader("Content-Type", mpw.FormDataContentType()). + SetHeader("Accept", swift_router.AcceptJSON). + AddBasicAuth(user.Name) MakeRequest(t, req, expectedStatus) } @@ -106,8 +106,8 @@ func TestPackageSwift(t *testing.T) { } for _, triple := range []string{"/sc_ope/package/1.0.0", "/scope/pack~age/1.0.0", "/scope/package/1_0.0"} { - req := NewRequestWithBody(t, "PUT", url+triple, bytes.NewReader([]byte{})) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url+triple, bytes.NewReader([]byte{})). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusBadRequest) assert.Equal(t, "1", resp.Header().Get("Content-Version")) @@ -168,9 +168,9 @@ func TestPackageSwift(t *testing.T) { t.Run("Download", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s/%s.zip", url, packageScope, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) - req.Header.Add("Accept", swift_router.AcceptZip) + req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s/%s.zip", url, packageScope, packageName, packageVersion)). + AddBasicAuth(user.Name). + SetHeader("Accept", swift_router.AcceptZip) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("Content-Version")) @@ -188,9 +188,9 @@ func TestPackageSwift(t *testing.T) { t.Run("EnumeratePackageVersions", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s", url, packageScope, packageName)) - req = AddBasicAuthHeader(req, user.Name) - req.Header.Add("Accept", swift_router.AcceptJSON) + req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s", url, packageScope, packageName)). + AddBasicAuth(user.Name). + SetHeader("Accept", swift_router.AcceptJSON) resp := MakeRequest(t, req, http.StatusOK) versionURL := setting.AppURL + url[1:] + fmt.Sprintf("/%s/%s/%s", packageScope, packageName, packageVersion) @@ -207,8 +207,8 @@ func TestPackageSwift(t *testing.T) { assert.Contains(t, result.Releases, packageVersion) assert.Equal(t, versionURL, result.Releases[packageVersion].URL) - req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s.json", url, packageScope, packageName)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s.json", url, packageScope, packageName)). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) assert.Equal(t, body, resp.Body.String()) @@ -217,9 +217,9 @@ func TestPackageSwift(t *testing.T) { t.Run("PackageVersionMetadata", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s/%s", url, packageScope, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) - req.Header.Add("Accept", swift_router.AcceptJSON) + req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s/%s", url, packageScope, packageName, packageVersion)). + AddBasicAuth(user.Name). + SetHeader("Accept", swift_router.AcceptJSON) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("Content-Version")) @@ -249,8 +249,8 @@ func TestPackageSwift(t *testing.T) { assert.Equal(t, "Swift", result.Metadata.ProgrammingLanguage.Name) assert.Equal(t, packageAuthor, result.Metadata.Author.GivenName) - req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s/%s.json", url, packageScope, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s/%s.json", url, packageScope, packageName, packageVersion)). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) assert.Equal(t, body, resp.Body.String()) @@ -262,9 +262,9 @@ func TestPackageSwift(t *testing.T) { t.Run("Default", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", manifestURL) - req = AddBasicAuthHeader(req, user.Name) - req.Header.Add("Accept", swift_router.AcceptSwift) + req := NewRequest(t, "GET", manifestURL). + AddBasicAuth(user.Name). + SetHeader("Accept", swift_router.AcceptSwift) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("Content-Version")) @@ -275,24 +275,24 @@ func TestPackageSwift(t *testing.T) { t.Run("DifferentVersion", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", manifestURL+"?swift-version=5.6") - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", manifestURL+"?swift-version=5.6"). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("Content-Version")) assert.Equal(t, "text/x-swift", resp.Header().Get("Content-Type")) assert.Equal(t, contentManifest2, resp.Body.String()) - req = NewRequest(t, "GET", manifestURL+"?swift-version=5.6.0") - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", manifestURL+"?swift-version=5.6.0"). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) }) t.Run("Redirect", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", manifestURL+"?swift-version=1.0") - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", manifestURL+"?swift-version=1.0"). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusSeeOther) assert.Equal(t, "1", resp.Header().Get("Content-Version")) @@ -303,8 +303,8 @@ func TestPackageSwift(t *testing.T) { t.Run("LookupPackageIdentifiers", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", url+"/identifiers") - req.Header.Add("Accept", swift_router.AcceptJSON) + req := NewRequest(t, "GET", url+"/identifiers"). + SetHeader("Accept", swift_router.AcceptJSON) resp := MakeRequest(t, req, http.StatusBadRequest) assert.Equal(t, "1", resp.Header().Get("Content-Version")) @@ -313,8 +313,8 @@ func TestPackageSwift(t *testing.T) { req = NewRequest(t, "GET", url+"/identifiers?url=https://unknown.host/") MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", url+"/identifiers?url="+packageRepositoryURL) - req.Header.Add("Accept", swift_router.AcceptJSON) + req = NewRequest(t, "GET", url+"/identifiers?url="+packageRepositoryURL). + SetHeader("Accept", swift_router.AcceptJSON) resp = MakeRequest(t, req, http.StatusOK) var result *swift_router.LookupPackageIdentifiersResponse diff --git a/tests/integration/api_packages_test.go b/tests/integration/api_packages_test.go index e530b2c1ad79..8c981566b602 100644 --- a/tests/integration/api_packages_test.go +++ b/tests/integration/api_packages_test.go @@ -41,14 +41,15 @@ func TestPackageAPI(t *testing.T) { filename := "file.bin" url := fmt.Sprintf("/api/packages/%s/generic/%s/%s/%s", user.Name, packageName, packageVersion, filename) - req := NewRequestWithBody(t, "PUT", url, bytes.NewReader([]byte{})) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url, bytes.NewReader([]byte{})). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) t.Run("ListPackages", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s?token=%s", user.Name, tokenReadPackage)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s", user.Name)). + AddTokenAuth(tokenReadPackage) resp := MakeRequest(t, req, http.StatusOK) var apiPackages []*api.Package @@ -65,10 +66,12 @@ func TestPackageAPI(t *testing.T) { t.Run("GetPackage", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenReadPackage) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenReadPackage) resp := MakeRequest(t, req, http.StatusOK) var p *api.Package @@ -87,7 +90,8 @@ func TestPackageAPI(t *testing.T) { assert.NoError(t, err) // no repository link - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenReadPackage) resp := MakeRequest(t, req, http.StatusOK) var ap1 *api.Package @@ -97,7 +101,8 @@ func TestPackageAPI(t *testing.T) { // link to public repository assert.NoError(t, packages_model.SetRepositoryLink(db.DefaultContext, p.ID, 1)) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenReadPackage) resp = MakeRequest(t, req, http.StatusOK) var ap2 *api.Package @@ -108,7 +113,8 @@ func TestPackageAPI(t *testing.T) { // link to private repository assert.NoError(t, packages_model.SetRepositoryLink(db.DefaultContext, p.ID, 2)) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenReadPackage) resp = MakeRequest(t, req, http.StatusOK) var ap3 *api.Package @@ -122,10 +128,12 @@ func TestPackageAPI(t *testing.T) { t.Run("ListPackageFiles", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s/files?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s/files", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenReadPackage) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s/files?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s/files", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenReadPackage) resp := MakeRequest(t, req, http.StatusOK) var files []*api.PackageFile @@ -143,10 +151,12 @@ func TestPackageAPI(t *testing.T) { t.Run("DeletePackage", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenDeletePackage)) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenDeletePackage) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenDeletePackage)) + req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenDeletePackage) MakeRequest(t, req, http.StatusNoContent) }) } @@ -170,7 +180,7 @@ func TestPackageAccess(t *testing.T) { url := fmt.Sprintf("/api/packages/%s/generic/test-package/1.0/%s.bin", owner.Name, filename) req := NewRequestWithBody(t, "PUT", url, bytes.NewReader([]byte{1})) if doer != nil { - AddBasicAuthHeader(req, doer.Name) + req.AddBasicAuth(doer.Name) } MakeRequest(t, req, expectedStatus) } @@ -179,7 +189,7 @@ func TestPackageAccess(t *testing.T) { url := fmt.Sprintf("/api/packages/%s/generic/test-package/1.0/admin.bin", owner.Name) req := NewRequest(t, "GET", url) if doer != nil { - AddBasicAuthHeader(req, doer.Name) + req.AddBasicAuth(doer.Name) } MakeRequest(t, req, expectedStatus) } @@ -374,7 +384,8 @@ func TestPackageAccess(t *testing.T) { {limitedOrgNoMember, http.StatusOK}, {publicOrgNoMember, http.StatusOK}, } { - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s?token=%s", target.Owner.Name, tokenReadPackage)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s", target.Owner.Name)). + AddTokenAuth(tokenReadPackage) MakeRequest(t, req, target.ExpectedStatus) } }) @@ -396,8 +407,8 @@ func TestPackageQuota(t *testing.T) { uploadPackage := func(doer *user_model.User, version string, expectedStatus int) { url := fmt.Sprintf("/api/packages/%s/generic/test-package/%s/file.bin", user.Name, version) - req := NewRequestWithBody(t, "PUT", url, bytes.NewReader([]byte{1})) - AddBasicAuthHeader(req, doer.Name) + req := NewRequestWithBody(t, "PUT", url, bytes.NewReader([]byte{1})). + AddBasicAuth(doer.Name) MakeRequest(t, req, expectedStatus) } @@ -424,8 +435,8 @@ func TestPackageQuota(t *testing.T) { uploadBlob := func(doer *user_model.User, data string, expectedStatus int) { url := fmt.Sprintf("/v2/%s/quota-test/blobs/uploads?digest=sha256:%x", user.Name, sha256.Sum256([]byte(data))) - req := NewRequestWithBody(t, "POST", url, strings.NewReader(data)) - AddBasicAuthHeader(req, doer.Name) + req := NewRequestWithBody(t, "POST", url, strings.NewReader(data)). + AddBasicAuth(doer.Name) MakeRequest(t, req, expectedStatus) } @@ -454,18 +465,18 @@ func TestPackageCleanup(t *testing.T) { // Upload and delete a generic package and upload a container blob data, _ := util.CryptoRandomBytes(5) url := fmt.Sprintf("/api/packages/%s/generic/cleanup-test/1.1.1/file.bin", user.Name) - req := NewRequestWithBody(t, "PUT", url, bytes.NewReader(data)) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url, bytes.NewReader(data)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - req = NewRequest(t, "DELETE", url) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", url). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) data, _ = util.CryptoRandomBytes(5) url = fmt.Sprintf("/v2/%s/cleanup-test/blobs/uploads?digest=sha256:%x", user.Name, sha256.Sum256(data)) - req = NewRequestWithBody(t, "POST", url, bytes.NewReader(data)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "POST", url, bytes.NewReader(data)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pbs, err := packages_model.FindExpiredUnreferencedBlobs(db.DefaultContext, duration) @@ -592,8 +603,8 @@ func TestPackageCleanup(t *testing.T) { for _, v := range c.Versions { url := fmt.Sprintf("/api/packages/%s/generic/package/%s/file.bin", user.Name, v.Version) - req := NewRequestWithBody(t, "PUT", url, bytes.NewReader([]byte{1})) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url, bytes.NewReader([]byte{1})). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) if v.Created != 0 { diff --git a/tests/integration/api_packages_vagrant_test.go b/tests/integration/api_packages_vagrant_test.go index cbfc362f32d5..a5e954f3a27d 100644 --- a/tests/integration/api_packages_vagrant_test.go +++ b/tests/integration/api_packages_vagrant_test.go @@ -64,8 +64,8 @@ func TestPackageVagrant(t *testing.T) { req := NewRequest(t, "GET", authenticateURL) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "GET", authenticateURL) - addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", authenticateURL). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) }) @@ -82,8 +82,8 @@ func TestPackageVagrant(t *testing.T) { req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)) - addTokenAuthHeader(req, token) + req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) req = NewRequest(t, "HEAD", boxURL) @@ -111,8 +111,8 @@ func TestPackageVagrant(t *testing.T) { assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) - req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)) - addTokenAuthHeader(req, token) + req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusConflict) }) diff --git a/tests/integration/api_pull_review_test.go b/tests/integration/api_pull_review_test.go index 0e9bace44c9d..daa136b21e45 100644 --- a/tests/integration/api_pull_review_test.go +++ b/tests/integration/api_pull_review_test.go @@ -29,7 +29,8 @@ func TestAPIPullReview(t *testing.T) { // test ListPullReviews session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token) + req := NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews", repo.OwnerName, repo.Name, pullIssue.Index). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var reviews []*api.PullReview @@ -54,20 +55,23 @@ func TestAPIPullReview(t *testing.T) { assert.True(t, reviews[5].Official) // test GetPullReview - req = NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews/%d?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, reviews[3].ID, token) + req = NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews/%d", repo.OwnerName, repo.Name, pullIssue.Index, reviews[3].ID). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var review api.PullReview DecodeJSON(t, resp, &review) assert.EqualValues(t, *reviews[3], review) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/pulls/%d/reviews/%d?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, reviews[5].ID, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/pulls/%d/reviews/%d", repo.OwnerName, repo.Name, pullIssue.Index, reviews[5].ID). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &review) assert.EqualValues(t, *reviews[5], review) // test GetPullReviewComments comment := unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 7}) - req = NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews/%d/comments?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, 10, token) + req = NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews/%d/comments", repo.OwnerName, repo.Name, pullIssue.Index, 10). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var reviewComments []*api.PullReviewComment DecodeJSON(t, resp, &reviewComments) @@ -79,7 +83,7 @@ func TestAPIPullReview(t *testing.T) { assert.EqualValues(t, comment.HTMLURL(db.DefaultContext), reviewComments[0].HTMLURL) // test CreatePullReview - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews", repo.OwnerName, repo.Name, pullIssue.Index), &api.CreatePullReviewOptions{ Body: "body1", // Event: "" # will result in PENDING Comments: []api.CreatePullReviewComment{ @@ -100,7 +104,7 @@ func TestAPIPullReview(t *testing.T) { NewLineNum: 1, }, }, - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &review) assert.EqualValues(t, 6, review.ID) @@ -108,10 +112,10 @@ func TestAPIPullReview(t *testing.T) { assert.EqualValues(t, 3, review.CodeCommentsCount) // test SubmitPullReview - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews/%d?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, review.ID, token), &api.SubmitPullReviewOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews/%d", repo.OwnerName, repo.Name, pullIssue.Index, review.ID), &api.SubmitPullReviewOptions{ Event: "APPROVED", Body: "just two nits", - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &review) assert.EqualValues(t, 6, review.ID) @@ -119,35 +123,37 @@ func TestAPIPullReview(t *testing.T) { assert.EqualValues(t, 3, review.CodeCommentsCount) // test dismiss review - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews/%d/dismissals?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, review.ID, token), &api.DismissPullReviewOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews/%d/dismissals", repo.OwnerName, repo.Name, pullIssue.Index, review.ID), &api.DismissPullReviewOptions{ Message: "test", - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &review) assert.EqualValues(t, 6, review.ID) assert.True(t, review.Dismissed) // test dismiss review - req = NewRequest(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews/%d/undismissals?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, review.ID, token)) + req = NewRequest(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews/%d/undismissals", repo.OwnerName, repo.Name, pullIssue.Index, review.ID)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &review) assert.EqualValues(t, 6, review.ID) assert.False(t, review.Dismissed) // test DeletePullReview - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews", repo.OwnerName, repo.Name, pullIssue.Index), &api.CreatePullReviewOptions{ Body: "just a comment", Event: "COMMENT", - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &review) assert.EqualValues(t, "COMMENT", review.State) assert.EqualValues(t, 0, review.CodeCommentsCount) - req = NewRequestf(t, http.MethodDelete, "/api/v1/repos/%s/%s/pulls/%d/reviews/%d?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, review.ID, token) + req = NewRequestf(t, http.MethodDelete, "/api/v1/repos/%s/%s/pulls/%d/reviews/%d", repo.OwnerName, repo.Name, pullIssue.Index, review.ID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // test CreatePullReview Comment without body but with comments - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews", repo.OwnerName, repo.Name, pullIssue.Index), &api.CreatePullReviewOptions{ // Body: "", Event: "COMMENT", Comments: []api.CreatePullReviewComment{ @@ -163,7 +169,7 @@ func TestAPIPullReview(t *testing.T) { NewLineNum: 0, }, }, - }) + }).AddTokenAuth(token) var commentReview api.PullReview resp = MakeRequest(t, req, http.StatusOK) @@ -175,11 +181,11 @@ func TestAPIPullReview(t *testing.T) { // test CreatePullReview Comment with body but without comments commentBody := "This is a body of the comment." - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews", repo.OwnerName, repo.Name, pullIssue.Index), &api.CreatePullReviewOptions{ Body: commentBody, Event: "COMMENT", Comments: []api.CreatePullReviewComment{}, - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &commentReview) @@ -189,11 +195,11 @@ func TestAPIPullReview(t *testing.T) { assert.False(t, commentReview.Dismissed) // test CreatePullReview Comment without body and no comments - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews", repo.OwnerName, repo.Name, pullIssue.Index), &api.CreatePullReviewOptions{ Body: "", Event: "COMMENT", Comments: []api.CreatePullReviewComment{}, - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusUnprocessableEntity) errMap := make(map[string]any) json.Unmarshal(resp.Body.Bytes(), &errMap) @@ -205,7 +211,8 @@ func TestAPIPullReview(t *testing.T) { assert.NoError(t, pullIssue12.LoadAttributes(db.DefaultContext)) repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue12.RepoID}) - req = NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token) + req = NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews", repo3.OwnerName, repo3.Name, pullIssue12.Index). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &reviews) assert.EqualValues(t, 11, reviews[0].ID) @@ -232,41 +239,41 @@ func TestAPIPullReviewRequest(t *testing.T) { // Test add Review Request session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.PullReviewRequestOptions{ + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo.OwnerName, repo.Name, pullIssue.Index), &api.PullReviewRequestOptions{ Reviewers: []string{"user4@example.com", "user8"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) // poster of pr can't be reviewer - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo.OwnerName, repo.Name, pullIssue.Index), &api.PullReviewRequestOptions{ Reviewers: []string{"user1"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) // test user not exist - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo.OwnerName, repo.Name, pullIssue.Index), &api.PullReviewRequestOptions{ Reviewers: []string{"testOther"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) // Test Remove Review Request session2 := loginUser(t, "user4") token2 := getTokenForLoggedInUser(t, session2, auth_model.AccessTokenScopeWriteRepository) - req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token2), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo.OwnerName, repo.Name, pullIssue.Index), &api.PullReviewRequestOptions{ Reviewers: []string{"user4"}, - }) + }).AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) // doer is not admin - req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token2), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo.OwnerName, repo.Name, pullIssue.Index), &api.PullReviewRequestOptions{ Reviewers: []string{"user8"}, - }) + }).AddTokenAuth(token2) MakeRequest(t, req, http.StatusUnprocessableEntity) - req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo.OwnerName, repo.Name, pullIssue.Index), &api.PullReviewRequestOptions{ Reviewers: []string{"user8"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Test team review request @@ -275,33 +282,35 @@ func TestAPIPullReviewRequest(t *testing.T) { repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue12.RepoID}) // Test add Team Review Request - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo3.OwnerName, repo3.Name, pullIssue12.Index), &api.PullReviewRequestOptions{ TeamReviewers: []string{"team1", "owners"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) // Test add Team Review Request to not allowned - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo3.OwnerName, repo3.Name, pullIssue12.Index), &api.PullReviewRequestOptions{ TeamReviewers: []string{"test_team"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) // Test add Team Review Request to not exist - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo3.OwnerName, repo3.Name, pullIssue12.Index), &api.PullReviewRequestOptions{ TeamReviewers: []string{"not_exist_team"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) // Test Remove team Review Request - req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo3.OwnerName, repo3.Name, pullIssue12.Index), &api.PullReviewRequestOptions{ TeamReviewers: []string{"team1"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // empty request test - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token), &api.PullReviewRequestOptions{}) + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo3.OwnerName, repo3.Name, pullIssue12.Index), &api.PullReviewRequestOptions{}). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) - req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token), &api.PullReviewRequestOptions{}) + req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo3.OwnerName, repo3.Name, pullIssue12.Index), &api.PullReviewRequestOptions{}). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) } diff --git a/tests/integration/api_pull_test.go b/tests/integration/api_pull_test.go index 9d590630e451..33cc826e5eaa 100644 --- a/tests/integration/api_pull_test.go +++ b/tests/integration/api_pull_test.go @@ -31,7 +31,8 @@ func TestAPIViewPulls(t *testing.T) { ctx := NewAPITestContext(t, "user2", repo.Name, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/pulls?state=all&token="+ctx.Token, owner.Name, repo.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/pulls?state=all", owner.Name, repo.Name). + AddTokenAuth(ctx.Token) resp := ctx.Session.MakeRequest(t, req, http.StatusOK) var pulls []*api.PullRequest @@ -76,10 +77,10 @@ func TestAPIMergePullWIP(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s", owner.Name, repo.Name, pr.Index, token), &forms.MergePullRequestForm{ + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge", owner.Name, repo.Name, pr.Index), &forms.MergePullRequestForm{ MergeMessageField: pr.Issue.Title, Do: string(repo_model.MergeStyleMerge), - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusMethodNotAllowed) } @@ -95,11 +96,11 @@ func TestAPICreatePullSuccess(t *testing.T) { session := loginUser(t, owner11.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", owner10.Name, repo10.Name, token), &api.CreatePullRequestOption{ + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", owner10.Name, repo10.Name), &api.CreatePullRequestOption{ Head: fmt.Sprintf("%s:master", owner11.Name), Base: "master", Title: "create a failure pr", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) MakeRequest(t, req, http.StatusUnprocessableEntity) // second request should fail } @@ -126,7 +127,8 @@ func TestAPICreatePullWithFieldsSuccess(t *testing.T) { Labels: []int64{5}, } - req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", owner10.Name, repo10.Name, token), opts) + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", owner10.Name, repo10.Name), opts). + AddTokenAuth(token) res := MakeRequest(t, req, http.StatusCreated) pull := new(api.PullRequest) @@ -158,7 +160,8 @@ func TestAPICreatePullWithFieldsFailure(t *testing.T) { Base: "master", } - req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", owner10.Name, repo10.Name, token), opts) + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", owner10.Name, repo10.Name), opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) opts.Title = "is required" @@ -182,35 +185,34 @@ func TestAPIEditPull(t *testing.T) { session := loginUser(t, owner10.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", owner10.Name, repo10.Name, token), &api.CreatePullRequestOption{ + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", owner10.Name, repo10.Name), &api.CreatePullRequestOption{ Head: "develop", Base: "master", Title: "create a success pr", - }) + }).AddTokenAuth(token) pull := new(api.PullRequest) resp := MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, pull) assert.EqualValues(t, "master", pull.Base.Name) - req = NewRequestWithJSON(t, http.MethodPatch, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d?token=%s", owner10.Name, repo10.Name, pull.Index, token), &api.EditPullRequestOption{ + req = NewRequestWithJSON(t, http.MethodPatch, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d", owner10.Name, repo10.Name, pull.Index), &api.EditPullRequestOption{ Base: "feature/1", Title: "edit a this pr", - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, pull) assert.EqualValues(t, "feature/1", pull.Base.Name) - req = NewRequestWithJSON(t, http.MethodPatch, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d?token=%s", owner10.Name, repo10.Name, pull.Index, token), &api.EditPullRequestOption{ + req = NewRequestWithJSON(t, http.MethodPatch, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d", owner10.Name, repo10.Name, pull.Index), &api.EditPullRequestOption{ Base: "not-exist", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) } func doAPIGetPullFiles(ctx APITestContext, pr *api.PullRequest, callback func(*testing.T, []*api.ChangedFile)) func(*testing.T) { return func(t *testing.T) { - url := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/files?token=%s", ctx.Username, ctx.Reponame, pr.Index, ctx.Token) - - req := NewRequest(t, http.MethodGet, url) + req := NewRequest(t, http.MethodGet, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/files", ctx.Username, ctx.Reponame, pr.Index)). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode == 0 { ctx.ExpectedCode = http.StatusOK } diff --git a/tests/integration/api_releases_test.go b/tests/integration/api_releases_test.go index 526842d5ac07..6ec3fcc4b8b1 100644 --- a/tests/integration/api_releases_test.go +++ b/tests/integration/api_releases_test.go @@ -59,11 +59,12 @@ func TestAPIListReleases(t *testing.T) { // test filter testFilterByLen := func(auth bool, query url.Values, expectedLength int, msgAndArgs ...string) { + link.RawQuery = query.Encode() + req := NewRequest(t, "GET", link.String()) if auth { - query.Set("token", token) + req.AddTokenAuth(token) } - link.RawQuery = query.Encode() - resp = MakeRequest(t, NewRequest(t, "GET", link.String()), http.StatusOK) + resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiReleases) assert.Len(t, apiReleases, expectedLength, msgAndArgs) } @@ -77,8 +78,7 @@ func TestAPIListReleases(t *testing.T) { } func createNewReleaseUsingAPI(t *testing.T, session *TestSession, token string, owner *user_model.User, repo *repo_model.Repository, name, target, title, desc string) *api.Release { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases?token=%s", - owner.Name, repo.Name, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases", owner.Name, repo.Name) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateReleaseOption{ TagName: name, Title: title, @@ -86,7 +86,7 @@ func createNewReleaseUsingAPI(t *testing.T, session *TestSession, token string, IsDraft: false, IsPrerelease: false, Target: target, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var newRelease api.Release @@ -122,9 +122,9 @@ func TestAPICreateAndUpdateRelease(t *testing.T) { newRelease := createNewReleaseUsingAPI(t, session, token, owner, repo, "v0.0.1", target, "v0.0.1", "test") - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases/%d?token=%s", - owner.Name, repo.Name, newRelease.ID, token) - req := NewRequest(t, "GET", urlStr) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases/%d", owner.Name, repo.Name, newRelease.ID) + req := NewRequest(t, "GET", urlStr). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var release api.Release @@ -141,7 +141,7 @@ func TestAPICreateAndUpdateRelease(t *testing.T) { IsDraft: &release.IsDraft, IsPrerelease: &release.IsPrerelease, Target: release.Target, - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &newRelease) @@ -189,10 +189,7 @@ func TestAPIGetLatestRelease(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases/latest", - owner.Name, repo.Name) - - req := NewRequestf(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/latest", owner.Name, repo.Name)) resp := MakeRequest(t, req, http.StatusOK) var release *api.Release @@ -209,10 +206,7 @@ func TestAPIGetReleaseByTag(t *testing.T) { tag := "v1.1" - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", - owner.Name, repo.Name, tag) - - req := NewRequestf(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, tag)) resp := MakeRequest(t, req, http.StatusOK) var release *api.Release @@ -222,10 +216,7 @@ func TestAPIGetReleaseByTag(t *testing.T) { nonexistingtag := "nonexistingtag" - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", - owner.Name, repo.Name, nonexistingtag) - - req = NewRequestf(t, "GET", urlStr) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, nonexistingtag)) resp = MakeRequest(t, req, http.StatusNotFound) var err *api.APIError @@ -244,15 +235,18 @@ func TestAPIDeleteReleaseByTagName(t *testing.T) { createNewReleaseUsingAPI(t, session, token, owner, repo, "release-tag", "", "Release Tag", "test") // delete release - req := NewRequestf(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/release-tag?token=%s", owner.Name, repo.Name, token)) + req := NewRequestf(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/release-tag", owner.Name, repo.Name)). + AddTokenAuth(token) _ = MakeRequest(t, req, http.StatusNoContent) // make sure release is deleted - req = NewRequestf(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/release-tag?token=%s", owner.Name, repo.Name, token)) + req = NewRequestf(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/release-tag", owner.Name, repo.Name)). + AddTokenAuth(token) _ = MakeRequest(t, req, http.StatusNotFound) // delete release tag too - req = NewRequestf(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/tags/release-tag?token=%s", owner.Name, repo.Name, token)) + req = NewRequestf(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/tags/release-tag", owner.Name, repo.Name)). + AddTokenAuth(token) _ = MakeRequest(t, req, http.StatusNoContent) } @@ -278,7 +272,8 @@ func TestAPIUploadAssetRelease(t *testing.T) { err = writer.Close() assert.NoError(t, err) - req := NewRequestWithBody(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/releases/%d/assets?name=test-asset&token=%s", owner.Name, repo.Name, r.ID, token), body) + req := NewRequestWithBody(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/releases/%d/assets?name=test-asset", owner.Name, repo.Name, r.ID), body). + AddTokenAuth(token) req.Header.Add("Content-Type", writer.FormDataContentType()) resp := MakeRequest(t, req, http.StatusCreated) diff --git a/tests/integration/api_repo_avatar_test.go b/tests/integration/api_repo_avatar_test.go index 58a4fc536c87..6677885f7eb2 100644 --- a/tests/integration/api_repo_avatar_test.go +++ b/tests/integration/api_repo_avatar_test.go @@ -38,7 +38,8 @@ func TestAPIUpdateRepoAvatar(t *testing.T) { Image: base64.StdEncoding.EncodeToString(avatar), } - req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/avatar?token=%s", repo.OwnerName, repo.Name, token), &opts) + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/avatar", repo.OwnerName, repo.Name), &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Test what happens if you don't have a valid Base64 string @@ -46,7 +47,8 @@ func TestAPIUpdateRepoAvatar(t *testing.T) { Image: "Invalid", } - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/avatar?token=%s", repo.OwnerName, repo.Name, token), &opts) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/avatar", repo.OwnerName, repo.Name), &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusBadRequest) // Test what happens if you use a file that is not an image @@ -60,7 +62,8 @@ func TestAPIUpdateRepoAvatar(t *testing.T) { Image: base64.StdEncoding.EncodeToString(text), } - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/avatar?token=%s", repo.OwnerName, repo.Name, token), &opts) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/avatar", repo.OwnerName, repo.Name), &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusInternalServerError) } @@ -71,6 +74,7 @@ func TestAPIDeleteRepoAvatar(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) token := getUserToken(t, user2.LowerName, auth_model.AccessTokenScopeWriteRepository) - req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/avatar?token=%s", repo.OwnerName, repo.Name, token)) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/avatar", repo.OwnerName, repo.Name)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) } diff --git a/tests/integration/api_repo_collaborator_test.go b/tests/integration/api_repo_collaborator_test.go index b7280a4f6c41..59cf85fef33d 100644 --- a/tests/integration/api_repo_collaborator_test.go +++ b/tests/integration/api_repo_collaborator_test.go @@ -31,7 +31,8 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { testCtx := NewAPITestContext(t, repo2Owner.Name, repo2.Name, auth_model.AccessTokenScopeWriteRepository) t.Run("RepoOwnerShouldBeOwner", func(t *testing.T) { - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, repo2Owner.Name, testCtx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission", repo2Owner.Name, repo2.Name, repo2Owner.Name). + AddTokenAuth(testCtx.Token) resp := MakeRequest(t, req, http.StatusOK) var repoPermission api.RepoCollaboratorPermission @@ -43,7 +44,8 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { t.Run("CollaboratorWithReadAccess", func(t *testing.T) { t.Run("AddUserAsCollaboratorWithReadAccess", doAPIAddCollaborator(testCtx, user4.Name, perm.AccessModeRead)) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user4.Name, testCtx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission", repo2Owner.Name, repo2.Name, user4.Name). + AddTokenAuth(testCtx.Token) resp := MakeRequest(t, req, http.StatusOK) var repoPermission api.RepoCollaboratorPermission @@ -55,7 +57,8 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { t.Run("CollaboratorWithWriteAccess", func(t *testing.T) { t.Run("AddUserAsCollaboratorWithWriteAccess", doAPIAddCollaborator(testCtx, user4.Name, perm.AccessModeWrite)) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user4.Name, testCtx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission", repo2Owner.Name, repo2.Name, user4.Name). + AddTokenAuth(testCtx.Token) resp := MakeRequest(t, req, http.StatusOK) var repoPermission api.RepoCollaboratorPermission @@ -67,7 +70,8 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { t.Run("CollaboratorWithAdminAccess", func(t *testing.T) { t.Run("AddUserAsCollaboratorWithAdminAccess", doAPIAddCollaborator(testCtx, user4.Name, perm.AccessModeAdmin)) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user4.Name, testCtx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission", repo2Owner.Name, repo2.Name, user4.Name). + AddTokenAuth(testCtx.Token) resp := MakeRequest(t, req, http.StatusOK) var repoPermission api.RepoCollaboratorPermission @@ -77,7 +81,8 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { }) t.Run("CollaboratorNotFound", func(t *testing.T) { - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, "non-existent-user", testCtx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission", repo2Owner.Name, repo2.Name, "non-existent-user"). + AddTokenAuth(testCtx.Token) MakeRequest(t, req, http.StatusNotFound) }) @@ -87,7 +92,8 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { _session := loginUser(t, user5.Name) _testCtx := NewAPITestContext(t, user5.Name, repo2.Name, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user5.Name, _testCtx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission", repo2Owner.Name, repo2.Name, user5.Name). + AddTokenAuth(_testCtx.Token) resp := _session.MakeRequest(t, req, http.StatusOK) var repoPermission api.RepoCollaboratorPermission @@ -102,7 +108,8 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { _session := loginUser(t, user5.Name) _testCtx := NewAPITestContext(t, user5.Name, repo2.Name, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user5.Name, _testCtx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission", repo2Owner.Name, repo2.Name, user5.Name). + AddTokenAuth(_testCtx.Token) resp := _session.MakeRequest(t, req, http.StatusOK) var repoPermission api.RepoCollaboratorPermission @@ -118,7 +125,8 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { _session := loginUser(t, user10.Name) _testCtx := NewAPITestContext(t, user10.Name, repo2.Name, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user11.Name, _testCtx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission", repo2Owner.Name, repo2.Name, user11.Name). + AddTokenAuth(_testCtx.Token) resp := _session.MakeRequest(t, req, http.StatusOK) var repoPermission api.RepoCollaboratorPermission diff --git a/tests/integration/api_repo_edit_test.go b/tests/integration/api_repo_edit_test.go index 0e992c2df249..c4fc2177b4ce 100644 --- a/tests/integration/api_repo_edit_test.go +++ b/tests/integration/api_repo_edit_test.go @@ -155,8 +155,8 @@ func TestAPIRepoEdit(t *testing.T) { // Test editing a repo1 which user2 owns, changing name and many properties origRepoEditOption := getRepoEditOptionFromRepo(repo1) repoEditOption := getNewRepoEditOption(origRepoEditOption) - url := fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, repo1.Name, token2) - req := NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req := NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, repo1.Name), &repoEditOption). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusOK) var repo api.Repository DecodeJSON(t, resp, &repo) @@ -186,8 +186,9 @@ func TestAPIRepoEdit(t *testing.T) { } *repoEditOption.HasWiki = true repoEditOption.ExternalWiki = nil - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, *repoEditOption.Name, token2) - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + url := fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, *repoEditOption.Name) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &repo) assert.NotNil(t, repo) @@ -209,7 +210,8 @@ func TestAPIRepoEdit(t *testing.T) { repoEditOption.ExternalWiki = &api.ExternalWiki{ ExternalWikiURL: "http://www.somewebsite.com", } - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &repo) assert.NotNil(t, repo) @@ -223,7 +225,8 @@ func TestAPIRepoEdit(t *testing.T) { repoEditOption.ExternalTracker.ExternalTrackerStyle = "regexp" repoEditOption.ExternalTracker.ExternalTrackerRegexpPattern = `(\d+)` - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &repo) assert.NotNil(t, repo) @@ -234,15 +237,18 @@ func TestAPIRepoEdit(t *testing.T) { // Do some tests with invalid URL for external tracker and wiki repoEditOption.ExternalTracker.ExternalTrackerURL = "htp://www.somewebsite.com" - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusUnprocessableEntity) repoEditOption.ExternalTracker.ExternalTrackerURL = "http://www.somewebsite.com" repoEditOption.ExternalTracker.ExternalTrackerFormat = "http://www.somewebsite.com/{user/{repo}?issue={index}" - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusUnprocessableEntity) repoEditOption.ExternalTracker.ExternalTrackerFormat = "http://www.somewebsite.com/{user}/{repo}?issue={index}" repoEditOption.ExternalWiki.ExternalWikiURL = "htp://www.somewebsite.com" - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusUnprocessableEntity) // Test small repo change through API with issue and wiki option not set; They shall not be touched. @@ -251,7 +257,8 @@ func TestAPIRepoEdit(t *testing.T) { repoEditOption.ExternalTracker = nil repoEditOption.HasWiki = nil repoEditOption.ExternalWiki = nil - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &repo) assert.NotNil(t, repo) @@ -265,39 +272,38 @@ func TestAPIRepoEdit(t *testing.T) { assert.NotNil(t, *repo1editedOption.ExternalWiki) // reset repo in db - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, *repoEditOption.Name, token2) - req = NewRequestWithJSON(t, "PATCH", url, &origRepoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, *repoEditOption.Name), &origRepoEditOption). + AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusOK) // Test editing a non-existing repo name := "repodoesnotexist" - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, name, token2) - req = NewRequestWithJSON(t, "PATCH", url, &api.EditRepoOption{Name: &name}) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, name), &api.EditRepoOption{Name: &name}). + AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusNotFound) // Test editing repo16 by user4 who does not have write access origRepoEditOption = getRepoEditOptionFromRepo(repo16) repoEditOption = getNewRepoEditOption(origRepoEditOption) - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, repo16.Name, token4) - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, repo16.Name), &repoEditOption). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusNotFound) // Tests a repo with no token given so will fail origRepoEditOption = getRepoEditOptionFromRepo(repo16) repoEditOption = getNewRepoEditOption(origRepoEditOption) - url = fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, repo16.Name) - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, repo16.Name), &repoEditOption) _ = MakeRequest(t, req, http.StatusNotFound) // Test using access token for a private repo that the user of the token owns origRepoEditOption = getRepoEditOptionFromRepo(repo16) repoEditOption = getNewRepoEditOption(origRepoEditOption) - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, repo16.Name, token2) - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, repo16.Name), &repoEditOption). + AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusOK) // reset repo in db - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, *repoEditOption.Name, token2) - req = NewRequestWithJSON(t, "PATCH", url, &origRepoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, *repoEditOption.Name), &origRepoEditOption). + AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusOK) // Test making a repo public that is private @@ -306,53 +312,54 @@ func TestAPIRepoEdit(t *testing.T) { repoEditOption = &api.EditRepoOption{ Private: &bFalse, } - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, repo16.Name, token2) - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + url = fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, repo16.Name) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusOK) repo16 = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 16}) assert.False(t, repo16.IsPrivate) // Make it private again repoEditOption.Private = &bTrue - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusOK) // Test to change empty repo assert.False(t, repo15.IsArchived) - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, repo15.Name, token2) + url = fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, repo15.Name) req = NewRequestWithJSON(t, "PATCH", url, &api.EditRepoOption{ Archived: &bTrue, - }) + }).AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusOK) repo15 = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 15}) assert.True(t, repo15.IsArchived) req = NewRequestWithJSON(t, "PATCH", url, &api.EditRepoOption{ Archived: &bFalse, - }) + }).AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" where user2 is a collaborator origRepoEditOption = getRepoEditOptionFromRepo(repo3) repoEditOption = getNewRepoEditOption(origRepoEditOption) - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", org3.Name, repo3.Name, token2) - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", org3.Name, repo3.Name), &repoEditOption). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) // reset repo in db - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", org3.Name, *repoEditOption.Name, token2) - req = NewRequestWithJSON(t, "PATCH", url, &origRepoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", org3.Name, *repoEditOption.Name), &origRepoEditOption). + AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" with no user token origRepoEditOption = getRepoEditOptionFromRepo(repo3) repoEditOption = getNewRepoEditOption(origRepoEditOption) - url = fmt.Sprintf("/api/v1/repos/%s/%s", org3.Name, repo3.Name) - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", org3.Name, repo3.Name), &repoEditOption) MakeRequest(t, req, http.StatusNotFound) // Test using repo "user2/repo1" where user4 is a NOT collaborator origRepoEditOption = getRepoEditOptionFromRepo(repo1) repoEditOption = getNewRepoEditOption(origRepoEditOption) - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, repo1.Name, token4) - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, repo1.Name), &repoEditOption). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusForbidden) }) } diff --git a/tests/integration/api_repo_file_create_test.go b/tests/integration/api_repo_file_create_test.go index fbe0b5bcd055..f78909eb3258 100644 --- a/tests/integration/api_repo_file_create_test.go +++ b/tests/integration/api_repo_file_create_test.go @@ -164,8 +164,8 @@ func TestAPICreateFile(t *testing.T) { createFileOptions.BranchName = branch fileID++ treePath := fmt.Sprintf("new/file%d.txt", fileID) - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req := NewRequestWithJSON(t, "POST", url, &createFileOptions) + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &createFileOptions). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusCreated) gitRepo, _ := git.OpenRepository(stdCtx.Background(), repo1.RepoPath()) commitID, _ := gitRepo.GetBranchCommitID(createFileOptions.NewBranchName) @@ -191,8 +191,8 @@ func TestAPICreateFile(t *testing.T) { createFileOptions.NewBranchName = "new_branch" fileID++ treePath := fmt.Sprintf("new/file%d.txt", fileID) - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req := NewRequestWithJSON(t, "POST", url, &createFileOptions) + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &createFileOptions). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusCreated) var fileResponse api.FileResponse DecodeJSON(t, resp, &fileResponse) @@ -209,8 +209,8 @@ func TestAPICreateFile(t *testing.T) { createFileOptions.Message = "" fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &createFileOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, &fileResponse) expectedMessage := "Add " + treePath + "\n" @@ -219,8 +219,8 @@ func TestAPICreateFile(t *testing.T) { // Test trying to create a file that already exists, should fail createFileOptions = getCreateFileOptions() treePath = "README.md" - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &createFileOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusUnprocessableEntity) expectedAPIError := context.APIError{ Message: "repository file already exists [path: " + treePath + "]", @@ -234,48 +234,46 @@ func TestAPICreateFile(t *testing.T) { createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo16.Name, treePath, token4) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &createFileOptions). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusNotFound) // Tests a repo with no token given so will fail createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &createFileOptions) MakeRequest(t, req, http.StatusNotFound) // Test using access token for a private repo that the user of the token owns createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo16.Name, treePath, token2) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &createFileOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusCreated) // Test using org repo "org3/repo3" where user2 is a collaborator createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", org3.Name, repo3.Name, treePath, token2) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath), &createFileOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusCreated) // Test using org repo "org3/repo3" with no user token createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath), &createFileOptions) MakeRequest(t, req, http.StatusNotFound) // Test using repo "user2/repo1" where user4 is a NOT collaborator createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token4) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &createFileOptions). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusForbidden) // Test creating a file in an empty repository @@ -283,8 +281,8 @@ func TestAPICreateFile(t *testing.T) { createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, "empty-repo", treePath, token2) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, "empty-repo", treePath), &createFileOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusCreated) emptyRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerName: "user2", Name: "empty-repo"}) // public repo gitRepo, _ := git.OpenRepository(stdCtx.Background(), emptyRepo.RepoPath()) diff --git a/tests/integration/api_repo_file_delete_test.go b/tests/integration/api_repo_file_delete_test.go index c6ab7a0e615b..7c93307e1981 100644 --- a/tests/integration/api_repo_file_delete_test.go +++ b/tests/integration/api_repo_file_delete_test.go @@ -64,8 +64,8 @@ func TestAPIDeleteFile(t *testing.T) { createFile(user2, repo1, treePath) deleteFileOptions := getDeleteFileOptions() deleteFileOptions.BranchName = branch - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req := NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req := NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &deleteFileOptions). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusOK) var fileResponse api.FileResponse DecodeJSON(t, resp, &fileResponse) @@ -80,8 +80,8 @@ func TestAPIDeleteFile(t *testing.T) { deleteFileOptions := getDeleteFileOptions() deleteFileOptions.BranchName = repo1.DefaultBranch deleteFileOptions.NewBranchName = "new_branch" - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req := NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req := NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &deleteFileOptions). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusOK) var fileResponse api.FileResponse DecodeJSON(t, resp, &fileResponse) @@ -95,8 +95,8 @@ func TestAPIDeleteFile(t *testing.T) { createFile(user2, repo1, treePath) deleteFileOptions = getDeleteFileOptions() deleteFileOptions.Message = "" - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req = NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &deleteFileOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fileResponse) expectedMessage := "Delete " + treePath + "\n" @@ -108,8 +108,8 @@ func TestAPIDeleteFile(t *testing.T) { createFile(user2, repo1, treePath) deleteFileOptions = getDeleteFileOptions() deleteFileOptions.SHA = "badsha" - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req = NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &deleteFileOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusBadRequest) // Test creating a file in repo16 by user4 who does not have write access @@ -117,8 +117,8 @@ func TestAPIDeleteFile(t *testing.T) { treePath = fmt.Sprintf("delete/file%d.txt", fileID) createFile(user2, repo16, treePath) deleteFileOptions = getDeleteFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo16.Name, treePath, token4) - req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req = NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &deleteFileOptions). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusNotFound) // Tests a repo with no token given so will fail @@ -126,8 +126,7 @@ func TestAPIDeleteFile(t *testing.T) { treePath = fmt.Sprintf("delete/file%d.txt", fileID) createFile(user2, repo16, treePath) deleteFileOptions = getDeleteFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath) - req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req = NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &deleteFileOptions) MakeRequest(t, req, http.StatusNotFound) // Test using access token for a private repo that the user of the token owns @@ -135,8 +134,8 @@ func TestAPIDeleteFile(t *testing.T) { treePath = fmt.Sprintf("delete/file%d.txt", fileID) createFile(user2, repo16, treePath) deleteFileOptions = getDeleteFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo16.Name, treePath, token2) - req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req = NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &deleteFileOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" where user2 is a collaborator @@ -144,8 +143,8 @@ func TestAPIDeleteFile(t *testing.T) { treePath = fmt.Sprintf("delete/file%d.txt", fileID) createFile(org3, repo3, treePath) deleteFileOptions = getDeleteFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", org3.Name, repo3.Name, treePath, token2) - req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req = NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath), &deleteFileOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" with no user token @@ -153,8 +152,7 @@ func TestAPIDeleteFile(t *testing.T) { treePath = fmt.Sprintf("delete/file%d.txt", fileID) createFile(org3, repo3, treePath) deleteFileOptions = getDeleteFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath) - req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req = NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath), &deleteFileOptions) MakeRequest(t, req, http.StatusNotFound) // Test using repo "user2/repo1" where user4 is a NOT collaborator @@ -162,8 +160,8 @@ func TestAPIDeleteFile(t *testing.T) { treePath = fmt.Sprintf("delete/file%d.txt", fileID) createFile(user2, repo1, treePath) deleteFileOptions = getDeleteFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token4) - req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req = NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &deleteFileOptions). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusForbidden) }) } diff --git a/tests/integration/api_repo_file_update_test.go b/tests/integration/api_repo_file_update_test.go index ecf24cdbf984..7e88f6cd8036 100644 --- a/tests/integration/api_repo_file_update_test.go +++ b/tests/integration/api_repo_file_update_test.go @@ -132,8 +132,8 @@ func TestAPIUpdateFile(t *testing.T) { createFile(user2, repo1, treePath) updateFileOptions := getUpdateFileOptions() updateFileOptions.BranchName = branch - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req := NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &updateFileOptions). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusOK) gitRepo, _ := git.OpenRepository(stdCtx.Background(), repo1.RepoPath()) commitID, _ := gitRepo.GetBranchCommitID(updateFileOptions.NewBranchName) @@ -156,8 +156,8 @@ func TestAPIUpdateFile(t *testing.T) { fileID++ treePath := fmt.Sprintf("update/file%d.txt", fileID) createFile(user2, repo1, treePath) - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req := NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &updateFileOptions). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusOK) var fileResponse api.FileResponse DecodeJSON(t, resp, &fileResponse) @@ -177,8 +177,8 @@ func TestAPIUpdateFile(t *testing.T) { createFile(user2, repo1, treePath) updateFileOptions.FromPath = treePath treePath = "rename/" + treePath - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &updateFileOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fileResponse) expectedSHA = "08bd14b2e2852529157324de9c226b3364e76136" @@ -195,8 +195,8 @@ func TestAPIUpdateFile(t *testing.T) { fileID++ treePath = fmt.Sprintf("update/file%d.txt", fileID) createFile(user2, repo1, treePath) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &updateFileOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fileResponse) expectedMessage := "Update " + treePath + "\n" @@ -209,8 +209,8 @@ func TestAPIUpdateFile(t *testing.T) { updateFileOptions = getUpdateFileOptions() correctSHA := updateFileOptions.SHA updateFileOptions.SHA = "badsha" - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &updateFileOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusUnprocessableEntity) expectedAPIError := context.APIError{ Message: "sha does not match [given: " + updateFileOptions.SHA + ", expected: " + correctSHA + "]", @@ -225,8 +225,8 @@ func TestAPIUpdateFile(t *testing.T) { treePath = fmt.Sprintf("update/file%d.txt", fileID) createFile(user2, repo16, treePath) updateFileOptions = getUpdateFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo16.Name, treePath, token4) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &updateFileOptions). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusNotFound) // Tests a repo with no token given so will fail @@ -234,8 +234,7 @@ func TestAPIUpdateFile(t *testing.T) { treePath = fmt.Sprintf("update/file%d.txt", fileID) createFile(user2, repo16, treePath) updateFileOptions = getUpdateFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &updateFileOptions) MakeRequest(t, req, http.StatusNotFound) // Test using access token for a private repo that the user of the token owns @@ -243,8 +242,8 @@ func TestAPIUpdateFile(t *testing.T) { treePath = fmt.Sprintf("update/file%d.txt", fileID) createFile(user2, repo16, treePath) updateFileOptions = getUpdateFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo16.Name, treePath, token2) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &updateFileOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" where user2 is a collaborator @@ -252,8 +251,8 @@ func TestAPIUpdateFile(t *testing.T) { treePath = fmt.Sprintf("update/file%d.txt", fileID) createFile(org3, repo3, treePath) updateFileOptions = getUpdateFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", org3.Name, repo3.Name, treePath, token2) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath), &updateFileOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" with no user token @@ -261,8 +260,7 @@ func TestAPIUpdateFile(t *testing.T) { treePath = fmt.Sprintf("update/file%d.txt", fileID) createFile(org3, repo3, treePath) updateFileOptions = getUpdateFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath), &updateFileOptions) MakeRequest(t, req, http.StatusNotFound) // Test using repo "user2/repo1" where user4 is a NOT collaborator @@ -270,8 +268,8 @@ func TestAPIUpdateFile(t *testing.T) { treePath = fmt.Sprintf("update/file%d.txt", fileID) createFile(user2, repo1, treePath) updateFileOptions = getUpdateFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token4) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &updateFileOptions). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusForbidden) }) } diff --git a/tests/integration/api_repo_files_change_test.go b/tests/integration/api_repo_files_change_test.go index 1ab759497fb0..d500d48b3609 100644 --- a/tests/integration/api_repo_files_change_test.go +++ b/tests/integration/api_repo_files_change_test.go @@ -93,8 +93,8 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[0].Path = createTreePath changeFilesOptions.Files[1].Path = updateTreePath changeFilesOptions.Files[2].Path = deleteTreePath - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents?token=%s", user2.Name, repo1.Name, token2) - req := NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents", user2.Name, repo1.Name), &changeFilesOptions). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusCreated) gitRepo, _ := git.OpenRepository(stdCtx.Background(), repo1.RepoPath()) commitID, _ := gitRepo.GetBranchCommitID(changeFilesOptions.NewBranchName) @@ -138,8 +138,9 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[2].Path = deleteTreePath createFile(user2, repo1, updateTreePath) createFile(user2, repo1, deleteTreePath) - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents?token=%s", user2.Name, repo1.Name, token2) - req := NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + url := fmt.Sprintf("/api/v1/repos/%s/%s/contents", user2.Name, repo1.Name) + req := NewRequestWithJSON(t, "POST", url, &changeFilesOptions). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusCreated) var filesResponse api.FilesResponse DecodeJSON(t, resp, &filesResponse) @@ -168,7 +169,8 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files = []*api.ChangeFileOperation{changeFilesOptions.Files[1]} changeFilesOptions.Files[0].FromPath = updateTreePath changeFilesOptions.Files[0].Path = "rename/" + updateTreePath - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, &filesResponse) expectedUpdateSHA = "08bd14b2e2852529157324de9c226b3364e76136" @@ -191,7 +193,8 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[2].Path = deleteTreePath createFile(user2, repo1, updateTreePath) createFile(user2, repo1, deleteTreePath) - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, &filesResponse) expectedMessage := fmt.Sprintf("Add %v\nUpdate %v\nDelete %v\n", createTreePath, updateTreePath, deleteTreePath) @@ -206,7 +209,8 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[0].Path = updateTreePath correctSHA := changeFilesOptions.Files[0].SHA changeFilesOptions.Files[0].SHA = "badsha" - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusUnprocessableEntity) expectedAPIError := context.APIError{ Message: "sha does not match [given: " + changeFilesOptions.Files[0].SHA + ", expected: " + correctSHA + "]", @@ -227,8 +231,8 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[0].Path = createTreePath changeFilesOptions.Files[1].Path = updateTreePath changeFilesOptions.Files[2].Path = deleteTreePath - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents?token=%s", user2.Name, repo16.Name, token4) - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents", user2.Name, repo16.Name), &changeFilesOptions). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusNotFound) // Tests a repo with no token given so will fail @@ -242,8 +246,7 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[0].Path = createTreePath changeFilesOptions.Files[1].Path = updateTreePath changeFilesOptions.Files[2].Path = deleteTreePath - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents", user2.Name, repo16.Name) - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents", user2.Name, repo16.Name), &changeFilesOptions) MakeRequest(t, req, http.StatusNotFound) // Test using access token for a private repo that the user of the token owns @@ -257,8 +260,8 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[0].Path = createTreePath changeFilesOptions.Files[1].Path = updateTreePath changeFilesOptions.Files[2].Path = deleteTreePath - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents?token=%s", user2.Name, repo16.Name, token2) - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents", user2.Name, repo16.Name), &changeFilesOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusCreated) // Test using org repo "org3/repo3" where user2 is a collaborator @@ -272,8 +275,8 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[0].Path = createTreePath changeFilesOptions.Files[1].Path = updateTreePath changeFilesOptions.Files[2].Path = deleteTreePath - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents?token=%s", org3.Name, repo3.Name, token2) - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents", org3.Name, repo3.Name), &changeFilesOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusCreated) // Test using org repo "org3/repo3" with no user token @@ -287,8 +290,7 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[0].Path = createTreePath changeFilesOptions.Files[1].Path = updateTreePath changeFilesOptions.Files[2].Path = deleteTreePath - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents", org3.Name, repo3.Name) - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents", org3.Name, repo3.Name), &changeFilesOptions) MakeRequest(t, req, http.StatusNotFound) // Test using repo "user2/repo1" where user4 is a NOT collaborator @@ -302,8 +304,8 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[0].Path = createTreePath changeFilesOptions.Files[1].Path = updateTreePath changeFilesOptions.Files[2].Path = deleteTreePath - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents?token=%s", user2.Name, repo1.Name, token4) - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents", user2.Name, repo1.Name), &changeFilesOptions). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusForbidden) }) } diff --git a/tests/integration/api_repo_get_contents_list_test.go b/tests/integration/api_repo_get_contents_list_test.go index 7874eddfd4d1..86313f5e3b20 100644 --- a/tests/integration/api_repo_get_contents_list_test.go +++ b/tests/integration/api_repo_get_contents_list_test.go @@ -154,14 +154,17 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) { MakeRequest(t, req, http.StatusNotFound) // Test accessing private ref with user token that does not have access - should fail - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo16.Name, treePath, token4) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusNotFound) // Test access private ref of owner of token - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/readme.md?token=%s", user2.Name, repo16.Name, token2) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/readme.md", user2.Name, repo16.Name). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) // Test access of org org3 private repo file by owner user2 - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?token=%s", org3.Name, repo3.Name, treePath, token2) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) } diff --git a/tests/integration/api_repo_get_contents_test.go b/tests/integration/api_repo_get_contents_test.go index 1d708a4cdb43..ffbdfcb0fab8 100644 --- a/tests/integration/api_repo_get_contents_test.go +++ b/tests/integration/api_repo_get_contents_test.go @@ -151,15 +151,18 @@ func testAPIGetContents(t *testing.T, u *url.URL) { MakeRequest(t, req, http.StatusNotFound) // Test accessing private ref with user token that does not have access - should fail - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo16.Name, treePath, token4) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusNotFound) // Test access private ref of owner of token - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/readme.md?token=%s", user2.Name, repo16.Name, token2) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/readme.md", user2.Name, repo16.Name). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) // Test access of org org3 private repo file by owner user2 - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?token=%s", org3.Name, repo3.Name, treePath, token2) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) } diff --git a/tests/integration/api_repo_git_blobs_test.go b/tests/integration/api_repo_git_blobs_test.go index 866234d0a6cc..184362e7e320 100644 --- a/tests/integration/api_repo_git_blobs_test.go +++ b/tests/integration/api_repo_git_blobs_test.go @@ -48,7 +48,8 @@ func TestAPIReposGitBlobs(t *testing.T) { MakeRequest(t, req, http.StatusNotFound) // Test using access token for a private repo that the user of the token owns - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s?token=%s", user2.Name, repo16.Name, repo16ReadmeSHA, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s", user2.Name, repo16.Name, repo16ReadmeSHA). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) // Test using bad sha @@ -56,11 +57,13 @@ func TestAPIReposGitBlobs(t *testing.T) { MakeRequest(t, req, http.StatusBadRequest) // Test using org repo "org3/repo3" where user2 is a collaborator - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s?token=%s", org3.Name, repo3.Name, repo3ReadmeSHA, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s", org3.Name, repo3.Name, repo3ReadmeSHA). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" where user2 is a collaborator - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s?token=%s", org3.Name, repo3.Name, repo3ReadmeSHA, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s", org3.Name, repo3.Name, repo3ReadmeSHA). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" with no user token diff --git a/tests/integration/api_repo_git_commits_test.go b/tests/integration/api_repo_git_commits_test.go index 765055720d79..365520620730 100644 --- a/tests/integration/api_repo_git_commits_test.go +++ b/tests/integration/api_repo_git_commits_test.go @@ -32,13 +32,16 @@ func TestAPIReposGitCommits(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) // check invalid requests - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/12345?token="+token, user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/12345", user.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/..?token="+token, user.Name) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/..", user.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/branch-not-exist?token="+token, user.Name) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/branch-not-exist", user.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) for _, ref := range [...]string{ @@ -47,7 +50,8 @@ func TestAPIReposGitCommits(t *testing.T) { "65f1", // short sha "65f1bf27bc3bf70f64657658635e66094edbcb4d", // full sha } { - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/%s?token="+token, user.Name, ref) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/%s", user.Name, ref). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) } } @@ -60,7 +64,8 @@ func TestAPIReposGitCommitList(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) // Test getting commits (Page 1) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo20/commits?token="+token+"¬=master&sha=remove-files-a", user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo20/commits?not=master&sha=remove-files-a", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiData []api.Commit @@ -83,7 +88,8 @@ func TestAPIReposGitCommitListNotMaster(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) // Test getting commits (Page 1) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?token="+token, user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiData []api.Commit @@ -108,7 +114,8 @@ func TestAPIReposGitCommitListPage2Empty(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) // Test getting commits (Page=2) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?token="+token+"&page=2", user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?page=2", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiData []api.Commit @@ -125,7 +132,8 @@ func TestAPIReposGitCommitListDifferentBranch(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) // Test getting commits (Page=1, Branch=good-sign) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?token="+token+"&sha=good-sign", user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?sha=good-sign", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiData []api.Commit @@ -144,7 +152,8 @@ func TestAPIReposGitCommitListWithoutSelectFields(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) // Test getting commits without files, verification, and stats - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?token="+token+"&sha=good-sign&stat=false&files=false&verification=false", user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?sha=good-sign&stat=false&files=false&verification=false", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiData []api.Commit @@ -165,14 +174,16 @@ func TestDownloadCommitDiffOrPatch(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) // Test getting diff - reqDiff := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/git/commits/f27c2b2b03dcab38beaf89b0ab4ff61f6de63441.diff?token="+token, user.Name) + reqDiff := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/git/commits/f27c2b2b03dcab38beaf89b0ab4ff61f6de63441.diff", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, reqDiff, http.StatusOK) assert.EqualValues(t, "commit f27c2b2b03dcab38beaf89b0ab4ff61f6de63441\nAuthor: User2 \nDate: Sun Aug 6 19:55:01 2017 +0200\n\n good signed commit\n\ndiff --git a/readme.md b/readme.md\nnew file mode 100644\nindex 0000000..458121c\n--- /dev/null\n+++ b/readme.md\n@@ -0,0 +1 @@\n+good sign\n", resp.Body.String()) // Test getting patch - reqPatch := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/git/commits/f27c2b2b03dcab38beaf89b0ab4ff61f6de63441.patch?token="+token, user.Name) + reqPatch := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/git/commits/f27c2b2b03dcab38beaf89b0ab4ff61f6de63441.patch", user.Name). + AddTokenAuth(token) resp = MakeRequest(t, reqPatch, http.StatusOK) assert.EqualValues(t, "From f27c2b2b03dcab38beaf89b0ab4ff61f6de63441 Mon Sep 17 00:00:00 2001\nFrom: User2 \nDate: Sun, 6 Aug 2017 19:55:01 +0200\nSubject: [PATCH] good signed commit\n\n---\n readme.md | 1 +\n 1 file changed, 1 insertion(+)\n create mode 100644 readme.md\n\ndiff --git a/readme.md b/readme.md\nnew file mode 100644\nindex 0000000..458121c\n--- /dev/null\n+++ b/readme.md\n@@ -0,0 +1 @@\n+good sign\n", @@ -186,7 +197,8 @@ func TestGetFileHistory(t *testing.T) { session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?path=readme.md&token="+token+"&sha=good-sign", user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?path=readme.md&sha=good-sign", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiData []api.Commit @@ -206,7 +218,8 @@ func TestGetFileHistoryNotOnMaster(t *testing.T) { session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo20/commits?path=test.csv&token="+token+"&sha=add-csv¬=master", user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo20/commits?path=test.csv&sha=add-csv¬=master", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiData []api.Commit diff --git a/tests/integration/api_repo_git_hook_test.go b/tests/integration/api_repo_git_hook_test.go index 9f3205ce60d9..9917b41790d1 100644 --- a/tests/integration/api_repo_git_hook_test.go +++ b/tests/integration/api_repo_git_hook_test.go @@ -32,8 +32,8 @@ func TestAPIListGitHooks(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", - owner.Name, repo.Name, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git", owner.Name, repo.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiGitHooks []*api.GitHook DecodeJSON(t, resp, &apiGitHooks) @@ -58,8 +58,8 @@ func TestAPIListGitHooksNoHooks(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", - owner.Name, repo.Name, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git", owner.Name, repo.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiGitHooks []*api.GitHook DecodeJSON(t, resp, &apiGitHooks) @@ -78,8 +78,8 @@ func TestAPIListGitHooksNoAccess(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", - owner.Name, repo.Name, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git", owner.Name, repo.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) } @@ -92,8 +92,8 @@ func TestAPIGetGitHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", - owner.Name, repo.Name, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive", owner.Name, repo.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiGitHook *api.GitHook DecodeJSON(t, resp, &apiGitHook) @@ -109,8 +109,8 @@ func TestAPIGetGitHookNoAccess(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", - owner.Name, repo.Name, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive", owner.Name, repo.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) } @@ -124,19 +124,19 @@ func TestAPIEditGitHook(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", - owner.Name, repo.Name, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive", + owner.Name, repo.Name) req := NewRequestWithJSON(t, "PATCH", urlStr, &api.EditGitHookOption{ Content: testHookContent, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiGitHook *api.GitHook DecodeJSON(t, resp, &apiGitHook) assert.True(t, apiGitHook.IsActive) assert.Equal(t, testHookContent, apiGitHook.Content) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", - owner.Name, repo.Name, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive", owner.Name, repo.Name). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var apiGitHook2 *api.GitHook DecodeJSON(t, resp, &apiGitHook2) @@ -152,11 +152,10 @@ func TestAPIEditGitHookNoAccess(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", - owner.Name, repo.Name, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive", owner.Name, repo.Name) req := NewRequestWithJSON(t, "PATCH", urlStr, &api.EditGitHookOption{ Content: testHookContent, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) } @@ -170,12 +169,12 @@ func TestAPIDeleteGitHook(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", - owner.Name, repo.Name, token) + req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive", owner.Name, repo.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", - owner.Name, repo.Name, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive", owner.Name, repo.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiGitHook2 *api.GitHook DecodeJSON(t, resp, &apiGitHook2) @@ -191,7 +190,7 @@ func TestAPIDeleteGitHookNoAccess(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", - owner.Name, repo.Name, token) + req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive", owner.Name, repo.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) } diff --git a/tests/integration/api_repo_git_notes_test.go b/tests/integration/api_repo_git_notes_test.go index a7327d932748..9f3e927077e9 100644 --- a/tests/integration/api_repo_git_notes_test.go +++ b/tests/integration/api_repo_git_notes_test.go @@ -24,14 +24,17 @@ func TestAPIReposGitNotes(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) // check invalid requests - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/notes/12345?token=%s", user.Name, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/notes/12345", user.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/notes/..?token=%s", user.Name, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/notes/..", user.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) // check valid request - req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/notes/65f1bf27bc3bf70f64657658635e66094edbcb4d?token=%s", user.Name, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/notes/65f1bf27bc3bf70f64657658635e66094edbcb4d", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiData api.Note diff --git a/tests/integration/api_repo_git_ref_test.go b/tests/integration/api_repo_git_ref_test.go index 20900b324194..875752ae3fd8 100644 --- a/tests/integration/api_repo_git_ref_test.go +++ b/tests/integration/api_repo_git_ref_test.go @@ -24,13 +24,16 @@ func TestAPIReposGitRefs(t *testing.T) { "refs/heads/master", // Branch "refs/tags/v1.1", // Tag } { - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/%s?token="+token, user.Name, ref) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/%s", user.Name, ref). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) } // Test getting all refs - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/refs?token="+token, user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/refs", user.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) // Test getting non-existent refs - req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/refs/heads/unknown?token="+token, user.Name) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/refs/heads/unknown", user.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) } diff --git a/tests/integration/api_repo_git_tags_test.go b/tests/integration/api_repo_git_tags_test.go index a9d47abf9378..2e8510ab1b3a 100644 --- a/tests/integration/api_repo_git_tags_test.go +++ b/tests/integration/api_repo_git_tags_test.go @@ -45,7 +45,8 @@ func TestAPIGitTags(t *testing.T) { aTag, _ := gitRepo.GetTag(aTagName) // SHOULD work for annotated tags - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/tags/%s?token=%s", user.Name, repo.Name, aTag.ID.String(), token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/tags/%s", user.Name, repo.Name, aTag.ID.String()). + AddTokenAuth(token) res := MakeRequest(t, req, http.StatusOK) var tag *api.AnnotatedTag @@ -60,7 +61,8 @@ func TestAPIGitTags(t *testing.T) { assert.Equal(t, util.URLJoin(repo.APIURL(), "git/tags", aTag.ID.String()), tag.URL) // Should NOT work for lightweight tags - badReq := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/tags/%s?token=%s", user.Name, repo.Name, commit.ID.String(), token) + badReq := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/tags/%s", user.Name, repo.Name, commit.ID.String()). + AddTokenAuth(token) MakeRequest(t, badReq, http.StatusBadRequest) } @@ -72,17 +74,14 @@ func TestAPIDeleteTagByName(t *testing.T) { session := loginUser(t, owner.LowerName) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/tags/delete-tag?token=%s", - owner.Name, repo.Name, token) - - req := NewRequestf(t, http.MethodDelete, urlStr) + req := NewRequest(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/tags/delete-tag", owner.Name, repo.Name)). + AddTokenAuth(token) _ = MakeRequest(t, req, http.StatusNoContent) // Make sure that actual releases can't be deleted outright createNewReleaseUsingAPI(t, session, token, owner, repo, "release-tag", "", "Release Tag", "test") - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/tags/release-tag?token=%s", - owner.Name, repo.Name, token) - req = NewRequestf(t, http.MethodDelete, urlStr) + req = NewRequest(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/tags/release-tag", owner.Name, repo.Name)). + AddTokenAuth(token) _ = MakeRequest(t, req, http.StatusConflict) } diff --git a/tests/integration/api_repo_git_trees_test.go b/tests/integration/api_repo_git_trees_test.go index aa732b9946cf..8eec6d8d220d 100644 --- a/tests/integration/api_repo_git_trees_test.go +++ b/tests/integration/api_repo_git_trees_test.go @@ -50,7 +50,8 @@ func TestAPIReposGitTrees(t *testing.T) { } // Test using access token for a private repo that the user of the token owns - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/trees/%s?token=%s", user2.Name, repo16.Name, repo16TreeSHA, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/trees/%s", user2.Name, repo16.Name, repo16TreeSHA). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) // Test using bad sha @@ -58,7 +59,8 @@ func TestAPIReposGitTrees(t *testing.T) { MakeRequest(t, req, http.StatusBadRequest) // Test using org repo "org3/repo3" where user2 is a collaborator - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/trees/%s?token=%s", org3.Name, repo3.Name, repo3TreeSHA, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/trees/%s", org3.Name, repo3.Name, repo3TreeSHA). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" with no user token diff --git a/tests/integration/api_repo_hook_test.go b/tests/integration/api_repo_hook_test.go index 18b12597dbdb..f27fcc00d6b3 100644 --- a/tests/integration/api_repo_hook_test.go +++ b/tests/integration/api_repo_hook_test.go @@ -27,17 +27,14 @@ func TestAPICreateHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - completeURL := func(lastSegment string) string { - return fmt.Sprintf("/api/v1/repos/%s/%s/%s?token=%s", owner.Name, repo.Name, lastSegment, token) - } - req := NewRequestWithJSON(t, "POST", completeURL("hooks"), api.CreateHookOption{ + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/%s", owner.Name, repo.Name, "hooks"), api.CreateHookOption{ Type: "gitea", Config: api.CreateHookOptionConfig{ "content_type": "json", "url": "http://example.com/", }, AuthorizationHeader: "Bearer s3cr3t", - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var apiHook *api.Hook diff --git a/tests/integration/api_repo_lfs_migrate_test.go b/tests/integration/api_repo_lfs_migrate_test.go index 2cd7132b76cc..8b4d79db022c 100644 --- a/tests/integration/api_repo_lfs_migrate_test.go +++ b/tests/integration/api_repo_lfs_migrate_test.go @@ -33,12 +33,12 @@ func TestAPIRepoLFSMigrateLocal(t *testing.T) { session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+token, &api.MigrateRepoOptions{ + req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate", &api.MigrateRepoOptions{ CloneAddr: path.Join(setting.RepoRootPath, "migration/lfs-test.git"), RepoOwnerID: user.ID, RepoName: "lfs-test-local", LFS: true, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, NoExpectedStatus) assert.EqualValues(t, http.StatusCreated, resp.Code) diff --git a/tests/integration/api_repo_lfs_test.go b/tests/integration/api_repo_lfs_test.go index b0e9269bb86e..211dcf76c112 100644 --- a/tests/integration/api_repo_lfs_test.go +++ b/tests/integration/api_repo_lfs_test.go @@ -82,11 +82,10 @@ func TestAPILFSBatch(t *testing.T) { session := loginUser(t, "user2") - newRequest := func(t testing.TB, br *lfs.BatchRequest) *http.Request { - req := NewRequestWithJSON(t, "POST", "/user2/lfs-batch-repo.git/info/lfs/objects/batch", br) - req.Header.Set("Accept", lfs.MediaType) - req.Header.Set("Content-Type", lfs.MediaType) - return req + newRequest := func(t testing.TB, br *lfs.BatchRequest) *RequestWrapper { + return NewRequestWithJSON(t, "POST", "/user2/lfs-batch-repo.git/info/lfs/objects/batch", br). + SetHeader("Accept", lfs.MediaType). + SetHeader("Content-Type", lfs.MediaType) } decodeResponse := func(t *testing.T, b *bytes.Buffer) *lfs.BatchResponse { var br lfs.BatchResponse @@ -342,9 +341,8 @@ func TestAPILFSUpload(t *testing.T) { session := loginUser(t, "user2") - newRequest := func(t testing.TB, p lfs.Pointer, content string) *http.Request { - req := NewRequestWithBody(t, "PUT", path.Join("/user2/lfs-upload-repo.git/info/lfs/objects/", p.Oid, strconv.FormatInt(p.Size, 10)), strings.NewReader(content)) - return req + newRequest := func(t testing.TB, p lfs.Pointer, content string) *RequestWrapper { + return NewRequestWithBody(t, "PUT", path.Join("/user2/lfs-upload-repo.git/info/lfs/objects/", p.Oid, strconv.FormatInt(p.Size, 10)), strings.NewReader(content)) } t.Run("InvalidPointer", func(t *testing.T) { @@ -447,11 +445,10 @@ func TestAPILFSVerify(t *testing.T) { session := loginUser(t, "user2") - newRequest := func(t testing.TB, p *lfs.Pointer) *http.Request { - req := NewRequestWithJSON(t, "POST", "/user2/lfs-verify-repo.git/info/lfs/verify", p) - req.Header.Set("Accept", lfs.MediaType) - req.Header.Set("Content-Type", lfs.MediaType) - return req + newRequest := func(t testing.TB, p *lfs.Pointer) *RequestWrapper { + return NewRequestWithJSON(t, "POST", "/user2/lfs-verify-repo.git/info/lfs/verify", p). + SetHeader("Accept", lfs.MediaType). + SetHeader("Content-Type", lfs.MediaType) } t.Run("InvalidJsonRequest", func(t *testing.T) { diff --git a/tests/integration/api_repo_raw_test.go b/tests/integration/api_repo_raw_test.go index ccb20a939ee6..e5f83d1c80c0 100644 --- a/tests/integration/api_repo_raw_test.go +++ b/tests/integration/api_repo_raw_test.go @@ -27,12 +27,14 @@ func TestAPIReposRaw(t *testing.T) { "v1.1", // Tag "65f1bf27bc3bf70f64657658635e66094edbcb4d", // Commit } { - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/raw/%s/README.md?token="+token, user.Name, ref) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/raw/%s/README.md", user.Name, ref). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) assert.EqualValues(t, "file", resp.Header().Get("x-gitea-object-type")) } // Test default branch - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/raw/README.md?token="+token, user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/raw/README.md", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) assert.EqualValues(t, "file", resp.Header().Get("x-gitea-object-type")) } diff --git a/tests/integration/api_repo_secrets_test.go b/tests/integration/api_repo_secrets_test.go index 263ad1608cda..feb9bae2b22c 100644 --- a/tests/integration/api_repo_secrets_test.go +++ b/tests/integration/api_repo_secrets_test.go @@ -60,44 +60,47 @@ func TestAPIRepoSecrets(t *testing.T) { } for _, c := range cases { - req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/actions/secrets/%s?token=%s", repo.FullName(), c.Name, token), api.CreateOrUpdateSecretOption{ + req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/actions/secrets/%s", repo.FullName(), c.Name), api.CreateOrUpdateSecretOption{ Data: "data", - }) + }).AddTokenAuth(token) MakeRequest(t, req, c.ExpectedStatus) } }) t.Run("Update", func(t *testing.T) { name := "update_secret" - url := fmt.Sprintf("/api/v1/repos/%s/actions/secrets/%s?token=%s", repo.FullName(), name, token) + url := fmt.Sprintf("/api/v1/repos/%s/actions/secrets/%s", repo.FullName(), name) req := NewRequestWithJSON(t, "PUT", url, api.CreateOrUpdateSecretOption{ Data: "initial", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) req = NewRequestWithJSON(t, "PUT", url, api.CreateOrUpdateSecretOption{ Data: "changed", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) }) t.Run("Delete", func(t *testing.T) { name := "delete_secret" - url := fmt.Sprintf("/api/v1/repos/%s/actions/secrets/%s?token=%s", repo.FullName(), name, token) + url := fmt.Sprintf("/api/v1/repos/%s/actions/secrets/%s", repo.FullName(), name) req := NewRequestWithJSON(t, "PUT", url, api.CreateOrUpdateSecretOption{ Data: "initial", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) - req = NewRequest(t, "DELETE", url) + req = NewRequest(t, "DELETE", url). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "DELETE", url) + req = NewRequest(t, "DELETE", url). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/actions/secrets/000?token=%s", repo.FullName(), token)) + req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/actions/secrets/000", repo.FullName())). + AddTokenAuth(token) MakeRequest(t, req, http.StatusBadRequest) }) } diff --git a/tests/integration/api_repo_tags_test.go b/tests/integration/api_repo_tags_test.go index c4282f99284d..c6eeb404c02c 100644 --- a/tests/integration/api_repo_tags_test.go +++ b/tests/integration/api_repo_tags_test.go @@ -27,7 +27,8 @@ func TestAPIRepoTags(t *testing.T) { repoName := "repo1" - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/tags?token=%s", user.Name, repoName, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/tags", user.Name, repoName). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var tags []*api.Tag @@ -55,14 +56,16 @@ func TestAPIRepoTags(t *testing.T) { } // get created tag - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/tags/%s?token=%s", user.Name, repoName, newTag.Name, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/tags/%s", user.Name, repoName, newTag.Name). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var tag *api.Tag DecodeJSON(t, resp, &tag) assert.EqualValues(t, newTag, tag) // delete tag - delReq := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/tags/%s?token=%s", user.Name, repoName, newTag.Name, token) + delReq := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/tags/%s", user.Name, repoName, newTag.Name). + AddTokenAuth(token) MakeRequest(t, delReq, http.StatusNoContent) // check if it's gone @@ -70,12 +73,12 @@ func TestAPIRepoTags(t *testing.T) { } func createNewTagUsingAPI(t *testing.T, session *TestSession, token, ownerName, repoName, name, target, msg string) *api.Tag { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/tags?token=%s", ownerName, repoName, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/tags", ownerName, repoName) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateTagOption{ TagName: name, Message: msg, Target: target, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var respObj api.Tag diff --git a/tests/integration/api_repo_teams_test.go b/tests/integration/api_repo_teams_test.go index 23cf8a25672f..558bac815014 100644 --- a/tests/integration/api_repo_teams_test.go +++ b/tests/integration/api_repo_teams_test.go @@ -31,8 +31,8 @@ func TestAPIRepoTeams(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) // ListTeams - url := fmt.Sprintf("/api/v1/repos/%s/teams?token=%s", publicOrgRepo.FullName(), token) - req := NewRequest(t, "GET", url) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/teams", publicOrgRepo.FullName())). + AddTokenAuth(token) res := MakeRequest(t, req, http.StatusOK) var teams []*api.Team DecodeJSON(t, res, &teams) @@ -49,34 +49,34 @@ func TestAPIRepoTeams(t *testing.T) { } // IsTeam - url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "Test_Team", token) - req = NewRequest(t, "GET", url) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/teams/%s", publicOrgRepo.FullName(), "Test_Team")). + AddTokenAuth(token) res = MakeRequest(t, req, http.StatusOK) var team *api.Team DecodeJSON(t, res, &team) assert.EqualValues(t, teams[1], team) - url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "NonExistingTeam", token) - req = NewRequest(t, "GET", url) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/teams/%s", publicOrgRepo.FullName(), "NonExistingTeam")). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) // AddTeam with user4 - url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "team1", token) - req = NewRequest(t, "PUT", url) + req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/teams/%s", publicOrgRepo.FullName(), "team1")). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) // AddTeam with user2 user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session = loginUser(t, user.Name) token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "team1", token) - req = NewRequest(t, "PUT", url) + req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/teams/%s", publicOrgRepo.FullName(), "team1")). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) MakeRequest(t, req, http.StatusUnprocessableEntity) // test duplicate request // DeleteTeam - url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "team1", token) - req = NewRequest(t, "DELETE", url) + req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/teams/%s", publicOrgRepo.FullName(), "team1")). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) MakeRequest(t, req, http.StatusUnprocessableEntity) // test duplicate request } diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index fa159c6c5b9c..90f84c794e12 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -45,8 +45,8 @@ func TestAPIUserReposWithWrongToken(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) wrongToken := fmt.Sprintf("Bearer %s", "wrong_token") - req := NewRequestf(t, "GET", "/api/v1/users/%s/repos", user.Name) - req = addTokenAuthHeader(req, wrongToken) + req := NewRequestf(t, "GET", "/api/v1/users/%s/repos", user.Name). + AddTokenAuth(wrongToken) resp := MakeRequest(t, req, http.StatusUnauthorized) assert.Contains(t, resp.Body.String(), "user does not exist") @@ -208,7 +208,8 @@ func TestAPISearchRepo(t *testing.T) { } t.Run(testName, func(t *testing.T) { - request := NewRequest(t, "GET", testCase.requestURL+"&token="+token) + request := NewRequest(t, "GET", testCase.requestURL). + AddTokenAuth(token) response := MakeRequest(t, request, http.StatusOK) var body api.SearchResults @@ -309,7 +310,8 @@ func TestAPIOrgRepos(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrganization) t.Run(testName, func(t *testing.T) { - req := NewRequestf(t, "GET", "/api/v1/orgs/%s/repos?token="+token, sourceOrg.Name) + req := NewRequestf(t, "GET", "/api/v1/orgs/%s/repos", sourceOrg.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiRepos []*api.Repository @@ -329,7 +331,8 @@ func TestAPIGetRepoByIDUnauthorized(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repositories/2?token="+token) + req := NewRequest(t, "GET", "/api/v1/repositories/2"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) } @@ -353,11 +356,11 @@ func TestAPIRepoMigrate(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+token, &api.MigrateRepoOptions{ + req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate", &api.MigrateRepoOptions{ CloneAddr: testCase.cloneURL, RepoOwnerID: testCase.userID, RepoName: testCase.repoName, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, NoExpectedStatus) if resp.Code == http.StatusUnprocessableEntity { respJSON := map[string]string{} @@ -398,12 +401,13 @@ func testAPIRepoMigrateConflict(t *testing.T, u *url.URL) { cloneURL := "https://github.com/go-gitea/test_repo.git" - req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+httpContext.Token, + req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate", &api.MigrateRepoOptions{ CloneAddr: cloneURL, RepoOwnerID: userID, RepoName: httpContext.Reponame, - }) + }). + AddTokenAuth(httpContext.Token) resp := httpContext.Session.MakeRequest(t, req, http.StatusConflict) respJSON := map[string]string{} DecodeJSON(t, resp, &respJSON) @@ -425,7 +429,8 @@ func TestAPIMirrorSyncNonMirrorRepo(t *testing.T) { DecodeJSON(t, resp, &repo) assert.False(t, repo.Mirror) - req = NewRequestf(t, "POST", "/api/v1/repos/user2/repo1/mirror-sync?token=%s", token) + req = NewRequestf(t, "POST", "/api/v1/repos/user2/repo1/mirror-sync"). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusBadRequest) errRespJSON := map[string]string{} DecodeJSON(t, resp, &errRespJSON) @@ -450,9 +455,9 @@ func TestAPIOrgRepoCreate(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteOrganization, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/org/%s/repos?token="+token, testCase.orgName), &api.CreateRepoOption{ + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/org/%s/repos", testCase.orgName), &api.CreateRepoOption{ Name: testCase.repoName, - }) + }).AddTokenAuth(token) MakeRequest(t, req, testCase.expectedStatus) } } @@ -473,10 +478,11 @@ func testAPIRepoCreateConflict(t *testing.T, u *url.URL) { httpContext.Reponame = "repo-tmp-17" t.Run("CreateRepo", doAPICreateRepository(httpContext, false)) - req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos?token="+httpContext.Token, + req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos", &api.CreateRepoOption{ Name: httpContext.Reponame, - }) + }). + AddTokenAuth(httpContext.Token) resp := httpContext.Session.MakeRequest(t, req, http.StatusConflict) respJSON := map[string]string{} DecodeJSON(t, resp, &respJSON) @@ -516,13 +522,13 @@ func TestAPIRepoTransfer(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser) repoName := "moveME" apiRepo := new(api.Repository) - req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/user/repos?token=%s", token), &api.CreateRepoOption{ + req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos", &api.CreateRepoOption{ Name: repoName, Description: "repo move around", Private: false, Readme: "Default", AutoInit: true, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, apiRepo) @@ -532,10 +538,10 @@ func TestAPIRepoTransfer(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}) session = loginUser(t, user.Name) token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer?token=%s", repo.OwnerName, repo.Name, token), &api.TransferRepoOption{ + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer", repo.OwnerName, repo.Name), &api.TransferRepoOption{ NewOwner: testCase.newOwner, TeamIDs: testCase.teams, - }) + }).AddTokenAuth(token) MakeRequest(t, req, testCase.expectedStatus) } @@ -551,21 +557,21 @@ func transfer(t *testing.T) *repo_model.Repository { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser) repoName := "moveME" apiRepo := new(api.Repository) - req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/user/repos?token=%s", token), &api.CreateRepoOption{ + req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos", &api.CreateRepoOption{ Name: repoName, Description: "repo move around", Private: false, Readme: "Default", AutoInit: true, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, apiRepo) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}) - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer?token=%s", repo.OwnerName, repo.Name, token), &api.TransferRepoOption{ + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer", repo.OwnerName, repo.Name), &api.TransferRepoOption{ NewOwner: "user4", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) return repo @@ -579,18 +585,21 @@ func TestAPIAcceptTransfer(t *testing.T) { // try to accept with not authorized user session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser) - req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) + req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject", repo.OwnerName, repo.Name)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) // try to accept repo that's not marked as transferred - req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/accept?token=%s", "user2", "repo1", token)) + req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/accept", "user2", "repo1")). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) // accept transfer session = loginUser(t, "user4") token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser) - req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/accept?token=%s", repo.OwnerName, repo.Name, token)) + req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/accept", repo.OwnerName, repo.Name)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusAccepted) apiRepo := new(api.Repository) DecodeJSON(t, resp, apiRepo) @@ -605,18 +614,21 @@ func TestAPIRejectTransfer(t *testing.T) { // try to reject with not authorized user session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) + req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject", repo.OwnerName, repo.Name)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) // try to reject repo that's not marked as transferred - req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", "user2", "repo1", token)) + req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject", "user2", "repo1")). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) // reject transfer session = loginUser(t, "user4") token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) + req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject", repo.OwnerName, repo.Name)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) apiRepo := new(api.Repository) DecodeJSON(t, resp, apiRepo) @@ -634,26 +646,26 @@ func TestAPIGenerateRepo(t *testing.T) { // user repo := new(api.Repository) - req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/generate?token=%s", templateRepo.OwnerName, templateRepo.Name, token), &api.GenerateRepoOption{ + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/generate", templateRepo.OwnerName, templateRepo.Name), &api.GenerateRepoOption{ Owner: user.Name, Name: "new-repo", Description: "test generate repo", Private: false, GitContent: true, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, repo) assert.Equal(t, "new-repo", repo.Name) // org - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/generate?token=%s", templateRepo.OwnerName, templateRepo.Name, token), &api.GenerateRepoOption{ + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/generate", templateRepo.OwnerName, templateRepo.Name), &api.GenerateRepoOption{ Owner: "org3", Name: "new-repo", Description: "test generate repo", Private: false, GitContent: true, - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, repo) @@ -667,7 +679,8 @@ func TestAPIRepoGetReviewers(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/reviewers?token=%s", user.Name, repo.Name, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/reviewers", user.Name, repo.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var reviewers []*api.User DecodeJSON(t, resp, &reviewers) @@ -681,7 +694,8 @@ func TestAPIRepoGetAssignees(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/assignees?token=%s", user.Name, repo.Name, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/assignees", user.Name, repo.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var assignees []*api.User DecodeJSON(t, resp, &assignees) diff --git a/tests/integration/api_repo_topic_test.go b/tests/integration/api_repo_topic_test.go index e7c9b95543b3..c41bc4abb638 100644 --- a/tests/integration/api_repo_topic_test.go +++ b/tests/integration/api_repo_topic_test.go @@ -63,30 +63,33 @@ func TestAPIRepoTopic(t *testing.T) { token2 := getUserToken(t, user2.Name, auth_model.AccessTokenScopeWriteRepository) // Test read topics using login - url := fmt.Sprintf("/api/v1/repos/%s/%s/topics", user2.Name, repo2.Name) - req := NewRequest(t, "GET", url+"?token="+token2) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/topics", user2.Name, repo2.Name)). + AddTokenAuth(token2) res := MakeRequest(t, req, http.StatusOK) var topics *api.TopicName DecodeJSON(t, res, &topics) assert.ElementsMatch(t, []string{"topicname1", "topicname2"}, topics.TopicNames) - // Log out user2 - url = fmt.Sprintf("/api/v1/repos/%s/%s/topics?token=%s", user2.Name, repo2.Name, token2) - // Test delete a topic - req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/topics/%s?token=%s", user2.Name, repo2.Name, "Topicname1", token2) + req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/topics/%s", user2.Name, repo2.Name, "Topicname1"). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) // Test add an existing topic - req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s?token=%s", user2.Name, repo2.Name, "Golang", token2) + req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s", user2.Name, repo2.Name, "Golang"). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) // Test add a topic - req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s?token=%s", user2.Name, repo2.Name, "topicName3", token2) + req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s", user2.Name, repo2.Name, "topicName3"). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) + url := fmt.Sprintf("/api/v1/repos/%s/%s/topics", user2.Name, repo2.Name) + // Test read topics using token - req = NewRequest(t, "GET", url) + req = NewRequest(t, "GET", url). + AddTokenAuth(token2) res = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, res, &topics) assert.ElementsMatch(t, []string{"topicname2", "golang", "topicname3"}, topics.TopicNames) @@ -95,9 +98,10 @@ func TestAPIRepoTopic(t *testing.T) { newTopics := []string{" windows ", " ", "MAC "} req = NewRequestWithJSON(t, "PUT", url, &api.RepoTopicOptions{ Topics: newTopics, - }) + }).AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "GET", url) + req = NewRequest(t, "GET", url). + AddTokenAuth(token2) res = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, res, &topics) assert.ElementsMatch(t, []string{"windows", "mac"}, topics.TopicNames) @@ -106,9 +110,10 @@ func TestAPIRepoTopic(t *testing.T) { newTopics = []string{"topicname1", "topicname2", "topicname!"} req = NewRequestWithJSON(t, "PUT", url, &api.RepoTopicOptions{ Topics: newTopics, - }) + }).AddTokenAuth(token2) MakeRequest(t, req, http.StatusUnprocessableEntity) - req = NewRequest(t, "GET", url) + req = NewRequest(t, "GET", url). + AddTokenAuth(token2) res = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, res, &topics) assert.ElementsMatch(t, []string{"windows", "mac"}, topics.TopicNames) @@ -117,9 +122,10 @@ func TestAPIRepoTopic(t *testing.T) { newTopics = []string{"t1", "t2", "t1", "t3", "t4", "t5", "t6", "t7", "t8", "t9", "t10", "t11", "t12", "t13", "t14", "t15", "t16", "17", "t18", "t19", "t20", "t21", "t22", "t23", "t24", "t25"} req = NewRequestWithJSON(t, "PUT", url, &api.RepoTopicOptions{ Topics: newTopics, - }) + }).AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "GET", url) + req = NewRequest(t, "GET", url). + AddTokenAuth(token2) res = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, res, &topics) assert.Len(t, topics.TopicNames, 25) @@ -128,28 +134,31 @@ func TestAPIRepoTopic(t *testing.T) { newTopics = append(newTopics, "t26") req = NewRequestWithJSON(t, "PUT", url, &api.RepoTopicOptions{ Topics: newTopics, - }) + }).AddTokenAuth(token2) MakeRequest(t, req, http.StatusUnprocessableEntity) // Test add a topic when there is already maximum - req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s?token=%s", user2.Name, repo2.Name, "t26", token2) + req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s", user2.Name, repo2.Name, "t26"). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusUnprocessableEntity) // Test delete a topic that repo doesn't have - req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/topics/%s?token=%s", user2.Name, repo2.Name, "Topicname1", token2) + req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/topics/%s", user2.Name, repo2.Name, "Topicname1"). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNotFound) // Get user4's token token4 := getUserToken(t, user4.Name, auth_model.AccessTokenScopeWriteRepository) // Test read topics with write access - url = fmt.Sprintf("/api/v1/repos/%s/%s/topics?token=%s", org3.Name, repo3.Name, token4) - req = NewRequest(t, "GET", url) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/topics", org3.Name, repo3.Name)). + AddTokenAuth(token4) res = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, res, &topics) assert.Empty(t, topics.TopicNames) // Test add a topic to repo with write access (requires repo admin access) - req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s?token=%s", org3.Name, repo3.Name, "topicName", token4) + req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s", org3.Name, repo3.Name, "topicName"). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusForbidden) } diff --git a/tests/integration/api_team_test.go b/tests/integration/api_team_test.go index a9ae89071747..4df545284e97 100644 --- a/tests/integration/api_team_test.go +++ b/tests/integration/api_team_test.go @@ -34,7 +34,8 @@ func TestAPITeam(t *testing.T) { session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrganization) - req := NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamUser.TeamID) + req := NewRequestf(t, "GET", "/api/v1/teams/%d", teamUser.TeamID). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiTeam api.Team @@ -49,7 +50,8 @@ func TestAPITeam(t *testing.T) { session = loginUser(t, user2.Name) token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrganization) - req = NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamUser.TeamID) + req = NewRequestf(t, "GET", "/api/v1/teams/%d", teamUser.TeamID). + AddTokenAuth(token) _ = MakeRequest(t, req, http.StatusForbidden) req = NewRequestf(t, "GET", "/api/v1/teams/%d", teamUser.TeamID) @@ -70,7 +72,8 @@ func TestAPITeam(t *testing.T) { Permission: "write", Units: []string{"repo.code", "repo.issues"}, } - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams?token=%s", org.Name, token), teamToCreate) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams", org.Name), teamToCreate). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusCreated) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -91,7 +94,8 @@ func TestAPITeam(t *testing.T) { Units: []string{"repo.code", "repo.pulls", "repo.releases"}, } - req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/teams/%d?token=%s", teamID, token), teamToEdit) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/teams/%d", teamID), teamToEdit). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -103,7 +107,8 @@ func TestAPITeam(t *testing.T) { // Edit team Description only editDescription = "first team" teamToEditDesc := api.EditTeamOption{Description: &editDescription} - req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/teams/%d?token=%s", teamID, token), teamToEditDesc) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/teams/%d", teamID), teamToEditDesc). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -115,7 +120,8 @@ func TestAPITeam(t *testing.T) { // Read team. teamRead := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) assert.NoError(t, teamRead.LoadUnits(db.DefaultContext)) - req = NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamID) + req = NewRequestf(t, "GET", "/api/v1/teams/%d", teamID). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -123,7 +129,8 @@ func TestAPITeam(t *testing.T) { teamRead.AccessMode.String(), teamRead.GetUnitNames(), teamRead.GetUnitsMap()) // Delete team. - req = NewRequestf(t, "DELETE", "/api/v1/teams/%d?token="+token, teamID) + req = NewRequestf(t, "DELETE", "/api/v1/teams/%d", teamID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &organization.Team{ID: teamID}) @@ -136,7 +143,8 @@ func TestAPITeam(t *testing.T) { Permission: "write", UnitsMap: map[string]string{"repo.code": "read", "repo.issues": "write", "repo.wiki": "none"}, } - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams?token=%s", org.Name, token), teamToCreate) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams", org.Name), teamToCreate). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusCreated) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -157,7 +165,8 @@ func TestAPITeam(t *testing.T) { UnitsMap: map[string]string{"repo.code": "read", "repo.pulls": "read", "repo.releases": "write"}, } - req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/teams/%d?token=%s", teamID, token), teamToEdit) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/teams/%d", teamID), teamToEdit). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -169,7 +178,8 @@ func TestAPITeam(t *testing.T) { // Edit team Description only editDescription = "second team" teamToEditDesc = api.EditTeamOption{Description: &editDescription} - req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/teams/%d?token=%s", teamID, token), teamToEditDesc) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/teams/%d", teamID), teamToEditDesc). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -180,7 +190,8 @@ func TestAPITeam(t *testing.T) { // Read team. teamRead = unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - req = NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamID) + req = NewRequestf(t, "GET", "/api/v1/teams/%d", teamID). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -189,7 +200,8 @@ func TestAPITeam(t *testing.T) { teamRead.AccessMode.String(), teamRead.GetUnitNames(), teamRead.GetUnitsMap()) // Delete team. - req = NewRequestf(t, "DELETE", "/api/v1/teams/%d?token="+token, teamID) + req = NewRequestf(t, "DELETE", "/api/v1/teams/%d", teamID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &organization.Team{ID: teamID}) @@ -200,7 +212,8 @@ func TestAPITeam(t *testing.T) { IncludesAllRepositories: true, Permission: "admin", } - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams?token=%s", org.Name, token), teamToCreate) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams", org.Name), teamToCreate). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusCreated) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -219,7 +232,8 @@ func TestAPITeam(t *testing.T) { teamID = apiTeam.ID // Delete team. - req = NewRequestf(t, "DELETE", "/api/v1/teams/%d?token="+token, teamID) + req = NewRequestf(t, "DELETE", "/api/v1/teams/%d", teamID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &organization.Team{ID: teamID}) } @@ -263,7 +277,8 @@ func TestAPITeamSearch(t *testing.T) { var results TeamSearchResults token := getUserToken(t, user.Name, auth_model.AccessTokenScopeReadOrganization) - req := NewRequestf(t, "GET", "/api/v1/orgs/%s/teams/search?q=%s&token=%s", org.Name, "_team", token) + req := NewRequestf(t, "GET", "/api/v1/orgs/%s/teams/search?q=%s", org.Name, "_team"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &results) assert.NotEmpty(t, results.Data) @@ -274,7 +289,8 @@ func TestAPITeamSearch(t *testing.T) { user5 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) token5 := getUserToken(t, user5.Name, auth_model.AccessTokenScopeReadOrganization) - req = NewRequestf(t, "GET", "/api/v1/orgs/%s/teams/search?q=%s&token=%s", org.Name, "team", token5) + req = NewRequestf(t, "GET", "/api/v1/orgs/%s/teams/search?q=%s", org.Name, "team"). + AddTokenAuth(token5) MakeRequest(t, req, http.StatusForbidden) } @@ -288,7 +304,8 @@ func TestAPIGetTeamRepo(t *testing.T) { var results api.Repository token := getUserToken(t, user.Name, auth_model.AccessTokenScopeReadOrganization) - req := NewRequestf(t, "GET", "/api/v1/teams/%d/repos/%s/?token=%s", team.ID, teamRepo.FullName(), token) + req := NewRequestf(t, "GET", "/api/v1/teams/%d/repos/%s/", team.ID, teamRepo.FullName()). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &results) assert.Equal(t, "big_test_private_4", teamRepo.Name) @@ -297,6 +314,7 @@ func TestAPIGetTeamRepo(t *testing.T) { user5 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) token5 := getUserToken(t, user5.Name, auth_model.AccessTokenScopeReadOrganization) - req = NewRequestf(t, "GET", "/api/v1/teams/%d/repos/%s/?token=%s", team.ID, teamRepo.FullName(), token5) + req = NewRequestf(t, "GET", "/api/v1/teams/%d/repos/%s/", team.ID, teamRepo.FullName()). + AddTokenAuth(token5) MakeRequest(t, req, http.StatusNotFound) } diff --git a/tests/integration/api_team_user_test.go b/tests/integration/api_team_user_test.go index aa33c690413b..6c80bc9f80b0 100644 --- a/tests/integration/api_team_user_test.go +++ b/tests/integration/api_team_user_test.go @@ -25,10 +25,12 @@ func TestAPITeamUser(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrganization) - req := NewRequest(t, "GET", "/api/v1/teams/1/members/user1?token="+token) + req := NewRequest(t, "GET", "/api/v1/teams/1/members/user1"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", "/api/v1/teams/1/members/user2?token="+token) + req = NewRequest(t, "GET", "/api/v1/teams/1/members/user2"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var user2 *api.User DecodeJSON(t, resp, &user2) diff --git a/tests/integration/api_token_test.go b/tests/integration/api_token_test.go index e28d9a372f3f..9c7bf37330d0 100644 --- a/tests/integration/api_token_test.go +++ b/tests/integration/api_token_test.go @@ -35,8 +35,8 @@ func TestAPIDeleteMissingToken(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - req := NewRequestf(t, "DELETE", "/api/v1/users/user1/tokens/%d", unittest.NonexistentID) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestf(t, "DELETE", "/api/v1/users/user1/tokens/%d", unittest.NonexistentID). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) } @@ -46,20 +46,20 @@ func TestAPIGetTokensPermission(t *testing.T) { // admin can get tokens for other users user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - req := NewRequestf(t, "GET", "/api/v1/users/user2/tokens") - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", "/api/v1/users/user2/tokens"). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) // non-admin can get tokens for himself user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - req = NewRequestf(t, "GET", "/api/v1/users/user2/tokens") - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", "/api/v1/users/user2/tokens"). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) // non-admin can't get tokens for other users user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) - req = NewRequestf(t, "GET", "/api/v1/users/user2/tokens") - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", "/api/v1/users/user2/tokens"). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusForbidden) } @@ -73,20 +73,20 @@ func TestAPIDeleteTokensPermission(t *testing.T) { // admin can delete tokens for other users createAPIAccessTokenWithoutCleanUp(t, "test-key-1", user2, nil) - req := NewRequestf(t, "DELETE", "/api/v1/users/"+user2.LoginName+"/tokens/test-key-1") - req = AddBasicAuthHeader(req, admin.Name) + req := NewRequest(t, "DELETE", "/api/v1/users/"+user2.LoginName+"/tokens/test-key-1"). + AddBasicAuth(admin.Name) MakeRequest(t, req, http.StatusNoContent) // non-admin can delete tokens for himself createAPIAccessTokenWithoutCleanUp(t, "test-key-2", user2, nil) - req = NewRequestf(t, "DELETE", "/api/v1/users/"+user2.LoginName+"/tokens/test-key-2") - req = AddBasicAuthHeader(req, user2.Name) + req = NewRequest(t, "DELETE", "/api/v1/users/"+user2.LoginName+"/tokens/test-key-2"). + AddBasicAuth(user2.Name) MakeRequest(t, req, http.StatusNoContent) // non-admin can't delete tokens for other users createAPIAccessTokenWithoutCleanUp(t, "test-key-3", user2, nil) - req = NewRequestf(t, "DELETE", "/api/v1/users/"+user2.LoginName+"/tokens/test-key-3") - req = AddBasicAuthHeader(req, user4.Name) + req = NewRequest(t, "DELETE", "/api/v1/users/"+user2.LoginName+"/tokens/test-key-3"). + AddBasicAuth(user4.Name) MakeRequest(t, req, http.StatusForbidden) } @@ -117,9 +117,6 @@ func TestAPIDeniesPermissionBasedOnTokenScope(t *testing.T) { // from other endpoints and not updated. // // Test cases are in alphabetical order by URL. - // - // Note: query parameters are not currently supported since the token is - // appended with `?=token=`. testCases := []requiredScopeTestCase{ { "/api/v1/admin/emails", @@ -526,11 +523,9 @@ func runTestCase(t *testing.T, testCase *requiredScopeTestCase, user *user_model accessToken := createAPIAccessTokenWithoutCleanUp(t, "test-token", user, &unauthorizedScopes) defer deleteAPIAccessToken(t, accessToken, user) - // Add API access token to the URL. - url := fmt.Sprintf("%s?token=%s", testCase.url, accessToken.Token) - // Request the endpoint. Verify that permission is denied. - req := NewRequestf(t, testCase.method, url) + req := NewRequest(t, testCase.method, testCase.url). + AddTokenAuth(accessToken.Token) MakeRequest(t, req, http.StatusForbidden) }) } @@ -552,9 +547,8 @@ func createAPIAccessTokenWithoutCleanUp(t *testing.T, tokenName string, user *us } } log.Debug("Requesting creation of token with scopes: %v", scopes) - req := NewRequestWithJSON(t, "POST", "/api/v1/users/"+user.LoginName+"/tokens", payload) - - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithJSON(t, "POST", "/api/v1/users/"+user.LoginName+"/tokens", payload). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusCreated) var newAccessToken api.AccessToken @@ -572,8 +566,8 @@ func createAPIAccessTokenWithoutCleanUp(t *testing.T, tokenName string, user *us // createAPIAccessTokenWithoutCleanUp Delete an API access token and assert that // deletion succeeded. func deleteAPIAccessToken(t *testing.T, accessToken api.AccessToken, user *user_model.User) { - req := NewRequestf(t, "DELETE", "/api/v1/users/"+user.LoginName+"/tokens/%d", accessToken.ID) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestf(t, "DELETE", "/api/v1/users/"+user.LoginName+"/tokens/%d", accessToken.ID). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &auth_model.AccessToken{ID: accessToken.ID}) diff --git a/tests/integration/api_twofa_test.go b/tests/integration/api_twofa_test.go index 1e5e26b8ccb0..aad806b6dc4f 100644 --- a/tests/integration/api_twofa_test.go +++ b/tests/integration/api_twofa_test.go @@ -23,8 +23,8 @@ func TestAPITwoFactor(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 16}) - req := NewRequestf(t, "GET", "/api/v1/user") - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", "/api/v1/user"). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) otpKey, err := totp.Generate(totp.GenerateOpts{ @@ -41,15 +41,15 @@ func TestAPITwoFactor(t *testing.T) { assert.NoError(t, auth_model.NewTwoFactor(db.DefaultContext, tfa)) - req = NewRequestf(t, "GET", "/api/v1/user") - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", "/api/v1/user"). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusUnauthorized) passcode, err := totp.GenerateCode(otpKey.Secret(), time.Now()) assert.NoError(t, err) - req = NewRequestf(t, "GET", "/api/v1/user") - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", "/api/v1/user"). + AddBasicAuth(user.Name) req.Header.Set("X-Gitea-OTP", passcode) MakeRequest(t, req, http.StatusOK) } diff --git a/tests/integration/api_user_avatar_test.go b/tests/integration/api_user_avatar_test.go index 807c119e2c99..5b4546f1504a 100644 --- a/tests/integration/api_user_avatar_test.go +++ b/tests/integration/api_user_avatar_test.go @@ -35,14 +35,16 @@ func TestAPIUpdateUserAvatar(t *testing.T) { Image: base64.StdEncoding.EncodeToString(avatar), } - req := NewRequestWithJSON(t, "POST", "/api/v1/user/avatar?token="+token, &opts) + req := NewRequestWithJSON(t, "POST", "/api/v1/user/avatar", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) opts = api.UpdateUserAvatarOption{ Image: "Invalid", } - req = NewRequestWithJSON(t, "POST", "/api/v1/user/avatar?token="+token, &opts) + req = NewRequestWithJSON(t, "POST", "/api/v1/user/avatar", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusBadRequest) // Test what happens if you use a file that is not an image @@ -56,7 +58,8 @@ func TestAPIUpdateUserAvatar(t *testing.T) { Image: base64.StdEncoding.EncodeToString(text), } - req = NewRequestWithJSON(t, "POST", "/api/v1/user/avatar?token="+token, &opts) + req = NewRequestWithJSON(t, "POST", "/api/v1/user/avatar", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusInternalServerError) } @@ -67,6 +70,7 @@ func TestAPIDeleteUserAvatar(t *testing.T) { session := loginUser(t, normalUsername) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteUser) - req := NewRequest(t, "DELETE", "/api/v1/user/avatar?token="+token) + req := NewRequest(t, "DELETE", "/api/v1/user/avatar"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) } diff --git a/tests/integration/api_user_email_test.go b/tests/integration/api_user_email_test.go index 9fff42af4225..6eeb54744455 100644 --- a/tests/integration/api_user_email_test.go +++ b/tests/integration/api_user_email_test.go @@ -21,7 +21,8 @@ func TestAPIListEmails(t *testing.T) { session := loginUser(t, normalUsername) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadUser) - req := NewRequest(t, "GET", "/api/v1/user/emails?token="+token) + req := NewRequest(t, "GET", "/api/v1/user/emails"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var emails []*api.Email @@ -52,13 +53,15 @@ func TestAPIAddEmail(t *testing.T) { Emails: []string{"user101@example.com"}, } - req := NewRequestWithJSON(t, "POST", "/api/v1/user/emails?token="+token, &opts) + req := NewRequestWithJSON(t, "POST", "/api/v1/user/emails", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) opts = api.CreateEmailOption{ Emails: []string{"user2-3@example.com"}, } - req = NewRequestWithJSON(t, "POST", "/api/v1/user/emails?token="+token, &opts) + req = NewRequestWithJSON(t, "POST", "/api/v1/user/emails", &opts). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var emails []*api.Email @@ -74,7 +77,8 @@ func TestAPIAddEmail(t *testing.T) { opts = api.CreateEmailOption{ Emails: []string{"notAEmail"}, } - req = NewRequestWithJSON(t, "POST", "/api/v1/user/emails?token="+token, &opts) + req = NewRequestWithJSON(t, "POST", "/api/v1/user/emails", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) } @@ -88,16 +92,19 @@ func TestAPIDeleteEmail(t *testing.T) { opts := api.DeleteEmailOption{ Emails: []string{"user2-3@example.com"}, } - req := NewRequestWithJSON(t, "DELETE", "/api/v1/user/emails?token="+token, &opts) + req := NewRequestWithJSON(t, "DELETE", "/api/v1/user/emails", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) opts = api.DeleteEmailOption{ Emails: []string{"user2-2@example.com"}, } - req = NewRequestWithJSON(t, "DELETE", "/api/v1/user/emails?token="+token, &opts) + req = NewRequestWithJSON(t, "DELETE", "/api/v1/user/emails", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "GET", "/api/v1/user/emails?token="+token) + req = NewRequest(t, "GET", "/api/v1/user/emails"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var emails []*api.Email diff --git a/tests/integration/api_user_follow_test.go b/tests/integration/api_user_follow_test.go index 62717af90e2a..1762732c10e6 100644 --- a/tests/integration/api_user_follow_test.go +++ b/tests/integration/api_user_follow_test.go @@ -30,14 +30,16 @@ func TestAPIFollow(t *testing.T) { t.Run("Follow", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/following/%s?token=%s", user1, token2)) + req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/following/%s", user1)). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) }) t.Run("ListFollowing", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/following?token=%s", user2, token2)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/following", user2)). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusOK) var users []api.User @@ -49,7 +51,8 @@ func TestAPIFollow(t *testing.T) { t.Run("ListMyFollowing", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/following?token=%s", token2)) + req := NewRequest(t, "GET", "/api/v1/user/following"). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusOK) var users []api.User @@ -61,7 +64,8 @@ func TestAPIFollow(t *testing.T) { t.Run("ListFollowers", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/followers?token=%s", user1, token1)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/followers", user1)). + AddTokenAuth(token1) resp := MakeRequest(t, req, http.StatusOK) var users []api.User @@ -73,7 +77,8 @@ func TestAPIFollow(t *testing.T) { t.Run("ListMyFollowers", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/followers?token=%s", token1)) + req := NewRequest(t, "GET", "/api/v1/user/followers"). + AddTokenAuth(token1) resp := MakeRequest(t, req, http.StatusOK) var users []api.User @@ -85,27 +90,32 @@ func TestAPIFollow(t *testing.T) { t.Run("CheckFollowing", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/following/%s?token=%s", user2, user1, token2)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/following/%s", user2, user1)). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/following/%s?token=%s", user1, user2, token2)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/following/%s", user1, user2)). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNotFound) }) t.Run("CheckMyFollowing", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/following/%s?token=%s", user1, token2)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/following/%s", user1)). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/following/%s?token=%s", user2, token1)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/following/%s", user2)). + AddTokenAuth(token1) MakeRequest(t, req, http.StatusNotFound) }) t.Run("Unfollow", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/following/%s?token=%s", user1, token2)) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/following/%s", user1)). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) }) } diff --git a/tests/integration/api_user_heatmap_test.go b/tests/integration/api_user_heatmap_test.go index 5a7e58a02d60..a49bdd0c2522 100644 --- a/tests/integration/api_user_heatmap_test.go +++ b/tests/integration/api_user_heatmap_test.go @@ -27,8 +27,8 @@ func TestUserHeatmap(t *testing.T) { timeutil.Set(fakeNow) defer timeutil.Unset() - urlStr := fmt.Sprintf("/api/v1/users/%s/heatmap?token=%s", normalUsername, token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/heatmap", normalUsername)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var heatmap []*activities_model.UserHeatmapData DecodeJSON(t, resp, &heatmap) diff --git a/tests/integration/api_user_info_test.go b/tests/integration/api_user_info_test.go index cf42b50a4d58..89f726685977 100644 --- a/tests/integration/api_user_info_test.go +++ b/tests/integration/api_user_info_test.go @@ -31,7 +31,8 @@ func TestAPIUserInfo(t *testing.T) { t.Run("GetInfo", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s?token=%s", user2, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s", user2)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var u api.User @@ -48,7 +49,8 @@ func TestAPIUserInfo(t *testing.T) { assert.Equal(t, org3.GetPlaceholderEmail(), u.Email) // Test if the correct Mail is returned if a User is logged in - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s?token=%s", org3.Name, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s", org3.Name)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &u) assert.Equal(t, org3.GetEmail(), u.Email) @@ -57,7 +59,8 @@ func TestAPIUserInfo(t *testing.T) { t.Run("GetAuthenticatedUser", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user?token=%s", token)) + req := NewRequest(t, "GET", "/api/v1/user"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var u api.User diff --git a/tests/integration/api_user_org_perm_test.go b/tests/integration/api_user_org_perm_test.go index c61004fab449..85bb1db1709d 100644 --- a/tests/integration/api_user_org_perm_test.go +++ b/tests/integration/api_user_org_perm_test.go @@ -35,7 +35,8 @@ func sampleTest(t *testing.T, auoptc apiUserOrgPermTestCase) { session := loginUser(t, auoptc.LoginUser) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrganization, auth_model.AccessTokenScopeReadUser) - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/orgs/%s/permissions?token=%s", auoptc.User, auoptc.Organization, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/orgs/%s/permissions", auoptc.User, auoptc.Organization)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiOP api.OrganizationPermissions @@ -128,7 +129,8 @@ func TestUnknowUser(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadUser, auth_model.AccessTokenScopeReadOrganization) - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/unknow/orgs/org25/permissions?token=%s", token)) + req := NewRequest(t, "GET", "/api/v1/users/unknow/orgs/org25/permissions"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusNotFound) var apiError api.APIError @@ -142,7 +144,8 @@ func TestUnknowOrganization(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadUser, auth_model.AccessTokenScopeReadOrganization) - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/user1/orgs/unknow/permissions?token=%s", token)) + req := NewRequest(t, "GET", "/api/v1/users/user1/orgs/unknow/permissions"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusNotFound) var apiError api.APIError DecodeJSON(t, resp, &apiError) diff --git a/tests/integration/api_user_orgs_test.go b/tests/integration/api_user_orgs_test.go index 51830961aca4..b6b4b6f2b2d2 100644 --- a/tests/integration/api_user_orgs_test.go +++ b/tests/integration/api_user_orgs_test.go @@ -74,8 +74,8 @@ func getUserOrgs(t *testing.T, userDoer, userCheck string) (orgs []*api.Organiza if len(userDoer) != 0 { token = getUserToken(t, userDoer, auth_model.AccessTokenScopeReadOrganization, auth_model.AccessTokenScopeReadUser) } - urlStr := fmt.Sprintf("/api/v1/users/%s/orgs?token=%s", userCheck, token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/orgs", userCheck)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &orgs) return orgs @@ -95,7 +95,8 @@ func TestMyOrgs(t *testing.T) { normalUsername := "user2" token := getUserToken(t, normalUsername, auth_model.AccessTokenScopeReadOrganization, auth_model.AccessTokenScopeReadUser) - req = NewRequest(t, "GET", "/api/v1/user/orgs?token="+token) + req = NewRequest(t, "GET", "/api/v1/user/orgs"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var orgs []*api.Organization DecodeJSON(t, resp, &orgs) diff --git a/tests/integration/api_user_search_test.go b/tests/integration/api_user_search_test.go index ddfeb25234b4..f776b3532576 100644 --- a/tests/integration/api_user_search_test.go +++ b/tests/integration/api_user_search_test.go @@ -27,7 +27,8 @@ func TestAPIUserSearchLoggedIn(t *testing.T) { session := loginUser(t, adminUsername) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadUser) query := "user2" - req := NewRequestf(t, "GET", "/api/v1/users/search?token=%s&q=%s", token, query) + req := NewRequestf(t, "GET", "/api/v1/users/search?q=%s", query). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var results SearchResults @@ -84,8 +85,8 @@ func TestAPIUserSearchAdminLoggedInUserHidden(t *testing.T) { session := loginUser(t, adminUsername) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadUser) query := "user31" - req := NewRequestf(t, "GET", "/api/v1/users/search?token=%s&q=%s", token, query) - req.SetBasicAuth(token, "x-oauth-basic") + req := NewRequestf(t, "GET", "/api/v1/users/search?q=%s", query). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var results SearchResults diff --git a/tests/integration/api_user_secrets_test.go b/tests/integration/api_user_secrets_test.go index 5909f4b83154..56bf30e80441 100644 --- a/tests/integration/api_user_secrets_test.go +++ b/tests/integration/api_user_secrets_test.go @@ -55,44 +55,47 @@ func TestAPIUserSecrets(t *testing.T) { } for _, c := range cases { - req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/user/actions/secrets/%s?token=%s", c.Name, token), api.CreateOrUpdateSecretOption{ + req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/user/actions/secrets/%s", c.Name), api.CreateOrUpdateSecretOption{ Data: "data", - }) + }).AddTokenAuth(token) MakeRequest(t, req, c.ExpectedStatus) } }) t.Run("Update", func(t *testing.T) { name := "update_secret" - url := fmt.Sprintf("/api/v1/user/actions/secrets/%s?token=%s", name, token) + url := fmt.Sprintf("/api/v1/user/actions/secrets/%s", name) req := NewRequestWithJSON(t, "PUT", url, api.CreateOrUpdateSecretOption{ Data: "initial", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) req = NewRequestWithJSON(t, "PUT", url, api.CreateOrUpdateSecretOption{ Data: "changed", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) }) t.Run("Delete", func(t *testing.T) { name := "delete_secret" - url := fmt.Sprintf("/api/v1/user/actions/secrets/%s?token=%s", name, token) + url := fmt.Sprintf("/api/v1/user/actions/secrets/%s", name) req := NewRequestWithJSON(t, "PUT", url, api.CreateOrUpdateSecretOption{ Data: "initial", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) - req = NewRequest(t, "DELETE", url) + req = NewRequest(t, "DELETE", url). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "DELETE", url) + req = NewRequest(t, "DELETE", url). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/actions/secrets/000?token=%s", token)) + req = NewRequest(t, "DELETE", "/api/v1/user/actions/secrets/000"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusBadRequest) }) } diff --git a/tests/integration/api_user_star_test.go b/tests/integration/api_user_star_test.go index 15a555d17d55..50423c80e7a2 100644 --- a/tests/integration/api_user_star_test.go +++ b/tests/integration/api_user_star_test.go @@ -28,14 +28,16 @@ func TestAPIStar(t *testing.T) { t.Run("Star", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/starred/%s?token=%s", repo, tokenWithUserScope)) + req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/starred/%s", repo)). + AddTokenAuth(tokenWithUserScope) MakeRequest(t, req, http.StatusNoContent) }) t.Run("GetStarredRepos", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/starred?token=%s", user, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/starred", user)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("X-Total-Count")) @@ -49,7 +51,8 @@ func TestAPIStar(t *testing.T) { t.Run("GetMyStarredRepos", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred?token=%s", tokenWithUserScope)) + req := NewRequest(t, "GET", "/api/v1/user/starred"). + AddTokenAuth(tokenWithUserScope) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("X-Total-Count")) @@ -63,17 +66,20 @@ func TestAPIStar(t *testing.T) { t.Run("IsStarring", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred/%s?token=%s", repo, tokenWithUserScope)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred/%s", repo)). + AddTokenAuth(tokenWithUserScope) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred/%s?token=%s", repo+"notexisting", tokenWithUserScope)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred/%s", repo+"notexisting")). + AddTokenAuth(tokenWithUserScope) MakeRequest(t, req, http.StatusNotFound) }) t.Run("Unstar", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/starred/%s?token=%s", repo, tokenWithUserScope)) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/starred/%s", repo)). + AddTokenAuth(tokenWithUserScope) MakeRequest(t, req, http.StatusNoContent) }) } diff --git a/tests/integration/api_user_watch_test.go b/tests/integration/api_user_watch_test.go index c07fd288d109..20528959e8c5 100644 --- a/tests/integration/api_user_watch_test.go +++ b/tests/integration/api_user_watch_test.go @@ -28,14 +28,16 @@ func TestAPIWatch(t *testing.T) { t.Run("Watch", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/subscription?token=%s", repo, tokenWithRepoScope)) + req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/subscription", repo)). + AddTokenAuth(tokenWithRepoScope) MakeRequest(t, req, http.StatusOK) }) t.Run("GetWatchedRepos", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/subscriptions?token=%s", user, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/subscriptions", user)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("X-Total-Count")) @@ -49,7 +51,8 @@ func TestAPIWatch(t *testing.T) { t.Run("GetMyWatchedRepos", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/subscriptions?token=%s", tokenWithRepoScope)) + req := NewRequest(t, "GET", "/api/v1/user/subscriptions"). + AddTokenAuth(tokenWithRepoScope) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("X-Total-Count")) @@ -63,17 +66,20 @@ func TestAPIWatch(t *testing.T) { t.Run("IsWatching", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/subscription?token=%s", repo, tokenWithRepoScope)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/subscription", repo)). + AddTokenAuth(tokenWithRepoScope) MakeRequest(t, req, http.StatusOK) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/subscription?token=%s", repo+"notexisting", tokenWithRepoScope)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/subscription", repo+"notexisting")). + AddTokenAuth(tokenWithRepoScope) MakeRequest(t, req, http.StatusNotFound) }) t.Run("Unwatch", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/subscription?token=%s", repo, tokenWithRepoScope)) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/subscription", repo)). + AddTokenAuth(tokenWithRepoScope) MakeRequest(t, req, http.StatusNoContent) }) } diff --git a/tests/integration/api_wiki_test.go b/tests/integration/api_wiki_test.go index f598982555b3..05d90fc4e371 100644 --- a/tests/integration/api_wiki_test.go +++ b/tests/integration/api_wiki_test.go @@ -182,13 +182,13 @@ func TestAPINewWikiPage(t *testing.T) { session := loginUser(t, username) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/new?token=%s", username, "repo1", token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/new", username, "repo1") req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateWikiPageOptions{ Title: title, ContentBase64: base64.StdEncoding.EncodeToString([]byte("Wiki page content for API unit tests")), Message: "", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) } } @@ -199,13 +199,13 @@ func TestAPIEditWikiPage(t *testing.T) { session := loginUser(t, username) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/page/Page-With-Spaced-Name?token=%s", username, "repo1", token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/page/Page-With-Spaced-Name", username, "repo1") req := NewRequestWithJSON(t, "PATCH", urlStr, &api.CreateWikiPageOptions{ Title: "edited title", ContentBase64: base64.StdEncoding.EncodeToString([]byte("Edited wiki page content for API unit tests")), Message: "", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) } diff --git a/tests/integration/cors_test.go b/tests/integration/cors_test.go index e4151d1c32e7..83d200402c86 100644 --- a/tests/integration/cors_test.go +++ b/tests/integration/cors_test.go @@ -14,7 +14,7 @@ import ( func TestCORSNotSet(t *testing.T) { defer tests.PrepareTestEnv(t)() - req := NewRequestf(t, "GET", "/api/v1/version") + req := NewRequest(t, "GET", "/api/v1/version") session := loginUser(t, "user2") resp := session.MakeRequest(t, req, http.StatusOK) assert.Equal(t, resp.Code, http.StatusOK) diff --git a/tests/integration/empty_repo_test.go b/tests/integration/empty_repo_test.go index 78453f28a585..8842de5f6f55 100644 --- a/tests/integration/empty_repo_test.go +++ b/tests/integration/empty_repo_test.go @@ -6,7 +6,6 @@ package integration import ( "bytes" "encoding/base64" - "fmt" "io" "mime/multipart" "net/http" @@ -119,14 +118,13 @@ func TestEmptyRepoAddFileByAPI(t *testing.T) { session := loginUser(t, "user30") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - url := fmt.Sprintf("/api/v1/repos/user30/empty/contents/new-file.txt?token=%s", token) - req := NewRequestWithJSON(t, "POST", url, &api.CreateFileOptions{ + req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user30/empty/contents/new-file.txt", &api.CreateFileOptions{ FileOptions: api.FileOptions{ NewBranchName: "new_branch", Message: "init", }, ContentBase64: base64.StdEncoding.EncodeToString([]byte("newly-added-api-file")), - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var fileResponse api.FileResponse @@ -138,7 +136,8 @@ func TestEmptyRepoAddFileByAPI(t *testing.T) { resp = session.MakeRequest(t, req, http.StatusOK) assert.Contains(t, resp.Body.String(), "newly-added-api-file") - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/user30/empty?token=%s", token)) + req = NewRequest(t, "GET", "/api/v1/repos/user30/empty"). + AddTokenAuth(token) resp = session.MakeRequest(t, req, http.StatusOK) var apiRepo api.Repository DecodeJSON(t, resp, &apiRepo) diff --git a/tests/integration/eventsource_test.go b/tests/integration/eventsource_test.go index 734f4a6a0a34..2ef421897750 100644 --- a/tests/integration/eventsource_test.go +++ b/tests/integration/eventsource_test.go @@ -65,17 +65,20 @@ func TestEventSourceManagerRun(t *testing.T) { var apiNL []api.NotificationThread // -- mark notifications as read -- - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?status-types=unread&token=%s", token)) + req := NewRequest(t, "GET", "/api/v1/notifications?status-types=unread"). + AddTokenAuth(token) resp := session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiNL) assert.Len(t, apiNL, 2) lastReadAt := "2000-01-01T00%3A50%3A01%2B00%3A00" // 946687801 <- only Notification 4 is in this filter ... - req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?last_read_at=%s&token=%s", user2.Name, repo1.Name, lastReadAt, token)) + req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?last_read_at=%s", user2.Name, repo1.Name, lastReadAt)). + AddTokenAuth(token) session.MakeRequest(t, req, http.StatusResetContent) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?token=%s&status-types=unread", token)) + req = NewRequest(t, "GET", "/api/v1/notifications?status-types=unread"). + AddTokenAuth(token) resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiNL) assert.Len(t, apiNL, 1) diff --git a/tests/integration/integration_test.go b/tests/integration/integration_test.go index 8534b0393b9d..1127de1afcdd 100644 --- a/tests/integration/integration_test.go +++ b/tests/integration/integration_test.go @@ -163,14 +163,15 @@ func (s *TestSession) GetCookie(name string) *http.Cookie { return nil } -func (s *TestSession) MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder { +func (s *TestSession) MakeRequest(t testing.TB, rw *RequestWrapper, expectedStatus int) *httptest.ResponseRecorder { t.Helper() + req := rw.Request baseURL, err := url.Parse(setting.AppURL) assert.NoError(t, err) for _, c := range s.jar.Cookies(baseURL) { req.AddCookie(c) } - resp := MakeRequest(t, req, expectedStatus) + resp := MakeRequest(t, rw, expectedStatus) ch := http.Header{} ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";")) @@ -180,14 +181,15 @@ func (s *TestSession) MakeRequest(t testing.TB, req *http.Request, expectedStatu return resp } -func (s *TestSession) MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseRecorder { +func (s *TestSession) MakeRequestNilResponseRecorder(t testing.TB, rw *RequestWrapper, expectedStatus int) *NilResponseRecorder { t.Helper() + req := rw.Request baseURL, err := url.Parse(setting.AppURL) assert.NoError(t, err) for _, c := range s.jar.Cookies(baseURL) { req.AddCookie(c) } - resp := MakeRequestNilResponseRecorder(t, req, expectedStatus) + resp := MakeRequestNilResponseRecorder(t, rw, expectedStatus) ch := http.Header{} ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";")) @@ -197,14 +199,15 @@ func (s *TestSession) MakeRequestNilResponseRecorder(t testing.TB, req *http.Req return resp } -func (s *TestSession) MakeRequestNilResponseHashSumRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseHashSumRecorder { +func (s *TestSession) MakeRequestNilResponseHashSumRecorder(t testing.TB, rw *RequestWrapper, expectedStatus int) *NilResponseHashSumRecorder { t.Helper() + req := rw.Request baseURL, err := url.Parse(setting.AppURL) assert.NoError(t, err) for _, c := range s.jar.Cookies(baseURL) { req.AddCookie(c) } - resp := MakeRequestNilResponseHashSumRecorder(t, req, expectedStatus) + resp := MakeRequestNilResponseHashSumRecorder(t, rw, expectedStatus) ch := http.Header{} ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";")) @@ -314,17 +317,42 @@ func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...auth. return token } -func NewRequest(t testing.TB, method, urlStr string) *http.Request { +type RequestWrapper struct { + *http.Request +} + +func (req *RequestWrapper) AddBasicAuth(username string) *RequestWrapper { + req.Request.SetBasicAuth(username, userPassword) + return req +} + +func (req *RequestWrapper) AddTokenAuth(token string) *RequestWrapper { + if token == "" { + return req + } + if !strings.HasPrefix(token, "Bearer ") { + token = "Bearer " + token + } + req.Request.Header.Set("Authorization", token) + return req +} + +func (req *RequestWrapper) SetHeader(name, value string) *RequestWrapper { + req.Request.Header.Set(name, value) + return req +} + +func NewRequest(t testing.TB, method, urlStr string) *RequestWrapper { t.Helper() return NewRequestWithBody(t, method, urlStr, nil) } -func NewRequestf(t testing.TB, method, urlFormat string, args ...any) *http.Request { +func NewRequestf(t testing.TB, method, urlFormat string, args ...any) *RequestWrapper { t.Helper() return NewRequest(t, method, fmt.Sprintf(urlFormat, args...)) } -func NewRequestWithValues(t testing.TB, method, urlStr string, values map[string]string) *http.Request { +func NewRequestWithValues(t testing.TB, method, urlStr string, values map[string]string) *RequestWrapper { t.Helper() urlValues := url.Values{} for key, value := range values { @@ -333,43 +361,38 @@ func NewRequestWithValues(t testing.TB, method, urlStr string, values map[string return NewRequestWithURLValues(t, method, urlStr, urlValues) } -func NewRequestWithURLValues(t testing.TB, method, urlStr string, urlValues url.Values) *http.Request { +func NewRequestWithURLValues(t testing.TB, method, urlStr string, urlValues url.Values) *RequestWrapper { t.Helper() - req := NewRequestWithBody(t, method, urlStr, bytes.NewBufferString(urlValues.Encode())) - req.Header.Add("Content-Type", "application/x-www-form-urlencoded") - return req + return NewRequestWithBody(t, method, urlStr, bytes.NewBufferString(urlValues.Encode())). + SetHeader("Content-Type", "application/x-www-form-urlencoded") } -func NewRequestWithJSON(t testing.TB, method, urlStr string, v any) *http.Request { +func NewRequestWithJSON(t testing.TB, method, urlStr string, v any) *RequestWrapper { t.Helper() jsonBytes, err := json.Marshal(v) assert.NoError(t, err) - req := NewRequestWithBody(t, method, urlStr, bytes.NewBuffer(jsonBytes)) - req.Header.Add("Content-Type", "application/json") - return req + return NewRequestWithBody(t, method, urlStr, bytes.NewBuffer(jsonBytes)). + SetHeader("Content-Type", "application/json") } -func NewRequestWithBody(t testing.TB, method, urlStr string, body io.Reader) *http.Request { +func NewRequestWithBody(t testing.TB, method, urlStr string, body io.Reader) *RequestWrapper { t.Helper() if !strings.HasPrefix(urlStr, "http") && !strings.HasPrefix(urlStr, "/") { urlStr = "/" + urlStr } - request, err := http.NewRequest(method, urlStr, body) + req, err := http.NewRequest(method, urlStr, body) assert.NoError(t, err) - request.RequestURI = urlStr - return request -} + req.RequestURI = urlStr -func AddBasicAuthHeader(request *http.Request, username string) *http.Request { - request.SetBasicAuth(username, userPassword) - return request + return &RequestWrapper{req} } const NoExpectedStatus = -1 -func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder { +func MakeRequest(t testing.TB, rw *RequestWrapper, expectedStatus int) *httptest.ResponseRecorder { t.Helper() + req := rw.Request recorder := httptest.NewRecorder() if req.RemoteAddr == "" { req.RemoteAddr = "test-mock:12345" @@ -383,8 +406,9 @@ func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest. return recorder } -func MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseRecorder { +func MakeRequestNilResponseRecorder(t testing.TB, rw *RequestWrapper, expectedStatus int) *NilResponseRecorder { t.Helper() + req := rw.Request recorder := NewNilResponseRecorder() testWebRoutes.ServeHTTP(recorder, req) if expectedStatus != NoExpectedStatus { @@ -396,8 +420,9 @@ func MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedSta return recorder } -func MakeRequestNilResponseHashSumRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseHashSumRecorder { +func MakeRequestNilResponseHashSumRecorder(t testing.TB, rw *RequestWrapper, expectedStatus int) *NilResponseHashSumRecorder { t.Helper() + req := rw.Request recorder := NewNilResponseHashSumRecorder() testWebRoutes.ServeHTTP(recorder, req) if expectedStatus != NoExpectedStatus { diff --git a/tests/integration/org_test.go b/tests/integration/org_test.go index aa01678ea947..94c4e197271c 100644 --- a/tests/integration/org_test.go +++ b/tests/integration/org_test.go @@ -169,8 +169,8 @@ func TestOrgRestrictedUser(t *testing.T) { Units: []string{"repo.code"}, } - req = NewRequestWithJSON(t, "POST", - fmt.Sprintf("/api/v1/orgs/%s/teams?token=%s", orgName, token), teamToCreate) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams", orgName), teamToCreate). + AddTokenAuth(token) var apiTeam api.Team @@ -183,8 +183,8 @@ func TestOrgRestrictedUser(t *testing.T) { // teamID := apiTeam.ID // Now we need to add the restricted user to the team - req = NewRequest(t, "PUT", - fmt.Sprintf("/api/v1/teams/%d/members/%s?token=%s", apiTeam.ID, restrictedUser, token)) + req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/teams/%d/members/%s", apiTeam.ID, restrictedUser)). + AddTokenAuth(token) _ = adminSession.MakeRequest(t, req, http.StatusNoContent) // Now we need to check if the restrictedUser can access the repo diff --git a/tests/integration/privateactivity_test.go b/tests/integration/privateactivity_test.go index 2b9b814106c1..5362462f7df9 100644 --- a/tests/integration/privateactivity_test.go +++ b/tests/integration/privateactivity_test.go @@ -35,11 +35,11 @@ func testPrivateActivityDoSomethingForActionEntries(t *testing.T) { session := loginUser(t, privateActivityTestUser) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all&token=%s", owner.Name, repoBefore.Name, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all", owner.Name, repoBefore.Name) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateIssueOption{ Body: "test", Title: "test", - }) + }).AddTokenAuth(token) session.MakeRequest(t, req, http.StatusCreated) } @@ -127,7 +127,8 @@ func testPrivateActivityHelperHasHeatmapContentFromPublic(t *testing.T) bool { func testPrivateActivityHelperHasHeatmapContentFromSession(t *testing.T, session *TestSession) bool { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadUser) - req := NewRequestf(t, "GET", "/api/v1/users/%s/heatmap?token=%s", privateActivityTestUser, token) + req := NewRequestf(t, "GET", "/api/v1/users/%s/heatmap", privateActivityTestUser). + AddTokenAuth(token) resp := session.MakeRequest(t, req, http.StatusOK) var items []*activities_model.UserHeatmapData diff --git a/tests/integration/pull_merge_test.go b/tests/integration/pull_merge_test.go index a4cc3e76fe94..d17bf4afda11 100644 --- a/tests/integration/pull_merge_test.go +++ b/tests/integration/pull_merge_test.go @@ -218,11 +218,11 @@ func TestCantMergeConflict(t *testing.T) { // Use API to create a conflicting pr token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", "user1", "repo1", token), &api.CreatePullRequestOption{ + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", "user1", "repo1"), &api.CreatePullRequestOption{ Head: "conflict", Base: "base", Title: "create a conflicting pr", - }) + }).AddTokenAuth(token) session.MakeRequest(t, req, http.StatusCreated) // Now this PR will be marked conflict - or at least a race will do - so drop down to pure code at this point... @@ -326,11 +326,11 @@ func TestCantMergeUnrelated(t *testing.T) { // Use API to create a conflicting pr token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", "user1", "repo1", token), &api.CreatePullRequestOption{ + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", "user1", "repo1"), &api.CreatePullRequestOption{ Head: "unrelated", Base: "base", Title: "create an unrelated pr", - }) + }).AddTokenAuth(token) session.MakeRequest(t, req, http.StatusCreated) // Now this PR could be marked conflict - or at least a race may occur - so drop down to pure code at this point... diff --git a/tests/integration/pull_status_test.go b/tests/integration/pull_status_test.go index 01cb40d2cf5c..26c99e644597 100644 --- a/tests/integration/pull_status_test.go +++ b/tests/integration/pull_status_test.go @@ -77,7 +77,7 @@ func TestPullCreate_CommitStatus(t *testing.T) { Context: "testci", })) - req = NewRequestf(t, "GET", "/user1/repo1/pulls/1/commits") + req = NewRequest(t, "GET", "/user1/repo1/pulls/1/commits") resp = session.MakeRequest(t, req, http.StatusOK) doc = NewHTMLParser(t, resp.Body) @@ -98,9 +98,9 @@ func doAPICreateCommitStatus(ctx APITestContext, commitID string, data api.Creat req := NewRequestWithJSON( t, http.MethodPost, - fmt.Sprintf("/api/v1/repos/%s/%s/statuses/%s?token=%s", ctx.Username, ctx.Reponame, commitID, ctx.Token), + fmt.Sprintf("/api/v1/repos/%s/%s/statuses/%s", ctx.Username, ctx.Reponame, commitID), data, - ) + ).AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return diff --git a/tests/integration/pull_update_test.go b/tests/integration/pull_update_test.go index e4b2ae65bd61..078253ffb0cb 100644 --- a/tests/integration/pull_update_test.go +++ b/tests/integration/pull_update_test.go @@ -40,7 +40,8 @@ func TestAPIPullUpdate(t *testing.T) { session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index) + req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update", pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index). + AddTokenAuth(token) session.MakeRequest(t, req, http.StatusOK) // Test GetDiverging after update @@ -68,7 +69,8 @@ func TestAPIPullUpdateByRebase(t *testing.T) { session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase&token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index) + req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase", pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index). + AddTokenAuth(token) session.MakeRequest(t, req, http.StatusOK) // Test GetDiverging after update diff --git a/tests/integration/repo_search_test.go b/tests/integration/repo_search_test.go index d113d1e57d03..cf199e98c289 100644 --- a/tests/integration/repo_search_test.go +++ b/tests/integration/repo_search_test.go @@ -51,7 +51,7 @@ func TestSearchRepo(t *testing.T) { } func testSearch(t *testing.T, url string, expected []string) { - req := NewRequestf(t, "GET", url) + req := NewRequest(t, "GET", url) resp := MakeRequest(t, req, http.StatusOK) filenames := resultFilenames(t, NewHTMLParser(t, resp.Body)) diff --git a/tests/integration/user_test.go b/tests/integration/user_test.go index ddde41596074..d8e4c64e8544 100644 --- a/tests/integration/user_test.go +++ b/tests/integration/user_test.go @@ -262,7 +262,7 @@ func TestListStopWatches(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - req := NewRequestf(t, "GET", "/user/stopwatches") + req := NewRequest(t, "GET", "/user/stopwatches") resp := session.MakeRequest(t, req, http.StatusOK) var apiWatches []*api.StopWatch DecodeJSON(t, resp, &apiWatches)