gopsutil icon indicating copy to clipboard operation
gopsutil copied to clipboard

HOST_PROC requires a mount point - hard to mock

Open mmetc opened this issue 3 years ago • 2 comments

Hi,

I'd like to use this library to detect running processes in an application. On said application I have functional tests. I want to fake the existence of some process. I don't care if this specific test must be skipped on freebsd/windows.

I thought I'd just set HOST_PROC and provide a few stub content in that directory, which works for listing Pids but fails the moment it checks if the process actually exists, since HOST_PROC must pass the isMount() check. Can we have an option or API to skip that?

Thanks

mmetc avatar May 16 '22 10:05 mmetc

For reference: this comes from #1051 to fix #1049. Not sure how we should handle that on our end.

Would a bind mount be OK for your test maybe?

Lomanic avatar May 16 '22 23:05 Lomanic

No, I don't want to require root to run tests. Something like this would work, on the other hand. I can set it with -X during build.

--- a/process/process_posix.go
+++ b/process/process_posix.go
@@ -75,11 +75,17 @@ func getTerminalMap() (map[uint64]string, error) {
 	return ret, nil
 }
 
+// Set this for testing, to use $HOST_PROC/proc when it's not mounted
+var skipMountCheck = ""
+
 // isMount is a port of python's os.path.ismount()
 // https://github.com/python/cpython/blob/08ff4369afca84587b1c82034af4e9f64caddbf2/Lib/posixpath.py#L186-L216
 // https://docs.python.org/3/library/os.path.html#os.path.ismount
 func isMount(path string) bool {
 	// Check symlinkness with os.Lstat; unix.DT_LNK is not portable
+	if skipMountCheck != "" {
+		return true
+	}
 	fileInfo, err := os.Lstat(path)
 	if err != nil {
 		return false

mmetc avatar May 17 '22 08:05 mmetc