XCResultKit icon indicating copy to clipboard operation
XCResultKit copied to clipboard

Find out which individual lines are covered

Open alexanderwe opened this issue 2 years ago • 3 comments
trafficstars

Hey @davidahouse, I hope it's fine to ask a question in an issue.

I was just wondering if it's possible to find out if an individual line of a CodeCoverageFile has been covered by a test ? Or this this represented by the CodeCoverageFileFunction.lineNumber property ?

Thanks in advance !

alexanderwe avatar Jan 21 '23 11:01 alexanderwe

@alexanderwe Sure, always ok to ask questions here.

So currently this library doesn't get that level of detail. If you look at the way this code runs xccov, it uses the arguments --report and --json. For that output, we only get down to the function level in each file. For most purposes that should be far enough.

But if you wanted to get to the line level, you need to run the xccov command a different way. What you have to do is something like this:

xcrun xccov view --archive --file <FULL PATH TO THE FILE> <FULL PATH TO XCRESULT FILE>

This gives you an output with details on every single line of the file. That is likely only helpful if you are trying to build an IDE, or perhaps show a web version of the file with the covered/un-covered lines formatted somehow.

I suspect it wouldn't be hard to add this to the library, so we can keep this issue open for that if someone wants to tackle it.

davidahouse avatar Jan 22 '23 14:01 davidahouse

@davidahouse Thanks a lot for your answer and suggestion ! What you suggested works indeed. By calling that command I was able to get the code coverage on a per file level. It was necessary too because I needed to do a per file line coverage report. So again, thanks a lot for that :)

I am fine with keeping the issue open. I can try if I find some free time to incorporate what I implemented also here. I just don't know if I find the time soon.

alexanderwe avatar Jan 24 '23 15:01 alexanderwe

Here is a snippet of the code I've implemented for doing that and I will share with any future reader 👇

import Foundation
import ShellOut

typealias FilesCoverage = [String: [LineCoverage]]

struct LineCoverage: Decodable {
    let isExecutable: Bool
    let line: Int
    let executionCount: Int?
}

func extractXCResultXCCovArchive(XCResultPath: String) throws -> FilesCoverage {
    try shellOut(to: ["xcrun xccov view --archive --json \(XCResultPath) > temp_xcrun_xccov_archive.json"])
    let json = try shellOut(to: ["cat temp_xcrun_xccov_archive.json"])
    return try JSONDecoder().decode(FilesCoverage.self, from: json.data(using: .utf8)!)
}

Shellout is a simple library for executing command line code from swift.

Nikoloutsos avatar Aug 09 '24 23:08 Nikoloutsos