1// Copyright 2015 Keybase, Inc. All rights reserved. Use of
2// this source code is governed by the included BSD license.
3
4package lsof
5
6import (
7	"os"
8	"path/filepath"
9	"testing"
10)
11
12func TestParse(t *testing.T) {
13	s := `p10292
14cbash
15u501
16fcwd
17tDIR
18n/keybase/private/gabrielh,oconnor663
19p10561
20cvim
21u501
22fcwd
23tDIR
24n/keybase/private/gabrielh,oconnor663
25f4
26tREG
27n/keybase/private/gabrielh,oconnor663/.fun_times.swp
28`
29
30	processes, err := parse(s)
31	if err != nil {
32		t.Fatal(err)
33	}
34
35	if len(processes) != 2 {
36		t.Fatalf("Invalid processes: %#v", processes)
37	}
38
39	process1 := processes[0]
40	if process1.PID != "10292" || process1.Command != "bash" || process1.UserID != "501" {
41		t.Fatalf("Invalid process: %#v", process1)
42	}
43
44	process2 := processes[1]
45	if process2.PID != "10561" || process2.Command != "vim" || process2.UserID != "501" {
46		t.Fatalf("Invalid process: %#v", process2)
47	}
48	if len(process2.FileDescriptors) != 2 {
49		t.Fatalf("Invalid file descriptors: %#v", process2.FileDescriptors)
50	}
51	p2fd1 := process2.FileDescriptors[0]
52	if p2fd1.FD != "cwd" || p2fd1.Type != FileTypeDir || p2fd1.Name != "/keybase/private/gabrielh,oconnor663" {
53		t.Fatalf("Invalid file descriptor: %#v", p2fd1)
54	}
55	p2fd2 := process2.FileDescriptors[1]
56	if p2fd2.FD != "4" || p2fd2.Type != FileTypeFile || p2fd2.Name != "/keybase/private/gabrielh,oconnor663/.fun_times.swp" {
57		t.Fatalf("Invalid file descriptor: %#v", p2fd2)
58	}
59}
60
61func TestParseEmpty(t *testing.T) {
62	processes, err := parse("")
63	if err != nil {
64		t.Fatal(err)
65	}
66	if len(processes) != 0 {
67		t.Fatal("Failed parsing empty")
68	}
69}
70
71func TestParseSkipInvalidField(t *testing.T) {
72	s := `p10561
73cvim
74u501
75fcwd
76tDIR
77Binvalidfield`
78
79	processes, err := parse(s)
80	if err != nil {
81		t.Fatal(err)
82	}
83	if len(processes) != 1 {
84		t.Fatal("Failed parsing")
85	}
86}
87
88func TestInvalidDir(t *testing.T) {
89	invalidDir := filepath.Join(os.Getenv("HOME"), "invaliddir")
90	_, err := MountPoint(invalidDir)
91	t.Logf("Error: %#v", err)
92	if err == nil {
93		t.Fatal("Should have errored")
94	}
95}
96