In ainneoin go bhfuil a fhios ag gach duine go maith go bhfuil tástáil do bhogearraí tábhachtach agus riachtanach, agus go bhfuil go leor ag déanamh go huathoibríoch é le fada an lá, i méid Habr ní raibh aon chos amháin ann chun meascán de tháirgí coitianta den sórt sin a bhunú i. an nideoige seo mar (an rud is fearr linn) GitLab agus JUnit . Líonaimis an bhearna seo!

tosaigh
Ar dtús, lig dom roinnt comhthéacs a thabhairt:
- Ós rud é go ritheann ár bhfeidhmchláir go léir ar Kubernetes, déanfaimid machnamh ar thástálacha a reáchtáil ar an mbonneagar cuí.
- Le haghaidh tionóil agus imscaradh a úsáidimid (i dtéarmaí comhpháirteanna bonneagair, ciallaíonn sé seo go huathoibríoch go bhfuil Helm i gceist freisin).
- Ní bheidh mé ag dul isteach ar na sonraí maidir le cruthú iarbhír na dtástálacha: inár gcás, scríobhann an cliant na tástálacha é féin, agus ní dhéanaimid chinntiú ach go n-seoladh (agus láithreacht tuarascáil chomhfhreagrach san iarratas cumaisc).
Cén chuma a bheidh ar sheicheamh ginearálta na ngníomhartha?
- Ag tógáil an iarratais - fágfaimid an cur síos ar an gcéim seo ar lár.
- Imscar an feidhmchlár chuig ainmspás ar leith de bhraisle Kubernetes agus cuir tús leis an tástáil.
- Déantán a chuardach agus tuairiscí JUnit a pharsáil le GitLab.
- Ainmspás a cruthaíodh roimhe seo a scriosadh.
Anois - a chur i bhfeidhm!
coigeartú
GitLab CI
Let tús le blúire .gitlab-ci.yaml, a chuireann síos ar an bhfeidhmchlár a imscaradh agus tástálacha a rith. Bhí an liostú sách toirtiúil, mar sin forlíontar go hiomlán é le tuairimí:
variables:
# объявляем версию werf, которую собираемся использовать
WERF_VERSION: "1.0 beta"
.base_deploy: &base_deploy
script:
# создаем namespace в K8s, если его нет
- kubectl --context="${WERF_KUBE_CONTEXT}" get ns ${CI_ENVIRONMENT_SLUG} || kubectl create ns ${CI_ENVIRONMENT_SLUG}
# загружаем werf и деплоим — подробнее об этом см. в документации
# (https://werf.io/how_to/gitlab_ci_cd_integration.html#deploy-stage)
- type multiwerf && source <(multiwerf use ${WERF_VERSION})
- werf version
- type werf && source <(werf ci-env gitlab --tagging-strategy tag-or-branch --verbose)
- werf deploy --stages-storage :local
--namespace ${CI_ENVIRONMENT_SLUG}
--set "global.commit_ref_slug=${CI_COMMIT_REF_SLUG:-''}"
# передаем переменную `run_tests`
# она будет использоваться в рендере Helm-релиза
--set "global.run_tests=${RUN_TESTS:-no}"
--set "global.env=${CI_ENVIRONMENT_SLUG}"
# изменяем timeout (бывают долгие тесты) и передаем его в релиз
--set "global.ci_timeout=${CI_TIMEOUT:-900}"
--timeout ${CI_TIMEOUT:-900}
dependencies:
- Build
.test-base: &test-base
extends: .base_deploy
before_script:
# создаем директорию для будущего отчета, исходя из $CI_COMMIT_REF_SLUG
- mkdir /mnt/tests/${CI_COMMIT_REF_SLUG} || true
# вынужденный костыль, т.к. GitLab хочет получить артефакты в своем build-dir’е
- mkdir ./tests || true
- ln -s /mnt/tests/${CI_COMMIT_REF_SLUG} ./tests/${CI_COMMIT_REF_SLUG}
after_script:
# после окончания тестов удаляем релиз вместе с Job’ом
# (и, возможно, его инфраструктурой)
- type multiwerf && source <(multiwerf use ${WERF_VERSION})
- werf version
- type werf && source <(werf ci-env gitlab --tagging-strategy tag-or-branch --verbose)
- werf dismiss --namespace ${CI_ENVIRONMENT_SLUG} --with-namespace
# мы разрешаем падения, но вы можете сделать иначе
allow_failure: true
variables:
RUN_TESTS: 'yes'
# задаем контекст в werf
# (https://werf.io/how_to/gitlab_ci_cd_integration.html#infrastructure)
WERF_KUBE_CONTEXT: 'admin@stage-cluster'
tags:
# используем раннер с тегом `werf-runner`
- werf-runner
artifacts:
# требуется собрать артефакт для того, чтобы его можно было увидеть
# в пайплайне и скачать — например, для более вдумчивого изучения
paths:
- ./tests/${CI_COMMIT_REF_SLUG}/*
# артефакты старше недели будут удалены
expire_in: 7 day
# важно: эти строки отвечают за парсинг отчета GitLab’ом
reports:
junit: ./tests/${CI_COMMIT_REF_SLUG}/report.xml
# для упрощения здесь показаны всего две стадии
# в реальности же у вас их будет больше — как минимум из-за деплоя
stages:
- build
- tests
build:
stage: build
script:
# сборка — снова по документации по werf
# (https://werf.io/how_to/gitlab_ci_cd_integration.html#build-stage)
- type multiwerf && source <(multiwerf use ${WERF_VERSION})
- werf version
- type werf && source <(werf ci-env gitlab --tagging-strategy tag-or-branch --verbose)
- werf build-and-publish --stages-storage :local
tags:
- werf-runner
except:
- schedules
run tests:
<<: *test-base
environment:
# "сама соль" именования namespace’а
# (https://docs.gitlab.com/ce/ci/variables/predefined_variables.html)
name: tests-${CI_COMMIT_REF_SLUG}
stage: tests
except:
- schedules
Kubernetes
Anois san eolaire .helm/templates cruthaimis YAML le Job - tests-job.yaml — tástálacha a rith agus na hacmhainní Kubernetes a theastaíonn uaidh. Féach na mínithe tar éis liostú:
{{- if eq .Values.global.run_tests "yes" }}
---
apiVersion: v1
kind: ConfigMap
metadata:
name: tests-script
data:
tests.sh: |
echo "======================"
echo "${APP_NAME} TESTS"
echo "======================"
cd /app
npm run test:ci
cp report.xml /app/test_results/${CI_COMMIT_REF_SLUG}/
echo ""
echo ""
echo ""
chown -R 999:999 /app/test_results/${CI_COMMIT_REF_SLUG}
---
apiVersion: batch/v1
kind: Job
metadata:
name: {{ .Chart.Name }}-test
annotations:
"helm.sh/hook": post-install,post-upgrade
"helm.sh/hook-weight": "2"
"werf/watch-logs": "true"
spec:
activeDeadlineSeconds: {{ .Values.global.ci_timeout }}
backoffLimit: 1
template:
metadata:
name: {{ .Chart.Name }}-test
spec:
containers:
- name: test
command: ['bash', '-c', '/app/tests.sh']
{{ tuple "application" . | include "werf_container_image" | indent 8 }}
env:
- name: env
value: {{ .Values.global.env }}
- name: CI_COMMIT_REF_SLUG
value: {{ .Values.global.commit_ref_slug }}
- name: APP_NAME
value: {{ .Chart.Name }}
{{ tuple "application" . | include "werf_container_env" | indent 8 }}
volumeMounts:
- mountPath: /app/test_results/
name: data
- mountPath: /app/tests.sh
name: tests-script
subPath: tests.sh
tolerations:
- key: dedicated
operator: Exists
- key: node-role.kubernetes.io/master
operator: Exists
restartPolicy: OnFailure
volumes:
- name: data
persistentVolumeClaim:
claimName: {{ .Chart.Name }}-pvc
- name: tests-script
configMap:
name: tests-script
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: {{ .Chart.Name }}-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Mi
storageClassName: {{ .Chart.Name }}-{{ .Values.global.commit_ref_slug }}
volumeName: {{ .Values.global.commit_ref_slug }}
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: {{ .Values.global.commit_ref_slug }}
spec:
accessModes:
- ReadWriteOnce
capacity:
storage: 10Mi
local:
path: /mnt/tests/
nodeAffinity:
required:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/hostname
operator: In
values:
- kube-master
persistentVolumeReclaimPolicy: Delete
storageClassName: {{ .Chart.Name }}-{{ .Values.global.commit_ref_slug }}
{{- end }}
Cén cineál acmhainní cur síos air sa chumraíocht seo? Agus é á imscaradh, cruthaímid ainmspás uathúil don tionscadal (léirítear é seo i .gitlab-ci.yaml - tests-${CI_COMMIT_REF_SLUG}) agus é a rolladh amach:
- ConfigMap le script tástála;
- Post le cur síos ar an pod agus an treoir shonraithe
command, a ritheann ach na tástálacha; - PV agus PVC, a ligeann duit sonraí tástála a stóráil.
Tabhair aird ar an riocht tosaigh le if ag tús an fhorléirithe - dá réir sin, ní mór comhaid YAML eile den chairt Helm leis an bhfeidhmchlár a fhilleadh isteach droim ar ais dearadh ionas nach n-imlonnaítear iad le linn tástála. Is é sin:
{{- if ne .Values.global.run_tests "yes" }}
---
я другой ямлик
{{- end }}
Mar sin féin, má tá na tástálacha roinnt bonneagair a cheangal (mar shampla, Redis, RabbitMQ, Mongo, PostgreSQL ...) - is féidir a n-YAMLanna a bheith aon mhúchadh. Imscaradh isteach i dtimpeallacht tástála iad freisin... déan iad a choigeartú de réir mar is cuí, ar ndóigh.
Teagmháil dheiridh
Mar tionóil agus imscaradh ag baint úsáide as oibreacha fíneálacha le tamall anuas ach ar an bhfreastalaí tógála (le gitlab-runner), agus seoltar an pod le tástálacha ar an máistir, beidh ort eolaire a chruthú /mnt/tests ar an máistir agus tabhair don reathaí é, mar shampla, trí NFS. Is féidir sampla mionsonraithe le mínithe a fháil i .
Beidh an toradh:
user@kube-master:~$ cat /etc/exports | grep tests
/mnt/tests IP_gitlab-builder/32(rw,nohide,insecure,no_subtree_check,sync,all_squash,anonuid=999,anongid=998)
user@gitlab-runner:~$ cat /etc/fstab | grep tests
IP_kube-master:/mnt/tests /mnt/tests nfs4 _netdev,auto 0 0
Ní chuireann aon duine cosc ar sciar NFS a dhéanamh go díreach ar gitlab-runner, agus ansin é a shuiteáil i gcódanna.
Tabhair faoi deara
B'fhéidir go bhfuil tú ag fiafraí cén fáth a ndéanann tú gach rud casta trí Jab a chruthú más féidir leat script a rith le tástálacha go díreach ar an rádala bhlaosc? Tá an freagra sách fánach ...
Éilíonn roinnt tástálacha rochtain ar an mbonneagar (MongoDB, RabbitMQ, PostgreSQL, etc.) chun a fhíorú go n-oibríonn siad i gceart. Déanaimid tástáil aontaithe - leis an gcur chuige seo, bíonn sé éasca aonáin bhreise den sórt sin a áireamh. Chomh maith le seo, a fháil againn caighdeán cur chuige imlonnaithe (fiú má úsáidtear NFS, gléasadh breise ar eolairí).
Toradh
Cad a fheicfimid nuair a chuirfimid an chumraíocht ullmhaithe i bhfeidhm?
Taispeánfaidh an t-iarratas ar chumasc staitisticí achoimre le haghaidh tástálacha a ritheadh sa phíblíne is déanaí:

Is féidir gach earráid a chliceáil anseo le haghaidh sonraí:

NB: Tabharfaidh an léitheoir aireach faoi deara go bhfuil muid ag tástáil feidhmchlár NodeJS, agus sna screenshots - .NET ... Ná bíodh iontas ort: níl ann ach agus an t-alt á ullmhú, níor aimsíodh aon earráidí agus an chéad iarratas á thástáil, ach tá siad fuarthas i gceann eile.
Conclúid
Mar a fheiceann tú, níl aon rud casta!
I bprionsabal, má tá bailitheoir sliogáin agat cheana féin agus go n-oibríonn sé, ach nach bhfuil Kubernetes ag teastáil uait, beidh sé níos simplí fós an tástáil a cheangal leis ná mar a thuairiscítear anseo. Agus i gheobhaidh tú samplaí do Ruby, Go, Gradle, Maven agus roinnt eile.
PS
Léigh freisin ar ár mblag:
- «";
- «";
- «'.
Foinse: will.com
