Commit d8121cb0 authored by GitLab Bot's avatar GitLab Bot

Add latest changes from gitlab-org/gitlab@master

parent 536aa3a1
......@@ -402,7 +402,9 @@ export default {
:text="currentEnvironmentName"
>
<div class="d-flex flex-column overflow-hidden">
<gl-dropdown-header class="text-center">{{ __('Environment') }}</gl-dropdown-header>
<gl-dropdown-header class="monitor-environment-dropdown-header text-center">{{
__('Environment')
}}</gl-dropdown-header>
<gl-dropdown-divider />
<gl-search-box-by-type
v-if="shouldRenderSearchableEnvironmentsDropdown"
......
......@@ -4,11 +4,14 @@ import {
GlAlert,
GlDropdown,
GlDropdownItem,
GlDropdownHeader,
GlDropdownDivider,
GlSearchBoxByType,
GlModal,
GlLoadingIcon,
GlModalDirective,
} from '@gitlab/ui';
import { s__ } from '~/locale';
import DuplicateDashboardForm from './duplicate_dashboard_form.vue';
const events = {
......@@ -20,7 +23,9 @@ export default {
GlAlert,
GlDropdown,
GlDropdownItem,
GlDropdownHeader,
GlDropdownDivider,
GlSearchBoxByType,
GlModal,
GlLoadingIcon,
DuplicateDashboardForm,
......@@ -44,6 +49,7 @@ export default {
alert: null,
loading: false,
form: {},
searchTerm: '',
};
},
computed: {
......@@ -54,6 +60,17 @@ export default {
selectedDashboardText() {
return this.selectedDashboard.display_name;
},
filteredDashboards() {
return this.allDashboards.filter(({ display_name }) =>
display_name.toLowerCase().includes(this.searchTerm.toLowerCase()),
);
},
shouldShowNoMsgContainer() {
return this.filteredDashboards.length === 0;
},
okButtonText() {
return this.loading ? s__('Metrics|Duplicating...') : s__('Metrics|Duplicate');
},
},
methods: {
...mapActions('monitoringDashboard', ['duplicateSystemDashboard']),
......@@ -95,45 +112,70 @@ export default {
};
</script>
<template>
<gl-dropdown toggle-class="dropdown-menu-toggle" :text="selectedDashboardText">
<gl-dropdown-item
v-for="dashboard in allDashboards"
:key="dashboard.path"
:active="dashboard.path === selectedDashboard.path"
active-class="is-active"
@click="selectDashboard(dashboard)"
>
{{ dashboard.display_name || dashboard.path }}
</gl-dropdown-item>
<template v-if="isSystemDashboard">
<gl-dropdown
toggle-class="dropdown-menu-toggle"
menu-class="monitor-dashboard-dropdown-menu"
:text="selectedDashboardText"
>
<div class="d-flex flex-column overflow-hidden">
<gl-dropdown-header class="monitor-dashboard-dropdown-header text-center">{{
__('Dashboard')
}}</gl-dropdown-header>
<gl-dropdown-divider />
<gl-search-box-by-type
ref="monitorDashboardsDropdownSearch"
v-model="searchTerm"
class="m-2"
/>
<div class="flex-fill overflow-auto">
<gl-dropdown-item
v-for="dashboard in filteredDashboards"
:key="dashboard.path"
:active="dashboard.path === selectedDashboard.path"
active-class="is-active"
@click="selectDashboard(dashboard)"
>
{{ dashboard.display_name || dashboard.path }}
</gl-dropdown-item>
</div>
<gl-modal
ref="duplicateDashboardModal"
modal-id="duplicateDashboardModal"
:title="s__('Metrics|Duplicate dashboard')"
ok-variant="success"
@ok="ok"
@hide="hide"
<div
v-show="shouldShowNoMsgContainer"
ref="monitorDashboardsDropdownMsg"
class="text-secondary no-matches-message"
>
<gl-alert v-if="alert" class="mb-3" variant="danger" @dismiss="alert = null">
{{ alert }}
</gl-alert>
<duplicate-dashboard-form
:dashboard="selectedDashboard"
:default-branch="defaultBranch"
@change="formChange"
/>
<template #modal-ok>
<gl-loading-icon v-if="loading" inline color="light" />
{{ loading ? s__('Metrics|Duplicating...') : s__('Metrics|Duplicate') }}
</template>
</gl-modal>
{{ __('No matching results') }}
</div>
<template v-if="isSystemDashboard">
<gl-dropdown-divider />
<gl-modal
ref="duplicateDashboardModal"
modal-id="duplicateDashboardModal"
:title="s__('Metrics|Duplicate dashboard')"
ok-variant="success"
@ok="ok"
@hide="hide"
>
<gl-alert v-if="alert" class="mb-3" variant="danger" @dismiss="alert = null">
{{ alert }}
</gl-alert>
<duplicate-dashboard-form
:dashboard="selectedDashboard"
:default-branch="defaultBranch"
@change="formChange"
/>
<template #modal-ok>
<gl-loading-icon v-if="loading" inline color="light" />
{{ okButtonText }}
</template>
</gl-modal>
<gl-dropdown-item ref="duplicateDashboardItem" v-gl-modal="'duplicateDashboardModal'">
{{ s__('Metrics|Duplicate dashboard') }}
</gl-dropdown-item>
</template>
<gl-dropdown-item ref="duplicateDashboardItem" v-gl-modal="'duplicateDashboardModal'">
{{ s__('Metrics|Duplicate dashboard') }}
</gl-dropdown-item>
</template>
</div>
</gl-dropdown>
</template>
......@@ -3,6 +3,7 @@ import { __ } from '~/locale';
export const mrStates = {
merged: 'merged',
closed: 'closed',
open: 'open',
};
export const humanMRStates = {
......
<script>
import { mapActions, mapState } from 'vuex';
import { mapActions, mapState, mapGetters } from 'vuex';
import {
GlFormGroup,
GlToggle,
......@@ -42,6 +42,7 @@ export default {
},
computed: {
...mapState(['formOptions', 'isLoading']),
...mapGetters({ isEdited: 'getIsEdited' }),
...mapComputed(
[
'enabled',
......@@ -92,6 +93,9 @@ export default {
isSubmitButtonDisabled() {
return this.formIsInvalid || this.isLoading;
},
isCancelButtonDisabled() {
return !this.isEdited || this.isLoading;
},
},
methods: {
...mapActions(['resetSettings', 'saveSettings']),
......@@ -211,7 +215,12 @@ export default {
</template>
<template #footer>
<div class="d-flex justify-content-end">
<gl-button ref="cancel-button" type="reset" class="mr-2 d-block" :disabled="isLoading">
<gl-button
ref="cancel-button"
type="reset"
:disabled="isCancelButtonDisabled"
class="mr-2 d-block"
>
{{ __('Cancel') }}
</gl-button>
<gl-button
......
import { isEqual } from 'lodash';
import { findDefaultOption } from '../utils';
export const getCadence = state =>
......@@ -6,3 +7,4 @@ export const getKeepN = state =>
state.settings.keep_n || findDefaultOption(state.formOptions.keepN);
export const getOlderThan = state =>
state.settings.older_than || findDefaultOption(state.formOptions.olderThan);
export const getIsEdited = state => !isEqual(state.original, state.settings);
import Vue from 'vue';
import { parseBoolean } from '~/lib/utils/common_utils';
import DismissibleAlert from '~/vue_shared/components/dismissible_alert.vue';
const mountVueAlert = el => {
const props = {
html: el.innerHTML,
};
const attrs = {
...el.dataset,
dismissible: parseBoolean(el.dataset.dismissible),
};
return new Vue({
el,
render(h) {
return h(DismissibleAlert, { props, attrs });
},
});
};
export default () => [...document.querySelectorAll('.js-vue-alert')].map(mountVueAlert);
<script>
import { GlAlert } from '@gitlab/ui';
export default {
components: {
GlAlert,
},
props: {
html: {
type: String,
required: false,
default: '',
},
},
data() {
return {
isDismissed: false,
};
},
methods: {
dismiss() {
this.isDismissed = true;
},
},
};
</script>
<template>
<gl-alert v-if="!isDismissed" v-bind="$attrs" @dismiss="dismiss" v-on="$listeners">
<div v-html="html"></div>
</gl-alert>
</template>
......@@ -47,7 +47,12 @@
}
.prometheus-graphs-header {
.monitor-environment-dropdown-menu {
.monitor-dashboard-dropdown-header header {
font-size: $gl-font-size;
}
.monitor-environment-dropdown-menu,
.monitor-dashboard-dropdown-menu {
&.show {
display: flex;
flex-direction: column;
......
......@@ -20,6 +20,10 @@ module AnalyticsNavbarHelper
].compact
end
def group_analytics_navbar_links(group, current_user)
[]
end
private
def navbar_sub_item(args)
......
......@@ -7,7 +7,6 @@ module GroupsHelper
groups#details
groups#activity
groups#subgroups
analytics#show
]
end
......
- navbar_sub_item = project_analytics_navbar_links(@project, current_user).sort_by(&:title)
- all_paths = navbar_sub_item.map(&:path)
- navbar_links = links.sort_by(&:title)
- all_paths = navbar_links.map(&:path)
- if navbar_sub_item.any?
- if navbar_links.any?
= nav_link(path: all_paths) do
= link_to navbar_sub_item.first.link, data: { qa_selector: 'project_analytics_link' } do
= link_to navbar_links.first.link do
.nav-icon-container
= sprite_icon('chart')
%span.nav-item-name
= _('Analytics')
%ul.sidebar-sub-level-items
- navbar_sub_item.each do |menu_item|
- navbar_links.each do |menu_item|
= nav_link(path: menu_item.path) do
= link_to(menu_item.link, menu_item.link_to_options) do
%span= menu_item.title
- should_display_analytics_pages_in_sidebar = Feature.enabled?(:analytics_pages_under_group_analytics_sidebar, @group)
- issues_count = group_issues_count(state: 'opened')
- merge_requests_count = group_merge_requests_count(state: 'opened')
......@@ -11,7 +12,9 @@
= @group.name
%ul.sidebar-top-level-items.qa-group-sidebar
- if group_sidebar_link?(:overview)
= nav_link(path: group_overview_nav_link_paths, html_options: { class: 'home' }) do
- paths = group_overview_nav_link_paths
- paths << 'contribution_analytics#show' unless should_display_analytics_pages_in_sidebar
= nav_link(path: paths, unless: -> { should_display_analytics_pages_in_sidebar && current_path?('groups/contribution_analytics#show') }, html_options: { class: 'home' }) do
= link_to group_path(@group) do
.nav-icon-container
= sprite_icon('home')
......@@ -42,18 +45,19 @@
%span
= _('Activity')
- if group_sidebar_link?(:contribution_analytics)
= nav_link(path: 'analytics#show') do
= link_to group_contribution_analytics_path(@group), title: _('Contribution Analytics'), data: { placement: 'right', qa_selector: 'contribution_analytics_link' } do
%span
= _('Contribution Analytics')
- unless should_display_analytics_pages_in_sidebar
- if group_sidebar_link?(:contribution_analytics)
= nav_link(path: 'contribution_analytics#show') do
= link_to group_contribution_analytics_path(@group), title: _('Contribution Analytics'), data: { placement: 'right', qa_selector: 'contribution_analytics_link' } do
%span
= _('Contribution Analytics')
= render_if_exists 'layouts/nav/group_insights_link'
= render_if_exists 'layouts/nav/group_insights_link'
= render_if_exists "layouts/nav/ee/epic_link", group: @group
- if group_sidebar_link?(:issues)
= nav_link(path: group_issues_sub_menu_items) do
= nav_link(path: group_issues_sub_menu_items, unless: -> { should_display_analytics_pages_in_sidebar && current_path?('issues_analytics#show') }) do
= link_to issues_group_path(@group), data: { qa_selector: 'group_issues_item' } do
.nav-icon-container
= sprite_icon('issues')
......@@ -80,7 +84,8 @@
%span
= boards_link_text
= render_if_exists 'layouts/nav/issues_analytics_link'
- unless should_display_analytics_pages_in_sidebar
= render_if_exists 'layouts/nav/issues_analytics_link'
- if group_sidebar_link?(:labels)
= nav_link(path: 'labels#index') do
......@@ -126,6 +131,8 @@
= render_if_exists 'groups/sidebar/packages'
= render 'layouts/nav/sidebar/analytics_links', links: group_analytics_navbar_links(@group, current_user)
- if group_sidebar_link?(:group_members)
= nav_link(path: 'group_members#index') do
= link_to group_group_members_path(@group) do
......
......@@ -298,7 +298,7 @@
= render_if_exists 'layouts/nav/sidebar/project_packages_link'
= render 'layouts/nav/sidebar/project_analytics_link'
= render 'layouts/nav/sidebar/analytics_links', links: project_analytics_navbar_links(@project, current_user)
- if project_nav_tab? :wiki
- wiki_url = project_wiki_path(@project, :home)
......
---
title: Added search box to dashboards dropdown in monitoring dashboard
merge_request: 23906
author:
type: added
---
title: Show security report outdated message for only Active MRs
merge_request: 23575
author:
type: other
---
title: Separate project and group entities into own class files
merge_request: 24070
author: Rajendra Kadam
type: added
......@@ -346,7 +346,7 @@ The default location where images are stored in source installations, is
1. Save the file and [restart GitLab](../restart_gitlab.md#installations-from-source) for the changes to take effect.
## Container Registry storage driver
### Container Registry storage driver
You can configure the Container Registry to use a different storage backend by
configuring a different storage driver. By default the GitLab Container Registry
......@@ -425,6 +425,12 @@ storage:
NOTE: **Note:**
`your-s3-bucket` should only be the name of a bucket that exists, and can't include subdirectories.
### Storage limitations
Currently, there is no storage limitation, which means a user can upload an
infinite amount of Docker images with arbitrary sizes. This setting will be
configurable in future releases.
## Change the registry's internal port
NOTE: **Note:**
......@@ -536,12 +542,6 @@ You can use GitLab as an auth endpoint with an external container registry.
1. Save the file and [restart GitLab](../restart_gitlab.md#installations-from-source) for the changes to take effect.
## Storage limitations
Currently, there is no storage limitation, which means a user can upload an
infinite amount of Docker images with arbitrary sizes. This setting will be
configurable in future releases.
## Configure Container Registry notifications
You can configure the Container Registry to send webhook notifications in
......@@ -595,6 +595,193 @@ notifications:
backoff: 1000
```
## Container Registry garbage collection
NOTE: **Note:**
The garbage collection tools are only available when you've installed GitLab
via an Omnibus package or the cloud native chart.
Container Registry can use considerable amounts of disk space. To clear up
some unused layers, the registry includes a garbage collect command.
GitLab offers a set of APIs to manipulate the Container Registry and aid the process
of removing unused tags. Currently, this is exposed using the API, but in the future,
these controls will be migrated to the GitLab interface.
Project maintainers can
[delete Container Registry tags in bulk](../../api/container_registry.md#delete-repository-tags-in-bulk)
periodically based on their own criteria, however, this alone does not recycle data,
it only unlinks tags from manifests and image blobs. To recycle the Container
Registry data in the whole GitLab instance, you can use the built-in command
provided by `gitlab-ctl`.
### Understanding the content-addressable layers
Consider the following example, where you first build the image:
```bash
# This builds a image with content of sha256:111111
docker build -t my.registry.com/my.group/my.project:latest .
docker push my.registry.com/my.group/my.project:latest
```
Now, you do overwrite `:latest` with a new version:
```bash
# This builds a image with content of sha256:222222
docker build -t my.registry.com/my.group/my.project:latest .
docker push my.registry.com/my.group/my.project:latest
```
Now, the `:latest` tag points to manifest of `sha256:222222`. However, due to
the architecture of registry, this data is still accessible when pulling the
image `my.registry.com/my.group/my.project@sha256:111111`, even though it is
no longer directly accessible via the `:latest` tag.
### Recycling unused tags
There are a couple of considerations you need to note before running the
built-in command:
- The built-in command will stop the registry before it starts the garbage collection.
- The garbage collect command takes some time to complete, depending on the
amount of data that exists.
- If you changed the location of registry configuration file, you will need to
specify its path.
- After the garbage collection is done, the registry should start up automatically.
DANGER: **Danger:**
By running the built-in garbage collection command, it will cause downtime to
the Container Registry. Running this command on an instance in an HA environment
while one of your other instances is still writing to the Registry storage,
will remove referenced manifests. To avoid that, make sure Registry is set to
[read-only mode](#performing-garbage-collection-without-downtime) before proceeding.
If you did not change the default location of the configuration file, run:
```sh
sudo gitlab-ctl registry-garbage-collect
```
This command will take some time to complete, depending on the amount of
layers you have stored.
If you changed the location of the Container Registry `config.yml`:
```sh
sudo gitlab-ctl registry-garbage-collect /path/to/config.yml
```
You may also [remove all unreferenced manifests](#removing-unused-layers-not-referenced-by-manifests),
although this is a way more destructive operation, and you should first
understand the implications.
### Removing unused layers not referenced by manifests
> [Introduced](https://gitlab.com/gitlab-org/omnibus-gitlab/merge_requests/3097) in Omnibus GitLab 11.10.
DANGER: **Danger:**
This is a destructive operation.
The GitLab Container Registry follows the same default workflow as Docker Distribution:
retain all layers, even ones that are unreferenced directly to allow all content
to be accessed using context addressable identifiers.
However, in most workflows, you don't care about old layers if they are not directly
referenced by the registry tag. The `registry-garbage-collect` command supports the
`-m` switch to allow you to remove all unreferenced manifests and layers that are
not directly accessible via `tag`:
```sh
sudo gitlab-ctl registry-garbage-collect -m
```
Since this is a way more destructive operation, this behavior is disabled by default.
You are likely expecting this way of operation, but before doing that, ensure
that you have backed up all registry data.
### Performing garbage collection without downtime
You can perform a garbage collection without stopping the Container Registry by setting
it into a read-only mode and by not using the built-in command. During this time,
you will be able to pull from the Container Registry, but you will not be able to
push.
NOTE: **Note:**
By default, the [registry storage path](#container-registry-storage-path)
is `/var/opt/gitlab/gitlab-rails/shared/registry`.
To enable the read-only mode:
1. In `/etc/gitlab/gitlab.rb`, specify the read-only mode:
```ruby
registry['storage'] = {
'filesystem' => {
'rootdirectory' => "<your_registry_storage_path>"
},
'maintenance' => {
'readonly' => {
'enabled' => true
}
}
}
```
1. Save and reconfigure GitLab:
```sh
sudo gitlab-ctl reconfigure
```
This will set the Container Registry into the read only mode.
1. Next, trigger the garbage collect command:
```sh
sudo /opt/gitlab/embedded/bin/registry garbage-collect /var/opt/gitlab/registry/config.yml
```
This will start the garbage collection, which might take some time to complete.
1. Once done, in `/etc/gitlab/gitlab.rb` change it back to read-write mode:
```ruby
registry['storage'] = {
'filesystem' => {
'rootdirectory' => "<your_registry_storage_path>"
},
'maintenance' => {
'readonly' => {
'enabled' => false
}
}
}
```
1. Save and reconfigure GitLab:
```sh
sudo gitlab-ctl reconfigure
```
### Running the garbage collection on schedule
Ideally, you want to run the garbage collection of the registry regularly on a
weekly basis at a time when the registry is not being in-use.
The simplest way is to add a new crontab job that it will run periodically
once a week.
Create a file under `/etc/cron.d/registry-garbage-collect`:
```bash
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# Run every Sunday at 04:05am
5 4 * * 0 root gitlab-ctl registry-garbage-collect
```
## Troubleshooting
Before diving in to the following sections, here's some basic troubleshooting:
......
......@@ -118,7 +118,7 @@ Parameters:
| ------------------------ | ----------------- | -------- | ----------- |
| `id` | integer/string | yes | The ID or [URL-encoded path of the group](README.md#namespaced-path-encoding) of the parent group |
| `skip_groups` | array of integers | no | Skip the group IDs passed |
| `all_available` | boolean | no | Show all the groups you have access to (defaults to `false` for authenticated users, `true` for admin); Attributes `owned` and `min_access_level` have preceden |
| `all_available` | boolean | no | Show all the groups you have access to (defaults to `false` for authenticated users, `true` for admin); Attributes `owned` and `min_access_level` have precedence |
| `search` | string | no | Return the list of authorized groups matching the search criteria |
| `order_by` | string | no | Order groups by `name`, `path` or `id`. Default is `name` |
| `sort` | string | no | Order groups in `asc` or `desc` order. Default is `asc` |
......
......@@ -6,7 +6,7 @@ The GitLab Pages feature must be enabled to use these endpoints. Find out more a
## Unpublish pages
Remove pages. The user must have admin priviledges.
Remove pages. The user must have admin privileges.
```text
DELETE /projects/:id/pages
......
......@@ -2117,7 +2117,7 @@ POST /projects/:id/push_rule
| `commit_message_negative_regex` **(STARTER)** | string | no | No commit message is allowed to match this, e.g. `ssh\:\/\/` |
| `branch_name_regex` **(STARTER)** | string | no | All branch names must match this, e.g. `(feature|hotfix)\/*` |
| `author_email_regex` **(STARTER)** | string | no | All commit author emails must match this, e.g. `@my-company.com$` |
| `file_name_regex` **(STARTER)** | string | no | All commited filenames must **not** match this, e.g. `(jar|exe)$` |
| `file_name_regex` **(STARTER)** | string | no | All committed filenames must **not** match this, e.g. `(jar|exe)$` |
| `max_file_size` **(STARTER)** | integer | no | Maximum file size (MB) |
| `commit_committer_check` **(PREMIUM)** | boolean | no | Users can only push commits to this repository that were committed with one of their own verified emails. |
| `reject_unsigned_commits` **(PREMIUM)** | boolean | no | Reject commit when it is not signed through GPG. |
......@@ -2140,7 +2140,7 @@ PUT /projects/:id/push_rule
| `commit_message_negative_regex` **(STARTER)** | string | no | No commit message is allowed to match this, e.g. `ssh\:\/\/` |
| `branch_name_regex` **(STARTER)** | string | no | All branch names must match this, e.g. `(feature|hotfix)\/*` |
| `author_email_regex` **(STARTER)** | string | no | All commit author emails must match this, e.g. `@my-company.com$` |
| `file_name_regex` **(STARTER)** | string | no | All commited filenames must **not** match this, e.g. `(jar|exe)$` |
| `file_name_regex` **(STARTER)** | string | no | All committed filenames must **not** match this, e.g. `(jar|exe)$` |
| `max_file_size` **(STARTER)** | integer | no | Maximum file size (MB) |
| `commit_committer_check` **(PREMIUM)** | boolean | no | Users can only push commits to this repository that were committed with one of their own verified emails. |
| `reject_unsigned_commits` **(PREMIUM)** | boolean | no | Reject commits when they are not GPG signed. |
......
......@@ -275,7 +275,7 @@ are listed in the descriptions of the relevant settings.
| `metrics_enabled` | boolean | no | (**If enabled, requires:** `metrics_host`, `metrics_method_call_threshold`, `metrics_packet_size`, `metrics_pool_size`, `metrics_port`, `metrics_sample_interval` and `metrics_timeout`) Enable influxDB metrics. |
| `metrics_host` | string | required by: `metrics_enabled` | InfluxDB host. |
| `metrics_method_call_threshold` | integer | required by: `metrics_enabled` | A method call is only tracked when it takes longer than the given amount of milliseconds. |
| `metrics_packet_size` | integer | required by: `metrics_enabled` | The amount of datapoints to send in a single UDP packet. |
| `metrics_packet_size` | integer | required by: `metrics_enabled` | The amount of data points to send in a single UDP packet. |
| `metrics_pool_size` | integer | required by: `metrics_enabled` | The amount of InfluxDB connections to keep open. |
| `metrics_port` | integer | required by: `metrics_enabled` | The UDP port to use for connecting to InfluxDB. |
| `metrics_sample_interval` | integer | required by: `metrics_enabled` | The sampling interval in seconds. |
......@@ -330,7 +330,7 @@ are listed in the descriptions of the relevant settings.
| `snowplow_iglu_registry_url` | string | no | The Snowplow base Iglu Schema Registry URL to use for custom context and self describing events'|
| `sourcegraph_enabled` | boolean | no | Enables Sourcegraph integration. Default is `false`. **If enabled, requires** `sourcegraph_url`. |
| `sourcegraph_url` | string | required by: `sourcegraph_enabled` | The Sourcegraph instance URL for integration. |
| `sourcegraph_public_only` | boolean | no | Blocks Sourcegraph from being loaded on private and internal projects. Defaul is `true`. |
| `sourcegraph_public_only` | boolean | no | Blocks Sourcegraph from being loaded on private and internal projects. Default is `true`. |
| `terminal_max_session_time` | integer | no | Maximum time for web terminal websocket connection (in seconds). Set to `0` for unlimited time. |
| `terms` | text | required by: `enforce_terms` | (**Required by:** `enforce_terms`) Markdown content for the ToS. |
| `throttle_authenticated_api_enabled` | boolean | no | (**If enabled, requires:** `throttle_authenticated_api_period_in_seconds` and `throttle_authenticated_api_requests_per_period`) Enable authenticated API request rate limit. Helps reduce request volume (e.g. from crawlers or abusive bots). |
......@@ -345,7 +345,7 @@ are listed in the descriptions of the relevant settings.
| `time_tracking_limit_to_hours` | boolean | no | Limit display of time tracking units to hours. Default is `false`. |
| `two_factor_grace_period` | integer | required by: `require_two_factor_authentication` | Amount of time (in hours) that users are allowed to skip forced configuration of two-factor authentication. |
| `unique_ips_limit_enabled` | boolean | no | (**If enabled, requires:** `unique_ips_limit_per_user` and `unique_ips_limit_time_window`) Limit sign in from multiple ips. |
| `unique_ips_limit_per_user` | integer | required by: `unique_ips_limit_enabled` | Maximum number of ips per user. |
| `unique_ips_limit_per_user` | integer | required by: `unique_ips_limit_enabled` | Maximum number of IPs per user. |
| `unique_ips_limit_time_window` | integer | required by: `unique_ips_limit_enabled` | How many seconds an IP will be counted towards the limit. |
| `usage_ping_enabled` | boolean | no | Every week GitLab will report license usage back to GitLab, Inc. |
| `user_default_external` | boolean | no | Newly registered users will be external by default. |
......
......@@ -164,7 +164,7 @@ Testing the `hasMetricTypes` computed prop would seem like a given, but to test
Keep an eye out for these kinds of tests, as they just make updating logic more fragile and tedious than it needs to be. This is also true for other libraries.
Some more examples can be found further down [below](#unit-testing-guidelines)
Some more examples can be found in the [Frontend unit tests section](testing_levels.md#frontend-unit-tests)
### Don't test your mock
......@@ -749,433 +749,22 @@ end
## Overview of Frontend Testing Levels
Main information on frontend testing levels can be found in the [Testing Levels page](testing_levels.md).
Tests relevant for frontend development can be found at the following places:
- `spec/javascripts/` which are run by Karma (command: `yarn karma`) and contain
- [frontend unit tests](#frontend-unit-tests)
- [frontend component tests](#frontend-component-tests)
- [frontend integration tests](#frontend-integration-tests)
- `spec/frontend/` which are run by Jest (command: `yarn jest`) and contain
- [frontend unit tests](#frontend-unit-tests)
- [frontend component tests](#frontend-component-tests)
- [frontend integration tests](#frontend-integration-tests)
- `spec/features/` which are run by RSpec and contain
- [feature tests](#feature-tests)
- `spec/javascripts/`, for Karma tests
- `spec/frontend/`, for Jest tests
- `spec/features/`, for RSpec tests
RSpec runs complete [feature tests](testing_levels.md#frontend-feature-tests), while the Jest and Karma directories contain [frontend unit tests](testing_levels.md#frontend-unit-tests), [frontend component tests](testing_levels.md#frontend-component-tests), and [frontend integration tests](testing_levels.md#frontend-integration-tests).
All tests in `spec/javascripts/` will eventually be migrated to `spec/frontend/` (see also [#52483](https://gitlab.com/gitlab-org/gitlab-foss/issues/52483)).
In addition, there used to be feature tests in `features/`, run by Spinach.
These were removed from the codebase in May 2018 ([#23036](https://gitlab.com/gitlab-org/gitlab-foss/issues/23036)).
Before May 2018, `features/` also contained feature tests run by Spinach. These tests were removed from the codebase in May 2018 ([#23036](https://gitlab.com/gitlab-org/gitlab-foss/issues/23036)).
See also [Notes on testing Vue components](../fe_guide/vue.html#testing-vue-components).
### Frontend unit tests
Unit tests are on the lowest abstraction level and typically test functionality that is not directly perceivable by a user.
```mermaid
graph RL
plain[Plain JavaScript];
Vue[Vue Components];
feature-flags[Feature Flags];
license-checks[License Checks];
plain---Vuex;
plain---GraphQL;
Vue---plain;
Vue---Vuex;
Vue---GraphQL;
browser---plain;
browser---Vue;
plain---backend;
Vuex---backend;
GraphQL---backend;
Vue---backend;
backend---database;
backend---feature-flags;
backend---license-checks;
class plain tested;
class Vuex tested;
classDef node color:#909090,fill:#f0f0f0,stroke-width:2px,stroke:#909090
classDef label stroke-width:0;
classDef tested color:#000000,fill:#a0c0ff,stroke:#6666ff,stroke-width:2px,stroke-dasharray: 5, 5;
subgraph " "
tested;
mocked;
class tested tested;
end
```
<div id="unit-testing-guidelines"></div>
#### When to use unit tests
<details>
<summary>exported functions and classes</summary>
Anything that is exported can be reused at various places in a way you have no control over.
Therefore it is necessary to document the expected behavior of the public interface with tests.
</details>
<details>
<summary>Vuex actions</summary>
Any Vuex action needs to work in a consistent way independent of the component it is triggered from.
</details>
<details>
<summary>Vuex mutations</summary>
For complex Vuex mutations it helps to identify the source of a problem by separating the tests from other parts of the Vuex store.
</details>
#### When *not* to use unit tests
<details>
<summary>non-exported functions or classes</summary>
Anything that is not exported from a module can be considered private or an implementation detail and doesn't need to be tested.
</details>
<details>
<summary>constants</summary>
Testing the value of a constant would mean to copy it.
This results in extra effort without additional confidence that the value is correct.
</details>
<details>
<summary>Vue components</summary>
Computed properties, methods, and lifecycle hooks can be considered an implementation detail of components and don't need to be tested.
They are implicitly covered by component tests.
The <a href="https://vue-test-utils.vuejs.org/guides/#getting-started">official Vue guidelines</a> suggest the same.
</details>
#### What to mock in unit tests
<details>
<summary>state of the class under test</summary>
Modifying the state of the class under test directly rather than using methods of the class avoids side-effects in test setup.
</details>
<details>
<summary>other exported classes</summary>
Every class needs to be tested in isolation to prevent test scenarios from growing exponentially.
</details>
<details>
<summary>single DOM elements if passed as parameters</summary>
For tests that only operate on single DOM elements rather than a whole page, creating these elements is cheaper than loading a whole HTML fixture.
</details>
<details>
<summary>all server requests</summary>
When running frontend unit tests, the backend may not be reachable.
Therefore all outgoing requests need to be mocked.
</details>
<details>
<summary>asynchronous background operations</summary>
Background operations cannot be stopped or waited on, so they will continue running in the following tests and cause side effects.
</details>
#### What *not* to mock in unit tests
<details>
<summary>non-exported functions or classes</summary>
Everything that is not exported can be considered private to the module and will be implicitly tested via the exported classes / functions.
</details>
<details>
<summary>methods of the class under test</summary>
By mocking methods of the class under test, the mocks will be tested and not the real methods.
</details>
<details>
<summary>utility functions (pure functions, or those that only modify parameters)</summary>
If a function has no side effects because it has no state, it is safe to not mock it in tests.
</details>
<details>
<summary>full HTML pages</summary>
Loading the HTML of a full page slows down tests, so it should be avoided in unit tests.
</details>
### Frontend component tests
Component tests cover the state of a single component that is perceivable by a user depending on external signals such as user input, events fired from other components, or application state.
```mermaid
graph RL
plain[Plain JavaScript];
Vue[Vue Components];
feature-flags[Feature Flags];
license-checks[License Checks];
plain---Vuex;
plain---GraphQL;
Vue---plain;
Vue---Vuex;
Vue---GraphQL;
browser---plain;
browser---Vue;
plain---backend;
Vuex---backend;
GraphQL---backend;
Vue---backend;
backend---database;
backend---feature-flags;
backend---license-checks;
class Vue tested;
classDef node color:#909090,fill:#f0f0f0,stroke-width:2px,stroke:#909090
classDef label stroke-width:0;
classDef tested color:#000000,fill:#a0c0ff,stroke:#6666ff,stroke-width:2px,stroke-dasharray: 5, 5;
subgraph " "
tested;
mocked;
class tested tested;
end
```
#### When to use component tests
- Vue components
#### When *not* to use component tests
<details>
<summary>Vue applications</summary>
Vue applications may contain many components.
Testing them on a component level requires too much effort.
Therefore they are tested on frontend integration level.
</details>
<details>
<summary>HAML templates</summary>
HAML templates contain only Markup and no frontend-side logic.
Therefore they are not complete components.
</details>
#### What to mock in component tests
<details>
<summary>DOM</summary>
Operating on the real DOM is significantly slower than on the virtual DOM.
</details>
<details>
<summary>properties and state of the component under test</summary>
Similarly to testing classes, modifying the properties directly (rather than relying on methods of the component) avoids side-effects.
</details>
<details>
<summary>Vuex store</summary>
To avoid side effects and keep component tests simple, Vuex stores are replaced with mocks.
</details>
<details>
<summary>all server requests</summary>
Similar to unit tests, when running component tests, the backend may not be reachable.
Therefore all outgoing requests need to be mocked.
</details>
<details>
<summary>asynchronous background operations</summary>
Similar to unit tests, background operations cannot be stopped or waited on, so they will continue running in the following tests and cause side effects.
</details>
<details>
<summary>child components</summary>
Every component is tested individually, so child components are mocked.
See also <a href="https://vue-test-utils.vuejs.org/api/#shallowmount">shallowMount()</a>
</details>
#### What *not* to mock in component tests
<details>
<summary>methods or computed properties of the component under test</summary>
By mocking part of the component under test, the mocks will be tested and not the real component.
</details>
<details>
<summary>functions and classes independent from Vue</summary>
All plain JavaScript code is already covered by unit tests and needs not to be mocked in component tests.
</details>
### Frontend integration tests
Integration tests cover the interaction between all components on a single page.
Their abstraction level is comparable to how a user would interact with the UI.
```mermaid
graph RL
plain[Plain JavaScript];
Vue[Vue Components];
feature-flags[Feature Flags];
license-checks[License Checks];
plain---Vuex;
plain---GraphQL;
Vue---plain;
Vue---Vuex;
Vue---GraphQL;
browser---plain;
browser---Vue;
plain---backend;
Vuex---backend;
GraphQL---backend;
Vue---backend;
backend---database;
backend---feature-flags;
backend---license-checks;
class plain tested;
class Vue tested;
class Vuex tested;
class GraphQL tested;
class browser tested;
linkStyle 0,1,2,3,4,5,6 stroke:#6666ff,stroke-width:2px,stroke-dasharray: 5, 5;
classDef node color:#909090,fill:#f0f0f0,stroke-width:2px,stroke:#909090
classDef label stroke-width:0;
classDef tested color:#000000,fill:#a0c0ff,stroke:#6666ff,stroke-width:2px,stroke-dasharray: 5, 5;
subgraph " "
tested;
mocked;
class tested tested;
end
```
#### When to use integration tests
<details>
<summary>page bundles (<code>index.js</code> files in <code>app/assets/javascripts/pages/</code>)</summary>
Testing the page bundles ensures the corresponding frontend components integrate well.
</details>
<details>
<summary>Vue applications outside of page bundles</summary>
Testing Vue applications as a whole ensures the corresponding frontend components integrate well.
</details>
#### What to mock in integration tests
<details>
<summary>HAML views (use fixtures instead)</summary>
Rendering HAML views requires a Rails environment including a running database which we cannot rely on in frontend tests.
</details>
<details>
<summary>all server requests</summary>
Similar to unit and component tests, when running component tests, the backend may not be reachable.
Therefore all outgoing requests need to be mocked.
</details>
<details>
<summary>asynchronous background operations that are not perceivable on the page</summary>
Background operations that affect the page need to be tested on this level.
All other background operations cannot be stopped or waited on, so they will continue running in the following tests and cause side effects.
</details>
#### What *not* to mock in integration tests
<details>
<summary>DOM</summary>
Testing on the real DOM ensures our components work in the environment they are meant for.
Part of this will be delegated to <a href="https://gitlab.com/gitlab-org/quality/team-tasks/issues/45">cross-browser testing</a>.
</details>
<details>
<summary>properties or state of components</summary>
On this level, all tests can only perform actions a user would do.
For example to change the state of a component, a click event would be fired.
</details>
<details>
<summary>Vuex stores</summary>
When testing the frontend code of a page as a whole, the interaction between Vue components and Vuex stores is covered as well.
</details>
### Feature tests
In contrast to [frontend integration tests](#frontend-integration-tests), feature tests make requests against the real backend instead of using fixtures.
This also implies that database queries are executed which makes this category significantly slower.
See also
- The [RSpec testing guidelines](../testing_guide/best_practices.md#rspec).
- System / Feature tests in the [Testing Best Practices](best_practices.md#system--feature-tests).
- [Issue #26159](https://gitlab.com/gitlab-org/gitlab/issues/26159) which aims at combine those guidelines with this page.
```mermaid
graph RL
plain[Plain JavaScript];
Vue[Vue Components];
feature-flags[Feature Flags];
license-checks[License Checks];
plain---Vuex;
plain---GraphQL;
Vue---plain;
Vue---Vuex;
Vue---GraphQL;
browser---plain;
browser---Vue;
plain---backend;
Vuex---backend;
GraphQL---backend;
Vue---backend;
backend---database;
backend---feature-flags;
backend---license-checks;
class backend tested;
class plain tested;
class Vue tested;
class Vuex tested;
class GraphQL tested;
class browser tested;
linkStyle 0,1,2,3,4,5,6,7,8,9,10 stroke:#6666ff,stroke-width:2px,stroke-dasharray: 5, 5;
classDef node color:#909090,fill:#f0f0f0,stroke-width:2px,stroke:#909090
classDef label stroke-width:0;
classDef tested color:#000000,fill:#a0c0ff,stroke:#6666ff,stroke-width:2px,stroke-dasharray: 5, 5;
subgraph " "
tested;
mocked;
class tested tested;
end
```
#### When to use feature tests
- Use cases that require a backend and cannot be tested using fixtures.
- Behavior that is not part of a page bundle but defined globally.
#### Relevant notes
A `:js` flag is added to the test to make sure the full environment is loaded.
```ruby
scenario 'successfully', :js do
sign_in(create(:admin))
end
```
The steps of each test are written using capybara methods ([documentation](https://www.rubydoc.info/gems/capybara)).
Bear in mind <abbr title="XMLHttpRequest">XHR</abbr> calls might require you to use `wait_for_requests` in between steps, like so:
```ruby
find('.form-control').native.send_keys(:enter)
wait_for_requests
expect(page).not_to have_selector('.card')
```
## Test helpers
### Vuex Helper: `testAction`
......
......@@ -51,6 +51,167 @@ records should use stubs/doubles as much as possible.
| `rubocop/` | `spec/rubocop/` | RSpec | |
| `spec/factories` | `spec/factories_spec.rb` | RSpec | |
### Frontend unit tests
Unit tests are on the lowest abstraction level and typically test functionality
that is not directly perceivable by a user.
```mermaid
graph RL
plain[Plain JavaScript];
Vue[Vue Components];
feature-flags[Feature Flags];
license-checks[License Checks];
plain---Vuex;
plain---GraphQL;
Vue---plain;
Vue---Vuex;
Vue---GraphQL;
browser---plain;
browser---Vue;
plain---backend;
Vuex---backend;
GraphQL---backend;
Vue---backend;
backend---database;
backend---feature-flags;
backend---license-checks;
class plain tested;
class Vuex tested;
classDef node color:#909090,fill:#f0f0f0,stroke-width:2px,stroke:#909090
classDef label stroke-width:0;
classDef tested color:#000000,fill:#a0c0ff,stroke:#6666ff,stroke-width:2px,stroke-dasharray: 5, 5;
subgraph " "
tested;
mocked;
class tested tested;
end
```
#### When to use unit tests
- **Exported functions and classes**:
Anything exported can be reused at various places in ways you have no control over.
You should document the expected behavior of the public interface with tests.
- **Vuex actions**:
Any Vuex action must work in a consistent way, independent of the component it is triggered from.
- **Vuex mutations**:
For complex Vuex mutations, you should separate the tests from other parts of the Vuex store to simplify problem-solving.
#### When *not* to use unit tests
- **Non-exported functions or classes**:
Anything not exported from a module can be considered private or an implementation detail, and doesn't need to be tested.
- **Constants**:
Testing the value of a constant means copying it, resulting in extra effort without additional confidence that the value is correct.
- **Vue components**:
Computed properties, methods, and lifecycle hooks can be considered an implementation detail of components, are implicitly covered by component tests, and don't need to be tested.
For more information, see the [official Vue guidelines](https://vue-test-utils.vuejs.org/guides/#getting-started).
#### What to mock in unit tests
- **State of the class under test**:
Modifying the state of the class under test directly rather than using methods of the class avoids side effects in test setup.
- **Other exported classes**:
Every class must be tested in isolation to prevent test scenarios from growing exponentially.
- **Single DOM elements if passed as parameters**:
For tests only operating on single DOM elements, rather than a whole page, creating these elements is cheaper than loading an entire HTML fixture.
- **All server requests**:
When running frontend unit tests, the backend may not be reachable, so all outgoing requests need to be mocked.
- **Asynchronous background operations**:
Background operations cannot be stopped or waited on, so they will continue running in the following tests and cause side effects.
#### What *not* to mock in unit tests
- **Non-exported functions or classes**:
Everything that is not exported can be considered private to the module, and will be implicitly tested through the exported classes and functions.
- **Methods of the class under test**:
By mocking methods of the class under test, the mocks will be tested and not the real methods.
- **Utility functions (pure functions, or those that only modify parameters)**:
If a function has no side effects because it has no state, it is safe to not mock it in tests.
- **Full HTML pages**:
Avoid loading the HTML of a full page in unit tests, as it slows down tests.
### Frontend component tests
Component tests cover the state of a single component that is perceivable by a user depending on external signals such as user input, events fired from other components, or application state.
```mermaid
graph RL
plain[Plain JavaScript];
Vue[Vue Components];
feature-flags[Feature Flags];
license-checks[License Checks];
plain---Vuex;
plain---GraphQL;
Vue---plain;
Vue---Vuex;
Vue---GraphQL;
browser---plain;
browser---Vue;
plain---backend;
Vuex---backend;
GraphQL---backend;
Vue---backend;
backend---database;
backend---feature-flags;
backend---license-checks;
class Vue tested;
classDef node color:#909090,fill:#f0f0f0,stroke-width:2px,stroke:#909090
classDef label stroke-width:0;
classDef tested color:#000000,fill:#a0c0ff,stroke:#6666ff,stroke-width:2px,stroke-dasharray: 5, 5;
subgraph " "
tested;
mocked;
class tested tested;
end
```
#### When to use component tests
- **Vue components**
#### When *not* to use component tests
- **Vue applications**:
Vue applications may contain many components.
Testing them on a component level requires too much effort.
Therefore they are tested on frontend integration level.
- **HAML templates**:
HAML templates contain only Markup and no frontend-side logic.
Therefore they are not complete components.
#### What to mock in component tests
- **DOM**:
Operating on the real DOM is significantly slower than on the virtual DOM.
- **Properties and state of the component under test**:
Similar to testing classes, modifying the properties directly (rather than relying on methods of the component) avoids side effects.
- **Vuex store**:
To avoid side effects and keep component tests simple, Vuex stores are replaced with mocks.
- **All server requests**:
Similar to unit tests, when running component tests, the backend may not be reachable, so all outgoing requests need to be mocked.
- **Asynchronous background operations**:
Similar to unit tests, background operations cannot be stopped or waited on, so they will continue running in the following tests and cause side effects.
- **Child components**:
Every component is tested individually, so child components are mocked.
See also [`shallowMount()`](https://vue-test-utils.vuejs.org/api/#shallowmount)
#### What *not* to mock in component tests
- **Methods or computed properties of the component under test**:
By mocking part of the component under test, the mocks will be tested and not the real component.
- **Functions and classes independent from Vue**:
All plain JavaScript code is already covered by unit tests and needs not to be mocked in component tests.
## Integration tests
Formal definition: <https://en.wikipedia.org/wiki/Integration_testing>
......@@ -66,14 +227,86 @@ They're useful to test permissions, redirections, what view is rendered etc.
| `app/controllers/` | `spec/controllers/` | RSpec | For N+1 tests, use [request specs](../query_recorder.md#use-request-specs-instead-of-controller-specs) |
| `app/mailers/` | `spec/mailers/` | RSpec | |
| `lib/api/` | `spec/requests/api/` | RSpec | |
| `app/assets/javascripts/` | `spec/javascripts/`, `spec/frontend/` | Karma & Jest | More details in the [Frontend Testing guide](frontend_testing.md) section. |
| `app/assets/javascripts/` | `spec/javascripts/`, `spec/frontend/` | Karma & Jest | [More details below](#frontend-integration-tests) |
### Frontend integration tests
Integration tests cover the interaction between all components on a single page.
Their abstraction level is comparable to how a user would interact with the UI.
```mermaid
graph RL
plain[Plain JavaScript];
Vue[Vue Components];
feature-flags[Feature Flags];
license-checks[License Checks];
plain---Vuex;
plain---GraphQL;
Vue---plain;
Vue---Vuex;
Vue---GraphQL;
browser---plain;
browser---Vue;
plain---backend;
Vuex---backend;
GraphQL---backend;
Vue---backend;
backend---database;
backend---feature-flags;
backend---license-checks;
class plain tested;
class Vue tested;
class Vuex tested;
class GraphQL tested;
class browser tested;
linkStyle 0,1,2,3,4,5,6 stroke:#6666ff,stroke-width:2px,stroke-dasharray: 5, 5;
classDef node color:#909090,fill:#f0f0f0,stroke-width:2px,stroke:#909090
classDef label stroke-width:0;
classDef tested color:#000000,fill:#a0c0ff,stroke:#6666ff,stroke-width:2px,stroke-dasharray: 5, 5;
subgraph " "
tested;
mocked;
class tested tested;
end
```
#### When to use integration tests
- **Page bundles (`index.js` files in `app/assets/javascripts/pages/`)**:
Testing the page bundles ensures the corresponding frontend components integrate well.
- **Vue applications outside of page bundles**:
Testing Vue applications as a whole ensures the corresponding frontend components integrate well.
#### What to mock in integration tests
- **HAML views (use fixtures instead)**:
Rendering HAML views requires a Rails environment including a running database, which you cannot rely on in frontend tests.
- **All server requests**:
Similar to unit and component tests, when running component tests, the backend may not be reachable, so all outgoing requests must be mocked.
- **Asynchronous background operations that are not perceivable on the page**:
Background operations that affect the page must be tested on this level.
All other background operations cannot be stopped or waited on, so they will continue running in the following tests and cause side effects.
#### What *not* to mock in integration tests
- **DOM**:
Testing on the real DOM ensures your components work in the intended environment.
Part of DOM testing is delegated to [cross-browser testing](https://gitlab.com/gitlab-org/quality/team-tasks/issues/45).
- **Properties or state of components**:
On this level, all tests can only perform actions a user would do.
For example: to change the state of a component, a click event would be fired.
- **Vuex stores**:
When testing the frontend code of a page as a whole, the interaction between Vue components and Vuex stores is covered as well.
### About controller tests
In an ideal world, controllers should be thin. However, when this is not the
case, it's acceptable to write a system/feature test without JavaScript instead
of a controller test. The reason is that testing a fat controller usually
involves a lot of stubbing, things like:
case, it's acceptable to write a system or feature test without JavaScript instead
of a controller test. Testing a fat controller usually involves a lot of stubbing, such as:
```ruby
controller.instance_variable_set(:@user, user)
......@@ -85,8 +318,7 @@ and use methods which are deprecated in Rails 5 ([#23768]).
### About Karma
As you may have noticed, Karma is both in the Unit tests and the Integration
tests category. That's because Karma is a tool that provides an environment to
Karma is both in the Unit tests and the Integration tests category. Karma provides an environment to
run JavaScript tests, so you can either run unit tests (e.g. test a single
JavaScript method), or integration tests (e.g. test a component that is composed
of multiple components).
......@@ -98,7 +330,7 @@ Formal definitions:
- <https://en.wikipedia.org/wiki/System_testing>
- <https://en.wikipedia.org/wiki/White-box_testing>
These kind of tests ensure the GitLab *Rails* application (i.e.
These kind of tests ensure the GitLab *Rails* application (for example,
`gitlab-foss`/`gitlab`) works as expected from a *browser* point of view.
Note that:
......@@ -118,14 +350,94 @@ makes sense since it's a small component, which cannot be tested at the unit or
controller level.
Only test the happy path, but make sure to add a test case for any regression
that couldn't have been caught at lower levels with better tests (i.e. if a
regression is found, regression tests should be added at the lowest-level
that couldn't have been caught at lower levels with better tests (for example, if a
regression is found, regression tests should be added at the lowest level
possible).
| Tests path | Testing engine | Notes |
| ---------- | -------------- | ----- |
| `spec/features/` | [Capybara] + [RSpec] | If your test has the `:js` metadata, the browser driver will be [Poltergeist], otherwise it's using [RackTest]. |
### Frontend feature tests
In contrast to [frontend integration tests](#frontend-integration-tests), feature
tests make requests against the real backend instead of using fixtures.
This also implies that database queries are executed which makes this category significantly slower.
See also:
- The [RSpec testing guidelines](../testing_guide/best_practices.md#rspec).
- System / Feature tests in the [Testing Best Practices](best_practices.md#system--feature-tests).
- [Issue #26159](https://gitlab.com/gitlab-org/gitlab/issues/26159) which aims at combining those guidelines with this page.
```mermaid
graph RL
plain[Plain JavaScript];
Vue[Vue Components];
feature-flags[Feature Flags];
license-checks[License Checks];
plain---Vuex;
plain---GraphQL;
Vue---plain;
Vue---Vuex;
Vue---GraphQL;
browser---plain;
browser---Vue;
plain---backend;
Vuex---backend;
GraphQL---backend;
Vue---backend;
backend---database;
backend---feature-flags;
backend---license-checks;
class backend tested;
class plain tested;
class Vue tested;
class Vuex tested;
class GraphQL tested;
class browser tested;
linkStyle 0,1,2,3,4,5,6,7,8,9,10 stroke:#6666ff,stroke-width:2px,stroke-dasharray: 5, 5;
classDef node color:#909090,fill:#f0f0f0,stroke-width:2px,stroke:#909090
classDef label stroke-width:0;
classDef tested color:#000000,fill:#a0c0ff,stroke:#6666ff,stroke-width:2px,stroke-dasharray: 5, 5;
subgraph " "
tested;
mocked;
class tested tested;
end
```
#### When to use feature tests
- Use cases that require a backend, and cannot be tested using fixtures.
- Behavior that is not part of a page bundle, but defined globally.
#### Relevant notes
A `:js` flag is added to the test to make sure the full environment is loaded:
```ruby
scenario 'successfully', :js do
sign_in(create(:admin))
end
```
The steps of each test are written using ([capybara methods](https://www.rubydoc.info/gems/capybara)).
XHR (XMLHttpRequest) calls might require you to use `wait_for_requests` in between steps, such as:
```ruby
find('.form-control').native.send_keys(:enter)
wait_for_requests
expect(page).not_to have_selector('.card')
```
### Consider **not** writing a system test
If we're confident that the low-level components work well (and we should be if
......
......@@ -128,97 +128,6 @@ module API
end
end
class ProjectDailyFetches < Grape::Entity
expose :fetch_count, as: :count
expose :date
end
class ProjectDailyStatistics < Grape::Entity
expose :fetches do
expose :total_fetch_count, as: :total
expose :fetches, as: :days, using: ProjectDailyFetches
end
end
class Member < Grape::Entity
expose :user, merge: true, using: UserBasic
expose :access_level
expose :expires_at
end
class AccessRequester < Grape::Entity
expose :user, merge: true, using: UserBasic
expose :requested_at
end
class BasicGroupDetails < Grape::Entity
expose :id
expose :web_url
expose :name
end
class Group < BasicGroupDetails
expose :path, :description, :visibility
expose :share_with_group_lock
expose :require_two_factor_authentication
expose :two_factor_grace_period
expose :project_creation_level_str, as: :project_creation_level
expose :auto_devops_enabled
expose :subgroup_creation_level_str, as: :subgroup_creation_level
expose :emails_disabled
expose :mentions_disabled
expose :lfs_enabled?, as: :lfs_enabled
expose :avatar_url do |group, options|
group.avatar_url(only_path: false)
end
expose :request_access_enabled
expose :full_name, :full_path
expose :parent_id
expose :custom_attributes, using: 'API::Entities::CustomAttribute', if: :with_custom_attributes
expose :statistics, if: :statistics do
with_options format_with: -> (value) { value.to_i } do
expose :storage_size
expose :repository_size
expose :wiki_size
expose :lfs_objects_size
expose :build_artifacts_size, as: :job_artifacts_size
end
end
end
class GroupDetail < Group
expose :runners_token, if: lambda { |group, options| options[:user_can_admin_group] }
expose :projects, using: Entities::Project do |group, options|
projects = GroupProjectsFinder.new(
group: group,
current_user: options[:current_user],
options: { only_owned: true, limit: projects_limit }
).execute
Entities::Project.prepare_relation(projects)
end
expose :shared_projects, using: Entities::Project do |group, options|
projects = GroupProjectsFinder.new(
group: group,
current_user: options[:current_user],
options: { only_shared: true, limit: projects_limit }
).execute
Entities::Project.prepare_relation(projects)
end
def projects_limit
if ::Feature.enabled?(:limit_projects_in_groups_api, default_enabled: true)
GroupProjectsFinder::DEFAULT_PROJECTS_LIMIT
else
nil
end
end
end
class DiffRefs < Grape::Entity
expose :base_sha, :head_sha, :start_sha
end
......
# frozen_string_literal: true
module API
module Entities
class AccessRequester < Grape::Entity
expose :user, merge: true, using: UserBasic
expose :requested_at
end
end
end
# frozen_string_literal: true
module API
module Entities
class BasicGroupDetails < Grape::Entity
expose :id
expose :web_url
expose :name
end
end
end
# frozen_string_literal: true
module API
module Entities
class Group < BasicGroupDetails
expose :path, :description, :visibility
expose :share_with_group_lock
expose :require_two_factor_authentication
expose :two_factor_grace_period
expose :project_creation_level_str, as: :project_creation_level
expose :auto_devops_enabled
expose :subgroup_creation_level_str, as: :subgroup_creation_level
expose :emails_disabled
expose :mentions_disabled
expose :lfs_enabled?, as: :lfs_enabled
expose :avatar_url do |group, options|
group.avatar_url(only_path: false)
end
expose :request_access_enabled
expose :full_name, :full_path
expose :parent_id
expose :custom_attributes, using: 'API::Entities::CustomAttribute', if: :with_custom_attributes
expose :statistics, if: :statistics do
with_options format_with: -> (value) { value.to_i } do
expose :storage_size
expose :repository_size
expose :wiki_size
expose :lfs_objects_size
expose :build_artifacts_size, as: :job_artifacts_size
end
end
end
end
end
# frozen_string_literal: true
module API
module Entities
class GroupDetail < Group
expose :runners_token, if: lambda { |group, options| options[:user_can_admin_group] }
expose :projects, using: Entities::Project do |group, options|
projects = GroupProjectsFinder.new(
group: group,
current_user: options[:current_user],
options: { only_owned: true, limit: projects_limit }
).execute
Entities::Project.prepare_relation(projects)
end
expose :shared_projects, using: Entities::Project do |group, options|
projects = GroupProjectsFinder.new(
group: group,
current_user: options[:current_user],
options: { only_shared: true, limit: projects_limit }
).execute
Entities::Project.prepare_relation(projects)
end
def projects_limit
if ::Feature.enabled?(:limit_projects_in_groups_api, default_enabled: true)
GroupProjectsFinder::DEFAULT_PROJECTS_LIMIT
else
nil
end
end
end
end
end
# frozen_string_literal: true
module API
module Entities
class Member < Grape::Entity
expose :user, merge: true, using: UserBasic
expose :access_level
expose :expires_at
end
end
end
# frozen_string_literal: true
module API
module Entities
class ProjectDailyFetches < Grape::Entity
expose :fetch_count, as: :count
expose :date
end
end
end
# frozen_string_literal: true
module API
module Entities
class ProjectDailyStatistics < Grape::Entity
expose :fetches do
expose :total_fetch_count, as: :total
expose :fetches, as: :days, using: ProjectDailyFetches
end
end
end
end
......@@ -31,3 +31,5 @@ module Banzai
end
end
end
Banzai::Filter::IssueReferenceFilter.prepend_if_ee('EE::Banzai::Filter::IssueReferenceFilter')
......@@ -10581,6 +10581,9 @@ msgstr ""
msgid "Issues / Merge Requests"
msgstr ""
msgid "Issues Analytics"
msgstr ""
msgid "Issues can be bugs, tasks or ideas to be discussed. Also, issues are searchable and filterable."
msgstr ""
......
......@@ -1152,13 +1152,6 @@ describe Projects::IssuesController do
expect(controller).to set_flash[:notice].to(/The issue was successfully deleted\./)
end
it "deletes the issue" do
delete :destroy, params: { namespace_id: project.namespace, project_id: project, id: issue.iid, destroy_confirm: true }
expect(response).to have_gitlab_http_status(:found)
expect(controller).to set_flash[:notice].to(/The issue was successfully deleted\./)
end
it "prevents deletion if destroy_confirm is not set" do
expect(Gitlab::ErrorTracking).to receive(:track_exception).and_call_original
......
......@@ -7,14 +7,22 @@ describe 'Group navbar' do
let(:user) { create(:user) }
let(:group) { create(:group) }
let(:analytics_nav_item) do
{
nav_item: _('Analytics'),
nav_sub_items: [
_('Contribution Analytics')
]
}
end
let(:structure) do
[
{
nav_item: _('Group overview'),
nav_sub_items: [
_('Details'),
_('Activity'),
(_('Contribution Analytics') if Gitlab.ee?)
_('Activity')
]
},
{
......@@ -34,6 +42,7 @@ describe 'Group navbar' do
nav_item: _('Kubernetes'),
nav_sub_items: []
},
(analytics_nav_item if Gitlab.ee?),
{
nav_item: _('Members'),
nav_sub_items: []
......
......@@ -59,13 +59,13 @@ describe 'Project navbar' do
_('Environments'),
_('Error Tracking'),
_('Serverless'),
_('Kubernetes'),
_('Auto DevOps')
_('Kubernetes')
]
},
{
nav_item: _('Analytics'),
nav_sub_items: [
_('CI / CD Analytics'),
(_('Code Review') if Gitlab.ee?),
_('Cycle Analytics'),
_('Repository Analytics')
......
......@@ -44,7 +44,7 @@ exports[`Dashboard template matches the default snapshot 1`] = `
class="d-flex flex-column overflow-hidden"
>
<gl-dropdown-header-stub
class="text-center"
class="monitor-environment-dropdown-header text-center"
>
Environment
</gl-dropdown-header-stub>
......
......@@ -35,13 +35,17 @@ describe('DashboardsDropdown', () => {
const findItems = () => wrapper.findAll(GlDropdownItem);
const findItemAt = i => wrapper.findAll(GlDropdownItem).at(i);
const findSearchInput = () => wrapper.find({ ref: 'monitorDashboardsDropdownSearch' });
const findNoItemsMsg = () => wrapper.find({ ref: 'monitorDashboardsDropdownMsg' });
const setSearchTerm = searchTerm => wrapper.setData({ searchTerm });
describe('when it receives dashboards data', () => {
beforeEach(() => {
wrapper = createComponent();
});
it('displays an item for each dashboard', () => {
expect(wrapper.findAll(GlDropdownItem).length).toEqual(dashboardGitResponse.length);
expect(findItems().length).toEqual(dashboardGitResponse.length);
});
it('displays items with the dashboard display name', () => {
......@@ -49,6 +53,32 @@ describe('DashboardsDropdown', () => {
expect(findItemAt(1).text()).toBe(dashboardGitResponse[1].display_name);
expect(findItemAt(2).text()).toBe(dashboardGitResponse[2].display_name);
});
it('displays a search input', () => {
expect(findSearchInput().isVisible()).toBe(true);
});
it('hides no message text by default', () => {
expect(findNoItemsMsg().isVisible()).toBe(false);
});
it('filters dropdown items when searched for item exists in the list', () => {
const searchTerm = 'Default';
setSearchTerm(searchTerm);
return wrapper.vm.$nextTick(() => {
expect(findItems()).toHaveLength(1);
});
});
it('shows no items found message when searched for item does not exists in the list', () => {
const searchTerm = 'does-not-exist';
setSearchTerm(searchTerm);
return wrapper.vm.$nextTick(() => {
expect(findNoItemsMsg().isVisible()).toBe(true);
});
});
});
describe('when a system dashboard is selected', () => {
......@@ -224,7 +254,7 @@ describe('DashboardsDropdown', () => {
it('displays an item for each dashboard', () => {
const item = wrapper.findAll({ ref: 'duplicateDashboardItem' });
expect(findItems().length).toEqual(dashboardGitResponse.length);
expect(findItems()).toHaveLength(dashboardGitResponse.length);
expect(item.length).toBe(0);
});
......
......@@ -518,6 +518,15 @@ export const metricsDashboardPayload = {
],
};
const customDashboardsData = new Array(30).fill(null).map((_, idx) => ({
default: false,
display_name: `Custom Dashboard ${idx}`,
can_edit: true,
system_dashboard: false,
project_blob_path: `${mockProjectDir}/blob/master/dashboards/.gitlab/dashboards/dashboard_${idx}.yml`,
path: `.gitlab/dashboards/dashboard_${idx}.yml`,
}));
export const dashboardGitResponse = [
{
default: true,
......@@ -527,22 +536,7 @@ export const dashboardGitResponse = [
project_blob_path: null,
path: 'config/prometheus/common_metrics.yml',
},
{
default: false,
display_name: 'Custom Dashboard 1',
can_edit: true,
system_dashboard: false,
project_blob_path: `${mockProjectDir}/blob/master/dashboards/.gitlab/dashboards/dashboard_1.yml`,
path: '.gitlab/dashboards/dashboard_1.yml',
},
{
default: false,
display_name: 'Custom Dashboard 2',
can_edit: true,
system_dashboard: false,
project_blob_path: `${mockProjectDir}/blob/master/dashboards/.gitlab/dashboards/dashboard_2.yml`,
path: '.gitlab/dashboards/dashboard_2.yml',
},
...customDashboardsData,
];
export const graphDataPrometheusQuery = {
......
......@@ -159,6 +159,7 @@ exports[`Settings Form renders 1`] = `
>
<glbutton-stub
class="mr-2 d-block"
disabled="true"
size="md"
type="reset"
variant="secondary"
......
......@@ -124,11 +124,35 @@ describe('Settings Form', () => {
form = findForm();
});
describe('form cancel event', () => {
describe('cancel button', () => {
it('has type reset', () => {
expect(findCancelButton().attributes('type')).toBe('reset');
});
it('is disabled the form was not changed from his original value', () => {
store.dispatch('receiveSettingsSuccess', { foo: 'bar' });
return wrapper.vm.$nextTick().then(() => {
expect(findCancelButton().attributes('disabled')).toBe('true');
});
});
it('is disabled when the form data is loading', () => {
store.dispatch('toggleLoading');
return wrapper.vm.$nextTick().then(() => {
expect(findCancelButton().attributes('disabled')).toBe('true');
});
});
it('is enabled when the user changed something in the form and the data is not being loaded', () => {
store.dispatch('receiveSettingsSuccess', { foo: 'bar' });
store.dispatch('updateSettings', { foo: 'baz' });
return wrapper.vm.$nextTick().then(() => {
expect(findCancelButton().attributes('disabled')).toBe(undefined);
});
});
});
describe('form cancel event', () => {
it('calls the appropriate function', () => {
dispatchSpy.mockReturnValue();
form.trigger('reset');
......
import * as getters from '~/registry/settings/store/getters';
import * as utils from '~/registry/settings/utils';
import { formOptions } from '../mock_data';
describe('Getters registry settings store', () => {
const settings = {
cadence: 'foo',
keep_n: 'bar',
older_than: 'baz',
};
describe.each`
getter | variable | formOption
${'getCadence'} | ${'cadence'} | ${'cadence'}
${'getKeepN'} | ${'keep_n'} | ${'keepN'}
${'getOlderThan'} | ${'older_than'} | ${'olderThan'}
`('Options getter', ({ getter, variable, formOption }) => {
beforeEach(() => {
utils.findDefaultOption = jest.fn();
});
it(`${getter} returns ${variable} when ${variable} exists in settings`, () => {
expect(getters[getter]({ settings })).toBe(settings[variable]);
});
it(`${getter} calls findDefaultOption when ${variable} does not exists in settings`, () => {
getters[getter]({ settings: {}, formOptions });
expect(utils.findDefaultOption).toHaveBeenCalledWith(formOptions[formOption]);
});
});
describe('getIsDisabled', () => {
it('returns false when original is equal to settings', () => {
const same = { foo: 'bar' };
expect(getters.getIsEdited({ original: same, settings: same })).toBe(false);
});
it('returns true when original is different from settings', () => {
expect(getters.getIsEdited({ original: { foo: 'bar' }, settings: { foo: 'baz' } })).toBe(
true,
);
});
});
});
import Vue from 'vue';
import initVueAlerts from '~/vue_alerts';
import { setHTMLFixture } from 'helpers/fixtures';
import { TEST_HOST } from 'helpers/test_constants';
describe('VueAlerts', () => {
const alerts = [
{
title: 'Lorem',
html: 'Lorem <strong>Ipsum</strong>',
dismissible: true,
primaryButtonText: 'Okay!',
primaryButtonLink: `${TEST_HOST}/okay`,
variant: 'tip',
},
{
title: 'Hello',
html: 'Hello <strong>World</strong>',
dismissible: false,
primaryButtonText: 'No!',
primaryButtonLink: `${TEST_HOST}/no`,
variant: 'info',
},
];
beforeEach(() => {
setHTMLFixture(
alerts
.map(
x => `
<div class="js-vue-alert"
data-dismissible="${x.dismissible}"
data-title="${x.title}"
data-primary-button-text="${x.primaryButtonText}"
data-primary-button-link="${x.primaryButtonLink}"
data-variant="${x.variant}">${x.html}</div>
`,
)
.join('\n'),
);
});
const findJsHooks = () => document.querySelectorAll('.js-vue-alert');
const findAlerts = () => document.querySelectorAll('.gl-alert');
const findAlertDismiss = alert => alert.querySelector('.gl-alert-dismiss');
const serializeAlert = alert => ({
title: alert.querySelector('.gl-alert-title').textContent.trim(),
html: alert.querySelector('.gl-alert-body div').innerHTML,
dismissible: Boolean(alert.querySelector('.gl-alert-dismiss')),
primaryButtonText: alert.querySelector('.gl-alert-action').textContent.trim(),
primaryButtonLink: alert.querySelector('.gl-alert-action').href,
variant: [...alert.classList].find(x => x.match('gl-alert-')).replace('gl-alert-', ''),
});
it('starts with only JsHooks', () => {
expect(findJsHooks().length).toEqual(alerts.length);
expect(findAlerts().length).toEqual(0);
});
describe('when mounted', () => {
beforeEach(() => {
initVueAlerts();
});
it('replaces JsHook with GlAlert', () => {
expect(findJsHooks().length).toEqual(0);
expect(findAlerts().length).toEqual(alerts.length);
});
it('passes along props to gl-alert', () => {
expect([...findAlerts()].map(serializeAlert)).toEqual(alerts);
});
describe('when dismissed', () => {
beforeEach(() => {
findAlertDismiss(findAlerts()[0]).click();
return Vue.nextTick();
});
it('hides the alert', () => {
expect(findAlerts().length).toEqual(alerts.length - 1);
});
});
});
});
import { shallowMount } from '@vue/test-utils';
import { GlAlert } from '@gitlab/ui';
import DismissibleAlert from '~/vue_shared/components/dismissible_alert.vue';
const TEST_HTML = 'Hello World! <strong>Foo</strong>';
describe('vue_shared/components/dismissible_alert', () => {
const testAlertProps = {
primaryButtonText: 'Lorem ipsum',
primaryButtonLink: '/lorem/ipsum',
};
let wrapper;
const createComponent = (props = {}) => {
wrapper = shallowMount(DismissibleAlert, {
propsData: {
html: TEST_HTML,
...testAlertProps,
...props,
},
});
};
afterEach(() => {
wrapper.destroy();
});
const findAlert = () => wrapper.find(GlAlert);
describe('with default', () => {
beforeEach(() => {
createComponent();
});
it('shows alert', () => {
const alert = findAlert();
expect(alert.exists()).toBe(true);
expect(alert.props()).toEqual(expect.objectContaining(testAlertProps));
});
it('shows given HTML', () => {
expect(findAlert().html()).toContain(TEST_HTML);
});
describe('when dismissed', () => {
beforeEach(() => {
findAlert().vm.$emit('dismiss');
});
it('hides the alert', () => {
expect(findAlert().exists()).toBe(false);
});
});
});
});
......@@ -55,6 +55,7 @@ module FilterSpecHelper
def reference_pipeline(context = {})
context.reverse_merge!(project: project) if defined?(project)
context.reverse_merge!(current_user: current_user) if defined?(current_user)
filters = [
Banzai::Filter::AutolinkFilter,
......
# frozen_string_literal: true
RSpec.shared_examples 'verified navigation bar' do
let(:expected_structure) do
structure.compact!
structure.each { |s| s[:nav_sub_items].compact! }
structure
end
it 'renders correctly' do
current_structure = page.find_all('.sidebar-top-level-items > li', class: ['!hidden']).map do |item|
current_structure = page.all('.sidebar-top-level-items > li', class: ['!hidden']).map do |item|
nav_item = item.find_all('a').first.text.gsub(/\s+\d+$/, '') # remove counts at the end
nav_sub_items = item
.find_all('.sidebar-sub-level-items a')
.map(&:text)
.drop(1) # remove the first hidden item
nav_sub_items = item.all('.sidebar-sub-level-items > li', class: ['!fly-out-top-item']).map do |list_item|
list_item.all('a').first.text
end
{ nav_item: nav_item, nav_sub_items: nav_sub_items }
end
structure.each { |s| s[:nav_sub_items].compact! }
expect(current_structure).to eq(structure)
expect(current_structure).to eq(expected_structure)
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment