Skip to content
This repository has been archived by the owner on Jan 19, 2024. It is now read-only.

Commit

Permalink
Make detekt happy
Browse files Browse the repository at this point in the history
  • Loading branch information
pawelpasterz committed Sep 28, 2020
1 parent 38a1ebb commit e5d7f5d
Show file tree
Hide file tree
Showing 51 changed files with 620 additions and 477 deletions.
1 change: 1 addition & 0 deletions flank-scripts/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ repositories {
detekt {
input = files("src/main/kotlin", "src/test/kotlin")
config = files("../config/detekt.yml")
autoCorrect = true
reports {
xml {
enabled = false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import java.time.format.DateTimeFormatter
fun generateNextReleaseTag(previousReleaseTag: String): String {
val (year, month, number) = previousReleaseTag.trimStart('v').split('.')
return if (isNextReleaseInCurrentMonth(
year,
month
)
year,
month
)
) "v$year.$month.${number.toInt() + 1}" else currentMonthFirstTag()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ fun File.appendReleaseNotes(releaseNotesWithType: ReleaseNotesWithType, releaseT
}

private fun File.appendToReleaseNotes(releaseNotesWithType: ReleaseNotesWithType, releaseTag: String) {
writeText(releaseNotesWithType.asString(releaseTag).withNewLineAtTheEnd() +
readLines().joinToString(System.lineSeparator()).withNewLineAtTheEnd())
writeText(
releaseNotesWithType.asString(releaseTag).withNewLineAtTheEnd() +
readLines().joinToString(System.lineSeparator()).withNewLineAtTheEnd()
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ class ReleaseCommand : CliktCommand(name = "release", help = "Contains all relea

init {
subcommands(
ReleaseFlankCommand(),
UpdateBugSnagCommand(),
DeleteOldSnapshotCommand(),
SyncMavenCommand(),
DeleteOldReleaseCommand(),
DeleteOldTagCommand()
ReleaseFlankCommand(),
UpdateBugSnagCommand(),
DeleteOldSnapshotCommand(),
SyncMavenCommand(),
DeleteOldReleaseCommand(),
DeleteOldTagCommand()
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,18 @@ private suspend fun httpRequest(jsonString: String) =

private fun createRequestBody(bugsnagApiKey: String, appVersion: String, githubWorkflowUrl: String) =
BugSnagRequest(
apiKey = bugsnagApiKey,
appVersion = appVersion,
releaseStage = "production",
builderName = "github-actions",
sourceControl = githubActionsSourceControl(appVersion),
metadata = mapOf("github_actions_build_url" to githubWorkflowUrl)
apiKey = bugsnagApiKey,
appVersion = appVersion,
releaseStage = "production",
builderName = "github-actions",
sourceControl = githubActionsSourceControl(appVersion),
metadata = mapOf("github_actions_build_url" to githubWorkflowUrl)
).toJson()

private fun githubActionsSourceControl(appVersion: String) = SourceControl(
"github",
REPOSITORY,
appVersion
"github",
REPOSITORY,
appVersion
)

private const val BUGNSAG_URL = "https://build.bugsnag.com/"
Expand Down
30 changes: 19 additions & 11 deletions flank-scripts/src/test/kotlin/flank/scripts/FuelTestRunner.kt
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ class FuelTestRunner(klass: Class<*>) : BlockJUnit4ClassRunner(klass) {
url == "https://api.github.com/repos/Flank/flank/git/refs/tags/success" -> request.buildResponse("", 200)
url == "https://api.github.com/repos/flank/flank/releases/latest" && request.headers["Authorization"].contains("token success") -> request.buildResponse(GitHubRelease("v20.08.0").toJson(), 200)
url == "https://api.github.com/repos/flank/flank/commits/success/pulls" -> request.buildResponse(
Json.encodeToString(githubPullRequestTest), 200)
Json.encodeToString(githubPullRequestTest),
200
)
request.isFailedGithubRequest() -> request.buildResponse(githubErrorBody, 422)
url == "https://build.bugsnag.com/" -> request.handleBugsnagResponse()
else -> Response(request.url)
Expand All @@ -46,10 +48,15 @@ class FuelTestRunner(klass: Class<*>) : BlockJUnit4ClassRunner(klass) {
.startsWith("https://api.github.com/") && request.headers["Authorization"].contains("token failure"))

private fun Request.buildResponse(body: String, statusCode: Int) =
Response(url, statusCode = statusCode, responseMessage = body, body = DefaultBody(
{ body.byteInputStream() },
{ body.length.toLong() }
))
Response(
url,
statusCode = statusCode,
responseMessage = body,
body = DefaultBody(
{ body.byteInputStream() },
{ body.length.toLong() }
)
)

private fun Request.handleBugsnagResponse() =
if (body.asString("application/json").toObject<BugSnagRequest>().apiKey == "success") {
Expand All @@ -68,12 +75,13 @@ class FuelTestRunner(klass: Class<*>) : BlockJUnit4ClassRunner(klass) {
}
}

private val githubPullRequestTest = listOf(GithubPullRequest(
"www.pull.request",
"feat: new Feature",
5,
listOf()
)
private val githubPullRequestTest = listOf(
GithubPullRequest(
"www.pull.request",
"feat: new Feature",
5,
listOf()
)
)

private val githubErrorBody = """
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ class GenerateReleaseNotesCommandTest {

// when
val command = GenerateReleaseNotesCommand().apply {
main(listOf(
"--token=token",
"--release-notes-file=$expected")
main(
listOf(
"--token=token",
"--release-notes-file=$expected"
)
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ class DependencyExtensionsTest {
"1.0",
"name",
AvailableVersion(
"1.1", null, null
"1.1",
null,
null
)
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ class UpdateDependenciesTest {
// given
val copyOfTestVersions =
testVersions.copyTo(
File("src/test/kotlin/flank/scripts/dependencies/update/testfiles/VersionsAfterUpdateDependencies"))
File("src/test/kotlin/flank/scripts/dependencies/update/testfiles/VersionsAfterUpdateDependencies")
)
val expectedVersions =
File("src/test/kotlin/flank/scripts/dependencies/update/testfiles/ExpectedVersionAfterUpdateDependencies")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ class UpdateGradleTest {
File("src/test/kotlin/flank/scripts/dependencies/update/testfiles/expected_gradle-wrapper.properties.test")
val copyOfTestVersions =
testGradleVersionFile.copyTo(
File("src/test/kotlin/flank/scripts/dependencies/update/testfiles/gradle-wrapper.properties"))
File("src/test/kotlin/flank/scripts/dependencies/update/testfiles/gradle-wrapper.properties")
)

// when
testReport.updateGradle("src/test/kotlin/flank/scripts/dependencies/update/testfiles/")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ class UpdatePluginsTest {
File("src/test/kotlin/flank/scripts/dependencies/update/testfiles/ExpectedVersionAfterPluginDependencies")
val copyOfTestVersions =
testVersions.copyTo(
File("src/test/kotlin/flank/scripts/dependencies/update/testfiles/VersionsAfterPluginDependencies"))
File("src/test/kotlin/flank/scripts/dependencies/update/testfiles/VersionsAfterPluginDependencies")
)
prepareBuildGradleForTest()

// when
Expand Down
44 changes: 25 additions & 19 deletions test_runner/src/main/kotlin/ftl/args/ArgsHelper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,10 @@ object ArgsHelper {

fun assertCommonProps(args: IArgs) {
assertNotEmpty(
args.project, "The project is not set. Define GOOGLE_CLOUD_PROJECT, set project in flank.yml\n" +
"or save service account credential to ${defaultCredentialPath}\n" +
" See https://github.com/GoogleCloudPlatform/google-cloud-java#specifying-a-project-id"
args.project,
"The project is not set. Define GOOGLE_CLOUD_PROJECT, set project in flank.yml\n" +
"or save service account credential to ${defaultCredentialPath}\n" +
" See https://github.com/GoogleCloudPlatform/google-cloud-java#specifying-a-project-id"
)

if (args.maxTestShards !in AVAILABLE_PHYSICAL_SHARD_COUNT_RANGE && args.maxTestShards != -1)
Expand Down Expand Up @@ -159,11 +160,11 @@ object ArgsHelper {

try {
storage.create(
BucketInfo.newBuilder(bucket)
.setStorageClass(StorageClass.REGIONAL)
.setLocation(storageLocation)
.setLabels(bucketLabel)
.build()
BucketInfo.newBuilder(bucket)
.setStorageClass(StorageClass.REGIONAL)
.setLocation(storageLocation)
.setLabels(bucketLabel)
.build()
)
} catch (e: Exception) {
println("Warning: Failed to make bucket for $projectId\nCause: ${e.message}")
Expand All @@ -177,9 +178,9 @@ object ArgsHelper {
if (!defaultCredentialPath.toFile().exists()) return null

return JsonObjectParser(JSON_FACTORY).parseAndClose(
Files.newInputStream(defaultCredentialPath),
Charsets.UTF_8,
GenericJson::class.java
Files.newInputStream(defaultCredentialPath),
Charsets.UTF_8,
GenericJson::class.java
)["project_id"] as String
} catch (e: Exception) {
println("Parsing $defaultCredentialPath failed:")
Expand Down Expand Up @@ -231,22 +232,27 @@ object ArgsHelper {
}
val (ignoredTests, testsToExecute) = filteredTests.partition { it.ignored }
val shards = if (args.disableSharding) {
listOf(Chunk(testsToExecute.map {
TestMethod(
name = it.testName,
isParameterized = it.isParameterizedClass,
time = 0.0
listOf(
Chunk(
testsToExecute.map {
TestMethod(
name = it.testName,
isParameterized = it.isParameterizedClass,
time = 0.0
)
}
)
}))
)
} else {
val oldTestResult = GcStorage.downloadJunitXml(args) ?: JUnitTestResult(mutableListOf())
val shardCount = forcedShardCount ?: shardCountByTime(testsToExecute, oldTestResult, args)
createShardsByShardCount(testsToExecute, oldTestResult, args, shardCount).map { Chunk(it.testMethods) }
}

return CalculateShardsResult(
testMethodsAlwaysRun(shards, args),
ignoredTestCases = ignoredTests.map { it.testName })
testMethodsAlwaysRun(shards, args),
ignoredTestCases = ignoredTests.map { it.testName }
)
}

private fun testMethodsAlwaysRun(shards: List<Chunk>, args: IArgs): List<Chunk> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ abstract class CommonRunCommand {
@CommandLine.Option(
names = ["--obfuscate"],
description = ["Replacing internal test names with unique identifiers when using --dump-shards option " +
"to avoid exposing internal details"])
"to avoid exposing internal details"]
)
var obfuscate: Boolean = false
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class NetworkProfilesDescribeCommand : Runnable {
paramLabel = "PROFILE_ID",
defaultValue = "",
description = ["The network profile to describe, found" +
" using \$ gcloud beta firebase test network-profiles list."])
" using \$ gcloud beta firebase test network-profiles list."]
)
var profileId: String = ""
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,11 @@ internal fun AndroidInstrumentationTest.setupTestTargets(
}
uniformSharding = UniformSharding().setNumShards(safeNumUniformShards)
} else {
manualSharding = ManualSharding().setTestTargetsForShard(testShards.map {
TestTargetsForShard().setTestTargets(it)
})
manualSharding = ManualSharding().setTestTargetsForShard(
testShards.map {
TestTargetsForShard().setTestTargets(it)
}
)
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion test_runner/src/main/kotlin/ftl/ios/IosCatalog.kt
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ If this project has already been granted access, please make sure you are using
on the Blaze or Flame billing plans, and that you have run
gcloud config set billing/quota_project project
If you are still having issues, please email [email protected] for support.""", e
If you are still having issues, please email [email protected] for support.""",
e
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,13 @@ private fun TestExecutionData.reduceTestCases() = copy(
)

internal fun List<TestExecutionData>.removeStackTraces(): List<TestExecutionData> = map(TestExecutionData::removeStackTraces)
private fun TestExecutionData.removeStackTraces() = copy(testCases = testCases.onEach {
if (it.flaky) {
it.stackTraces = emptyList()
}
})
private fun TestExecutionData.removeStackTraces() = copy(
testCases = testCases.onEach {
if (it.flaky) {
it.stackTraces = emptyList()
}
}
)

// For primary step return stepId instead of primaryStepId
private val Step.primaryStepId get() = multiStep?.primaryStepId ?: stepId
Expand Down
41 changes: 25 additions & 16 deletions test_runner/src/main/kotlin/ftl/reports/util/ReportManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -106,26 +106,33 @@ object ReportManager {
HtmlErrorReport
).map { it.run(matrices, testSuite, printToStdout = false, args = args) }
}
JUnitReport.run(matrices, testSuite?.apply {
if (ignoredTestCases.isNotEmpty()) {
testsuites?.add(ignoredTestCases.toJunitTestsResults())
}
}, printToStdout = false, args = args)
JUnitReport.run(
matrices,
testSuite?.apply {
if (ignoredTestCases.isNotEmpty()) {
testsuites?.add(ignoredTestCases.toJunitTestsResults())
}
},
printToStdout = false,
args = args
)
when {
args.fullJUnitResult -> processFullJunitResult(args, matrices, testShardChunks)
args.useLegacyJUnitResult -> processJunitXml(testSuite, args, testShardChunks)
else -> processJunitXml(testSuite, args, testShardChunks)
}
}

private fun IgnoredTestCases.toJunitTestsResults() = getSkippedJUnitTestSuite(map {
JUnitTestCase(
classname = it.split("#").first().replace("class ", ""),
name = it.split("#").last(),
time = "0.0",
skipped = null
)
})
private fun IgnoredTestCases.toJunitTestsResults() = getSkippedJUnitTestSuite(
map {
JUnitTestCase(
classname = it.split("#").first().replace("class ", ""),
name = it.split("#").last(),
time = "0.0",
skipped = null
)
}
)

private fun processFullJunitResult(args: IArgs, matrices: MatrixMap, testShardChunks: ShardChunks) {
val testSuite = processXmlFromApi(matrices, args, withStackTraces = true)
Expand Down Expand Up @@ -171,9 +178,11 @@ object ReportManager {
) {
val list = createShardEfficiencyList(oldResult, newResult, args, testShardChunks)

println("Actual shard times:\n" + list.joinToString("\n") {
" ${it.shard}: Expected: ${it.expectedTime.roundToInt()}s, Actual: ${it.finalTime.roundToInt()}s, Diff: ${it.timeDiff.roundToInt()}s"
} + "\n")
println(
"Actual shard times:\n" + list.joinToString("\n") {
" ${it.shard}: Expected: ${it.expectedTime.roundToInt()}s, Actual: ${it.finalTime.roundToInt()}s, Diff: ${it.timeDiff.roundToInt()}s"
} + "\n"
)
}

private fun processJunitXml(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ private fun AndroidArgs.additionalApksContexts() = additionalAppTestApks.map {
app = (it.app ?: appApk)
?.asFileReference()
?: throw FlankGeneralError("Cannot create app-test apks pair for instrumentation tests, missing app apk for test ${it.test}"),
test = it.test.asFileReference(), environmentVariables = it.environmentVariables
test = it.test.asFileReference(),
environmentVariables = it.environmentVariables
)
}.toTypedArray()
Loading

0 comments on commit e5d7f5d

Please sign in to comment.