Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix part of #5343: Implement script to run code coverage for a specific file #5433

Merged
merged 88 commits into from
Jun 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
88 commits
Select commit Hold shift + click to select a range
6ec35a7
Fix lint new line and kdoc checks
Rd4dev Jun 4, 2024
1ec224a
Execute Bazel Command to run coverage on the test target
Rd4dev Jun 5, 2024
ee92168
Parse the coverage execution result to acquire the generated coverage…
Rd4dev Jun 5, 2024
075c77c
Implemented functionality to TestBazelWorkspace utility to add source…
Rd4dev Jun 7, 2024
d0519d6
Sample Test data and Listing all contents
Rd4dev Jun 9, 2024
b15b7bb
Added Test for BazelClient - for sample target and non target executions
Rd4dev Jun 9, 2024
f441d11
Added Coverage Runner functionality tests
Rd4dev Jun 10, 2024
cc86309
Added tests for the RunCoverageForTestTarget utility
Rd4dev Jun 11, 2024
4a6073b
Replaced Java Test Sources with Kotlin Sources
Rd4dev Jun 13, 2024
13534a1
Fix Static Checks / Lint warnings
Rd4dev Jun 13, 2024
fc52d82
Fix Buildifier Lint checks
Rd4dev Jun 13, 2024
0226baa
Added tests for TestBazelWorkspaceTest to check addition of source an…
Rd4dev Jun 13, 2024
2fe7485
Fix Lint warnings with TestBazelWorkspaceTest
Rd4dev Jun 13, 2024
bd683b5
Fix Regex Pattern checks
Rd4dev Jun 13, 2024
d410d17
Prototyped parsing and reading the extracted file data as byte array
Rd4dev Jun 15, 2024
ece147a
Updated the runCoverageForTestTarget to parse the data file and read …
Rd4dev Jun 15, 2024
b101ec8
Updated Bazel Client Tests with updated execution to return byte array
Rd4dev Jun 15, 2024
5db0650
Updated BazelClientTest for ParseCoverageDataFile and readDatFileAsBi…
Rd4dev Jun 17, 2024
87be114
Updated CoverageRunnerTest to check with updated getCoverage result r…
Rd4dev Jun 17, 2024
456e81b
Updated RunCoverageForTestTargetTest to check the returned coverage data
Rd4dev Jun 17, 2024
2c65524
Update kdoc to match the function paramaters
Rd4dev Jun 17, 2024
62f9e1d
Removing suspend while keeping the async operations
Rd4dev Jun 17, 2024
5e6d2ef
Updated RunCoverageForTestTarget to take in custom process timeout as…
Rd4dev Jun 17, 2024
31b6401
Initialized bazelClient using lazy field
Rd4dev Jun 17, 2024
81d6855
Adjusted visibility and removed unnecessary documentation for private…
Rd4dev Jun 17, 2024
6cb1da7
Revoking visibility of bazelClient functions as that is called outsid…
Rd4dev Jun 17, 2024
b41fb01
Fix Lint Check issues
Rd4dev Jun 17, 2024
e66ac12
Merge branch 'develop' of https://github.com/Rd4dev/oppia-android int…
Rd4dev Jun 17, 2024
c646840
Merge branch 'develop' of https://github.com/Rd4dev/oppia-android int…
Rd4dev Jun 18, 2024
1ffc83d
Introduce new script RunCoverage.kt to later take in source filename …
Rd4dev Jun 18, 2024
248a20a
Merge branch 'develop' of https://github.com/Rd4dev/oppia-android int…
Rd4dev Jun 19, 2024
d817c85
Map file names to appropriate test and localTest names
Rd4dev Jun 19, 2024
7f1be37
Running Multiple test targets using hardcoded test target names
Rd4dev Jun 19, 2024
9e78d1a
Added Kdoc and processTimeout custom argument with basic clean up
Rd4dev Jun 19, 2024
cc5e981
Seperated logic as class and functions, introduced test file with set…
Rd4dev Jun 20, 2024
5075a1a
Added tests for findTestFile()
Rd4dev Jun 20, 2024
fdaf9cb
Added tests case for RunCoverage to check execution of coverage and f…
Rd4dev Jun 20, 2024
8e28f1d
Cleanup of RunCoverageTest
Rd4dev Jun 20, 2024
92bf266
Fix kdoc lint checks and TestBazelWorkspace Tests
Rd4dev Jun 20, 2024
eb7cdc2
Fix Lint Checks on indentation
Rd4dev Jun 20, 2024
ee078e2
Refactored BazelClient coverage execution to return data as list of s…
Rd4dev Jun 21, 2024
f15e087
Fix Lint checks
Rd4dev Jun 21, 2024
506916d
Removed ending periods in KDoc Strings
Rd4dev Jun 21, 2024
c68487d
Merge branch 'develop' of https://github.com/Rd4dev/oppia-android int…
Rd4dev Jun 21, 2024
0f5cffd
Resolved with conflicts to the code_coverage_bazel_command_execution …
Rd4dev Jun 21, 2024
87d34ad
Update the script to align with changes in BazelClient PR 1.1 to retu…
Rd4dev Jun 21, 2024
ba1c66a
Fix KDoc String punctuations, more clearer variable names and simplif…
Rd4dev Jun 22, 2024
438476c
Removed unused Paths import
Rd4dev Jun 22, 2024
ac30ca7
Merge branch 'develop' of https://github.com/Rd4dev/oppia-android int…
Rd4dev Jun 22, 2024
c7c2f2f
Fixed indentation and line spaces for better readability
Rd4dev Jun 22, 2024
1eac413
Merge branch 'code_coverage_bazel_command_execution' of https://githu…
Rd4dev Jun 22, 2024
6a2a029
For Reference: Multiple test cases with LocalTest and Test works but …
Rd4dev Jun 22, 2024
e4ede82
For Reference: Added package group for sharedTest and Test, yet multi…
Rd4dev Jun 22, 2024
9e0189d
Added implementation for script module test content files (to be refa…
Rd4dev Jun 22, 2024
d477d20
Refactored the addSourceAndTestFileWithContent to be suitable for mul…
Rd4dev Jun 22, 2024
6720de7
For Reference: Added App cases, but just having sharedTest in package…
Rd4dev Jun 22, 2024
04243f1
KDoC and reverting sharedTest to test, this passes test
Rd4dev Jun 22, 2024
985e861
For Reference: Even doing app/test fails with NPE
Rd4dev Jun 22, 2024
33f9a0b
Made findTestFile private and removed related tests
Rd4dev Jun 22, 2024
5229ecd
Used kotlin patterns to simplify the and make it more readable
Rd4dev Jun 22, 2024
d9ad634
Returning the coverageDataList as immutable list
Rd4dev Jun 22, 2024
ac4c82b
Fix Lint Checks
Rd4dev Jun 23, 2024
6eb90c7
Fixed Multi Level Source and Test File coverage execution by adding t…
Rd4dev Jun 23, 2024
68c714b
Fix Lint Check
Rd4dev Jun 23, 2024
e0be83a
Removed RunCoverageForTestTarget as it is redundant
Rd4dev Jun 23, 2024
c834aa7
Removed the RunCoverageForTestTarget as the functionality will be re-…
Rd4dev Jun 23, 2024
47a6197
Resolved merge conflicts with upstream code_coverage_bazel_command_ex…
Rd4dev Jun 23, 2024
c654eed
Removed the RunCoverageForTestTarget Build inclusions
Rd4dev Jun 23, 2024
3ab4e1e
Resolved merge conflict while syncing with upstream
Rd4dev Jun 23, 2024
0306258
Refactor execute to use separate helper functions
Rd4dev Jun 23, 2024
6179699
Used mapNotNull to avoid mutability
Rd4dev Jun 23, 2024
73f553d
Merge branch 'develop' into code_coverage_bazel_command_execution
BenHenning Jun 24, 2024
0f63469
Merge branch 'develop' into code_coverage_bazel_command_execution
BenHenning Jun 24, 2024
1b9426d
Fix instrumentation and throw error on invalid path
Rd4dev Jun 26, 2024
85b4bcd
Throw error on missing test files
Rd4dev Jun 26, 2024
356e4fb
Removed accidentally added coverage_reports folder
Rd4dev Jun 26, 2024
9734a84
Lint fix and Fix failing Test
Rd4dev Jun 26, 2024
f36eb83
Merge branch 'develop' of https://github.com/Rd4dev/oppia-android int…
Rd4dev Jun 26, 2024
6488d53
Merge branch 'code_coverage_bazel_command_execution' of https://githu…
Rd4dev Jun 26, 2024
6f4b76f
Merge branch 'code_coverage_bazel_command_execution' of https://githu…
Rd4dev Jun 26, 2024
7a020a1
Update the test file exemption list retrieval
Rd4dev Jun 26, 2024
d6c1f33
Changed mutable lists to lists
Rd4dev Jun 26, 2024
3b6b049
Removed print statement and refactored same package deps
Rd4dev Jun 26, 2024
d88edf6
Fixed improper dep assignment
Rd4dev Jun 26, 2024
9403d77
Fix Lint Checks
Rd4dev Jun 26, 2024
cce689a
Fix Buildifier lint check
Rd4dev Jun 26, 2024
fd0f035
Fix typos and update to print the file path to error message
Rd4dev Jun 26, 2024
34c9c8e
Merge branch 'develop' into code_coverage_using_filename
adhiamboperes Jun 26, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions scripts/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,16 @@ kt_jvm_binary(
],
)

kt_jvm_binary(
name = "run_coverage",
testonly = True,
data = TEST_FILE_EXEMPTION_ASSETS,
main_class = "org.oppia.android.scripts.coverage.RunCoverageKt",
runtime_deps = [
"//scripts/src/java/org/oppia/android/scripts/coverage:run_coverage_lib",
],
)

# Note that this is intentionally not test-only since it's used by the app build pipeline. Also,
# this apparently needs to be a java_binary to set up runfiles correctly when executed within a
# Starlark rule as a tool.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,9 +142,11 @@ class BazelClient(private val rootDirectory: File, private val commandExecutor:
* or null if the coverage data file could not be parsed
*/
fun runCoverageForTestTarget(bazelTestTarget: String): List<String>? {
val computeInstrumentation = bazelTestTarget.split("/").let { "//${it[2]}/..." }
val coverageCommandOutputLines = executeBazelCommand(
"coverage",
bazelTestTarget
bazelTestTarget,
"--instrumentation_filter=$computeInstrumentation"
)
return parseCoverageDataFilePath(coverageCommandOutputLines)?.let { path ->
File(path).readLines()
Expand Down
14 changes: 14 additions & 0 deletions scripts/src/java/org/oppia/android/scripts/coverage/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,20 @@ Libraries corresponding to developer scripts that obtain coverage data for test

load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kt_jvm_library")

kt_jvm_library(
name = "run_coverage_lib",
testonly = True,
srcs = [
"RunCoverage.kt",
],
visibility = ["//scripts:oppia_script_binary_visibility"],
deps = [
":coverage_runner",
"//scripts/src/java/org/oppia/android/scripts/common:bazel_client",
"//scripts/src/java/org/oppia/android/scripts/proto:script_exemptions_java_proto",
],
)

kt_jvm_library(
name = "coverage_runner",
testonly = True,
Expand Down
148 changes: 148 additions & 0 deletions scripts/src/java/org/oppia/android/scripts/coverage/RunCoverage.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
package org.oppia.android.scripts.coverage

import kotlinx.coroutines.runBlocking
import org.oppia.android.scripts.common.BazelClient
import org.oppia.android.scripts.common.CommandExecutor
import org.oppia.android.scripts.common.CommandExecutorImpl
import org.oppia.android.scripts.common.ScriptBackgroundCoroutineDispatcher
import org.oppia.android.scripts.proto.TestFileExemptions
import java.io.File
import java.util.concurrent.TimeUnit

/**
* Entry point function for running coverage analysis for a source file.
*
* Usage:
* bazel run //scripts:run_coverage_for_test_target -- <path_to_root> <relative_path_to_file>
*
* Arguments:
* - path_to_root: directory path to the root of the Oppia Android repository.
* - relative_path_to_file: the relative path to the file to analyse coverage
*
* Example:
* bazel run //scripts:run_coverage -- $(pwd)
* utility/src/main/java/org/oppia/android/util/parser/math/MathModel.kt
* Example with custom process timeout:
* bazel run //scripts:run_coverage -- $(pwd)
* utility/src/main/java/org/oppia/android/util/parser/math/MathModel.kt processTimeout=10
*
*/
fun main(vararg args: String) {
Rd4dev marked this conversation as resolved.
Show resolved Hide resolved
val repoRoot = args[0]
val filePath = args[1]

if (!File(repoRoot, filePath).exists()) {
error("File doesn't exist: $filePath.")
}

ScriptBackgroundCoroutineDispatcher().use { scriptBgDispatcher ->
val processTimeout: Long = args.find { it.startsWith("processTimeout=") }
?.substringAfter("=")
?.toLongOrNull() ?: 5

val commandExecutor: CommandExecutor = CommandExecutorImpl(
scriptBgDispatcher, processTimeout = processTimeout, processTimeoutUnit = TimeUnit.MINUTES
)

RunCoverage(repoRoot, filePath, commandExecutor, scriptBgDispatcher).execute()
}
}

/**
* Class responsible for executing coverage on a given file.
*
* @param repoRoot the root directory of the repository
* @param filePath the relative path to the file to analyse coverage
* @param commandExecutor executes the specified command in the specified working directory
* @param scriptBgDispatcher the [ScriptBackgroundCoroutineDispatcher] to be used for running the coverage command
*/
class RunCoverage(
private val repoRoot: String,
private val filePath: String,
private val commandExecutor: CommandExecutor,
private val scriptBgDispatcher: ScriptBackgroundCoroutineDispatcher
) {
private val bazelClient by lazy { BazelClient(File(repoRoot), commandExecutor) }

private val rootDirectory = File(repoRoot).absoluteFile
private val testFileExemptionTextProto = "scripts/assets/test_file_exemptions"

/**
* Executes coverage analysis for the specified file.
*
* Loads test file exemptions and checks if the specified file is exempted. If exempted,
* prints a message indicating no coverage analysis is performed. Otherwise, initializes
* a Bazel client, finds potential test file paths, retrieves Bazel targets, and initiates
* coverage analysis for each test target found.
*
* @return a list of lists containing coverage data for each requested test target, if
* the file is exempted from having a test file, an empty list is returned
*/
fun execute(): List<List<String>> {
val testFileExemptionList = loadTestFileExemptionsProto(testFileExemptionTextProto)
.testFileExemptionList
.filter { it.testFileNotRequired }
.map { it.exemptedFilePath }

if (filePath in testFileExemptionList) {
println("This file is exempted from having a test file; skipping coverage check.")
return emptyList()
}

val testFilePaths = findTestFile(repoRoot, filePath)
if (testFilePaths.isEmpty()) {
error("No appropriate test file found for $filePath")
}

val testTargets = bazelClient.retrieveBazelTargets(testFilePaths)

return testTargets.mapNotNull { testTarget ->
val coverageData = runCoverageForTarget(testTarget)
if (coverageData == null) {
println("Coverage data for $testTarget is null")
}
coverageData
}
}

private fun runCoverageForTarget(testTarget: String): List<String>? {
return runBlocking {
CoverageRunner(rootDirectory, scriptBgDispatcher, commandExecutor)
.runWithCoverageAsync(testTarget.removeSuffix(".kt"))
.await()
}
}
}

private fun findTestFile(repoRoot: String, filePath: String): List<String> {
val possibleTestFilePaths = when {
filePath.startsWith("scripts/") -> {
listOf(filePath.replace("/java/", "/javatests/").replace(".kt", "Test.kt"))
}
filePath.startsWith("app/") -> {
listOf(
filePath.replace("/main/", "/sharedTest/").replace(".kt", "Test.kt"),
filePath.replace("/main/", "/test/").replace(".kt", "Test.kt"),
filePath.replace("/main/", "/test/").replace(".kt", "LocalTest.kt")
)
}
else -> {
listOf(filePath.replace("/main/", "/test/").replace(".kt", "Test.kt"))
}
}

val repoRootFile = File(repoRoot).absoluteFile

return possibleTestFilePaths
.map { File(repoRootFile, it) }
.filter(File::exists)
.map { it.relativeTo(repoRootFile).path }
}

private fun loadTestFileExemptionsProto(testFileExemptiontextProto: String): TestFileExemptions {
return File("$testFileExemptiontextProto.pb").inputStream().use { stream ->
TestFileExemptions.newBuilder().also { builder ->
builder.mergeFrom(stream)
}.build()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,22 +57,22 @@ class TestBazelWorkspace(private val temporaryRootFolder: TemporaryFolder) {
* @param filename the name of the source file (without the .kt extension)
* @param sourceContent the content of the source file
* @param testContent the content of the test file
* @param subpackage the subpackage under which the source and test files should be added
* @param sourceSubpackage the subpackage under which the source files should be added
* @param testSubpackage the subpackage under which the test files should be added
*/
fun addSourceAndTestFileWithContent(
filename: String,
sourceContent: String,
testContent: String,
subpackage: String
sourceSubpackage: String,
testSubpackage: String
) {
val sourceSubpackage = "$subpackage/main/java/com/example"
addSourceContentAndBuildFile(
filename,
sourceContent,
sourceSubpackage
)

val testSubpackage = "$subpackage/test/java/com/example"
val testFileName = "${filename}Test"
addTestContentAndBuildFile(
filename,
Expand All @@ -83,6 +83,51 @@ class TestBazelWorkspace(private val temporaryRootFolder: TemporaryFolder) {
)
}

/**
* Adds a source file and 2 test files with the specified name and content,
* and updates the corresponding build configuration.
*
* @param filename the name of the source file (without the .kt extension)
* @param sourceContent the content of the source file
* @param testContentShared the content of the test file for SharedTest Package
* @param testContentLocal the content of the test file for Test Package
* @param subpackage the subpackage under which the source and test files should be added
*/
fun addMultiLevelSourceAndTestFileWithContent(
BenHenning marked this conversation as resolved.
Show resolved Hide resolved
filename: String,
sourceContent: String,
testContentShared: String,
testContentLocal: String,
subpackage: String
) {
val sourceSubpackage = "$subpackage/main/java/com/example"
addSourceContentAndBuildFile(
filename,
sourceContent,
sourceSubpackage
)

val testSubpackageShared = "$subpackage/sharedTest/java/com/example"
val testFileNameShared = "${filename}Test"
addTestContentAndBuildFile(
filename,
testFileNameShared,
testContentShared,
sourceSubpackage,
testSubpackageShared
)

val testSubpackageLocal = "$subpackage/test/java/com/example"
val testFileNameLocal = "${filename}LocalTest"
addTestContentAndBuildFile(
filename,
testFileNameLocal,
testContentLocal,
sourceSubpackage,
testSubpackageLocal
)
}

/**
* Adds a source file with the specified name and content to the specified subpackage,
* and updates the corresponding build configuration.
Expand Down Expand Up @@ -172,7 +217,7 @@ class TestBazelWorkspace(private val temporaryRootFolder: TemporaryFolder) {
testBuildFile.appendText(
"""
kt_jvm_test(
name = "test",
name = "$testName",
srcs = ["$testName.kt"],
deps = [
"//$sourceSubpackage:${filename.lowercase()}",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -424,10 +424,11 @@ class BazelClientTest {
filename = "TwoSum",
sourceContent = sourceContent,
testContent = testContent,
subpackage = "coverage"
sourceSubpackage = "coverage/main/java/com/example",
testSubpackage = "coverage/test/java/com/example"
)

val result = bazelClient.runCoverageForTestTarget("//coverage/test/java/com/example:test")
val result = bazelClient.runCoverageForTestTarget("//coverage/test/java/com/example:TwoSumTest")
val expectedResult = listOf(
"SF:coverage/main/java/com/example/TwoSum.kt",
"FN:7,com/example/TwoSum${'$'}Companion::sumNumbers (II)Ljava/lang/Object;",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,16 @@ kt_jvm_test(
"//third_party:org_jetbrains_kotlin_kotlin-test-junit",
],
)

kt_jvm_test(
name = "RunCoverageTest",
srcs = ["RunCoverageTest.kt"],
deps = [
"//scripts:test_file_check_assets",
"//scripts/src/java/org/oppia/android/scripts/coverage:run_coverage_lib",
"//scripts/src/java/org/oppia/android/scripts/testing:test_bazel_workspace",
"//testing:assertion_helpers",
"//third_party:com_google_truth_truth",
"//third_party:org_jetbrains_kotlin_kotlin-test-junit",
],
)
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class CoverageRunnerTest {
}

@Test
fun testRunCoverage_emptyDirectory_throwsException() {
fun testRunWithCoverageAsync_emptyDirectory_throwsException() {
val exception = assertThrows<IllegalStateException>() {
runBlocking {
coverageRunner.runWithCoverageAsync(bazelTestTarget).await()
Expand All @@ -48,7 +48,7 @@ class CoverageRunnerTest {
}

@Test
fun testRunCoverage_invalidTestTarget_throwsException() {
fun testRunWithCoverageAsync_invalidTestTarget_throwsException() {
testBazelWorkspace.initEmptyWorkspace()

val exception = assertThrows<IllegalStateException>() {
Expand All @@ -62,7 +62,7 @@ class CoverageRunnerTest {
}

@Test
fun testRunCoverage_validSampleTestTarget_returnsCoverageData() {
fun testRunWithCoverageAsync_validSampleTestTarget_returnsCoverageData() {
testBazelWorkspace.initEmptyWorkspace()

val sourceContent =
Expand Down Expand Up @@ -105,12 +105,13 @@ class CoverageRunnerTest {
filename = "TwoSum",
sourceContent = sourceContent,
testContent = testContent,
subpackage = "coverage"
sourceSubpackage = "coverage/main/java/com/example",
testSubpackage = "coverage/test/java/com/example"
)

val result = runBlocking {
coverageRunner.runWithCoverageAsync(
"//coverage/test/java/com/example:test"
"//coverage/test/java/com/example:TwoSumTest"
).await()
}
val expectedResult = listOf(
Expand Down
Loading
Loading