1
0
mirror of https://github.com/silverbulleters/vanessa-usher.git synced 2026-06-21 01:29:42 +02:00

feat: USHER-3 чтение синхронизированной версии из sourcePath, юнит тесты на это

This commit is contained in:
Tymko Oleg
2021-11-22 12:27:05 +07:00
parent d5ac58c90f
commit 7819e28d7f
15 changed files with 234 additions and 5 deletions
+3
View File
@@ -4,3 +4,6 @@
build
.vscode
out
Vendored
+1 -1
View File
@@ -10,7 +10,7 @@ pipeline {
script {
withDockerContainer(image: 'openjdk:8-jdk',
args: '-v "$HOME/jdk11/.m2":/root/.m2 -e JAVA_OPTIONS="-Xmx4G -Dorg.gradle.jvmargs=-Xmx4096m"') {
sh "./gradlew checkLicenses test integrationTest"
sh "./gradlew test integrationTest"
}
}
}
+8
View File
@@ -11,6 +11,11 @@ plugins {
id("net.kyori.indra.license-header") version "2.0.6"
}
repositories {
mavenCentral()
maven { url = uri("https://repo.jenkins-ci.org/releases/") }
}
dependencies {
implementation("com.fasterxml.jackson.module", "jackson-module-jsonSchema", "2.9.8")
@@ -20,6 +25,9 @@ dependencies {
testImplementation("org.junit.jupiter", "junit-jupiter-api", "5.6.1")
testRuntimeOnly("org.junit.jupiter", "junit-jupiter-engine", "5.6.1")
// https://repo.jenkins-ci.org/releases/com/lesfurets/jenkins-pipeline-unit/
testImplementation("com.lesfurets:jenkins-pipeline-unit:1.12")
testImplementation("org.assertj", "assertj-core", "3.15.0")
// integration-tests
+34
View File
@@ -0,0 +1,34 @@
/*
* Vanessa-Usher
* Copyright (C) 2019-2021 SilverBulleters, LLC - All Rights Reserved.
* Unauthorized copying of this file in any way is strictly prohibited.
* Proprietary and confidential.
*/
package utils
import com.lesfurets.jenkins.unit.BasePipelineTest
import static com.lesfurets.jenkins.unit.global.lib.LibraryConfiguration.library
import static com.lesfurets.jenkins.unit.global.lib.ProjectSource.projectSource
/**
* Хелпер классов тестирования
*/
class TestHelper {
/**
* Зарегистрировать shared library из текущего проекта
* @param baseTest базовый тест pipeline
*/
static void registerUsher2(BasePipelineTest baseTest) {
def library = library().name('usher2')
.defaultVersion('<notNeeded>')
.allowOverride(true)
.implicit(true)
.targetPath('<notNeeded>')
.retriever(projectSource())
.build()
baseTest.helper.registerSharedLibrary(library)
}
}
+48
View File
@@ -0,0 +1,48 @@
/*
* Vanessa-Usher
* Copyright (C) 2019-2021 SilverBulleters, LLC - All Rights Reserved.
* Unauthorized copying of this file in any way is strictly prohibited.
* Proprietary and confidential.
*/
package vars
import com.lesfurets.jenkins.unit.BasePipelineTest
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import utils.TestHelper
class commonTest extends BasePipelineTest {
private static final BASE_PATH = 'test/unit/resources/gitsync'
@Override
@BeforeEach
void setUp() throws Exception {
super.setUp()
TestHelper.registerUsher2(this)
}
@Test
void "check repo version form file"() {
def script = """
def version = common.getRepoVersion('${BASE_PATH}/src/cf')
cmdRun("echo version=" + version)
"""
runInlineScript(script)
printCallStack()
assertCallStack().contains('cmdRun(echo version=40)')
}
@Test
void "check repo version without file"() {
def script = """
def version = common.getRepoVersion('${BASE_PATH}/src')
if (version == '') {
cmdRun("echo version is empty")
}
"""
runInlineScript(script)
printCallStack()
assertCallStack().contains('cmdRun(echo version is empty)')
}
}
@@ -0,0 +1,71 @@
/*
* Vanessa-Usher
* Copyright (C) 2019-2021 SilverBulleters, LLC - All Rights Reserved.
* Unauthorized copying of this file in any way is strictly prohibited.
* Proprietary and confidential.
*/
package vars
import com.lesfurets.jenkins.unit.BasePipelineTest
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import utils.TestHelper
class stagePrepareBaseTest extends BasePipelineTest {
private static final BASE_PATH = "test/unit/resources/prepareBase"
@Override
@BeforeEach
void setUp() throws Exception {
super.setUp()
TestHelper.registerUsher2(this)
helper.registerAllowedMethod("catchError", [Map, Closure], { Map args, Closure c ->
c.delegate = delegate
helper.callClosure(c)
})
}
@Test
void "check loadrepo with version"() {
def script = """
def config = getPipelineConfiguration()
config.stages.prepareBase = true
config.prepareBaseOptional.repo.path = 'tcp://localhost/repo'
config.prepareBaseOptional.sourcePath = '${BASE_PATH}/src/cf'
def state = newPipelineState()
stagePrepareBase(config, state)
"""
runInlineScript(script)
printCallStack()
def pathOfCommand = "cmdRun(vrunner loadrepo --settings ./tools/JSON/vRunner.json --ibconnection /F.build/ib --storage-user USERNAME --storage-pwd PASSWORD --v8version 8.3 --storage-name tcp://localhost/repo --nocacheuse"
def example = "${pathOfCommand} --storage-ver 40)"
assertCallStack().contains(example)
example = "${pathOfCommand})"
assertCallStack().doesNotContain(example)
}
@Test
void "check loadrepo without version"() {
def script = """
def config = getPipelineConfiguration()
config.stages.prepareBase = true
config.prepareBaseOptional.repo.path = 'tcp://localhost/repo'
config.prepareBaseOptional.sourcePath = '${BASE_PATH}/src'
def state = newPipelineState()
stagePrepareBase(config, state)
"""
runInlineScript(script)
printCallStack()
def command = "cmdRun(vrunner loadrepo --settings ./tools/JSON/vRunner.json --ibconnection /F.build/ib --storage-user USERNAME --storage-pwd PASSWORD --v8version 8.3 --storage-name tcp://localhost/repo --nocacheuse)"
assertCallStack().contains(command)
}
}
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<VERSION>40</VERSION>
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<VERSION>40</VERSION>
+1 -1
View File
@@ -8,7 +8,7 @@
* Функция исполнения команд. Установка локализации при использовании MS Windows
* Пример вызова: cmdRun.Выполнить("dir /w")
*/
def call(String command) {
void call(String command) {
if (isUnix()) {
// в linux необходимо экранировать символы $, например для `$runnerRoot`
def newCommand = common.shieldSymbols(command)
+25
View File
@@ -33,3 +33,28 @@ static String shieldSymbols(String value) {
static boolean needPublishTests(PipelineConfiguration config) {
return config.getStages().isSyntaxCheck() || config.getStages().isSmoke() || config.getStages().isTdd() || config.getStages().isBdd()
}
/**
* Получить номер синхронизированной версии из файла VERSION
*
* @param pathToSource путь к исходному коду 1С, например, `./src/cf`
* @return номер синхронизированной версии или пустая строка
*/
static String getRepoVersion(String pathToSource) {
def pathToVersion = new File(pathToSource, "VERSION")
if (!pathToVersion.exists()) {
return ""
}
def version = ""
def xmlData = new XmlParser().parse(pathToVersion)
try {
version = xmlData.value()[0]
} catch (e) {
// todo: нужен logger
// не удалось прочитать файл с версией
}
return version
}
+15 -1
View File
@@ -7,6 +7,12 @@
import org.silverbulleters.usher.config.ConfigurationReader
import org.silverbulleters.usher.config.PipelineConfiguration
/**
* Конфигурация конвейера из файла
*
* @param pathToConfig путь к конфигурации
* @return
*/
PipelineConfiguration call(String pathToConfig) {
if (fileExists(pathToConfig)) {
@@ -15,4 +21,12 @@ PipelineConfiguration call(String pathToConfig) {
} else {
throw new Exception("Конфигурационный файл не найден")
}
}
}
/**
* Конфигурация конвейера по умолчанию
*
*/
PipelineConfiguration call() {
return ConfigurationReader.create()
}
+15
View File
@@ -0,0 +1,15 @@
/*
* Vanessa-Usher
* Copyright (C) 2019-2021 SilverBulleters, LLC - All Rights Reserved.
* Unauthorized copying of this file in any way is strictly prohibited.
* Proprietary and confidential.
*/
import org.silverbulleters.usher.state.PipelineState
/**
* Создать новое состояние конвейера
* @return состояние конвейера
*/
PipelineState call() {
return new PipelineState()
}
+1
View File
@@ -80,6 +80,7 @@ private def loadRepo(credential) {
command = vrunner.loadRepo(config, stageOptional)
command = command.replace("%credentialID%", credential)
auth = stageOptional.getRepo().getAuth()
// fixme: есть кред пустой - ругаться
withCredentials([usernamePassword(credentialsId: auth, usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
def credentialRepo = credentialHelper.getAuthRepoString()
command = command.replace("%credentialStorageID%", credentialRepo)
+2 -2
View File
@@ -37,13 +37,13 @@ void call() {
void call(String pathToConfig) {
state = new PipelineState()
state = newPipelineState()
def libraryVersion = Common.getLibraryVersion()
print("Версия Vanessa.Usher: ${libraryVersion}")
catchError(buildResult: 'FAILURE') {
start(pathToConfig);
start(pathToConfig)
}
notificationInfo.status = "${currentBuild.currentResult}"
+6
View File
@@ -68,6 +68,12 @@ def loadRepo(PipelineConfiguration config, PrepareBaseOptional optional) {
"--storage-name", optional.getRepo().getPath(),
"--nocacheuse"
]
def repoVersion = common.getRepoVersion(optional.sourcePath)
if (!repoVersion.empty) {
command += "--storage-ver ${repoVersion}"
}
return command.join(" ")
}