Files
xieyi-weixin-/test_wxwork_process_monitor.py
T
2026-09-21 10:56:48 +08:00

51 lines
2.6 KiB
Python

from wxwork_process_monitor import changes, summarize, atomic_json, append_events
import json
def test_pid_reuse_is_stop_and_start():
old={'processes':[{'pid':21,'createdAt':'old','name':'WXWork.exe'}]}
new={'processes':[{'pid':21,'createdAt':'new','name':'WXWork.exe'}]}
events=changes(old,new)
assert [e['type'] for e in events]==['process_stopped','process_started']
def test_unchanged_snapshot_produces_no_duplicate_events():
s={'processes':[{'pid':21,'createdAt':'t'}],'connections':[{'pid':21,'state':'LISTEN','localPort':9882}],'modules':[{'pid':21,'path':'C:/WeCom/test.dll'}]}
assert changes(s,s)==[]
def test_connection_state_change_is_recorded():
before={'connections':[{'pid':21,'state':'SYN_SENT','localPort':55}]}
after={'connections':[{'pid':21,'state':'ESTABLISHED','localPort':55}]}
assert [x['type'] for x in changes(before,after)]==['connection_gone','connection_observed']
def test_summary_distinguishes_presence_from_protocol_readiness():
s={'processes':[{'pid':11,'name':'WXWork.exe'},{'pid':12,'name':'wecom-agent.exe'},{'pid':13,'name':'wironboxd32.exe'}],'modules':[], 'errors':[], 'connections':[{'pid':11,'protocol':'tcp','state':'LISTEN','localAddress':'127.0.0.1','localPort':9882},{'pid':11,'protocol':'udp','state':'BOUND','localAddress':'0.0.0.0','localPort':5826}]}
report=summarize(s)
assert report['agents']==[12] and report['ironbox']==[13]
assert len(report['tcpListeners'])==1
assert 'canSend' not in report
def test_status_replace_and_bounded_event_log(tmp_path):
path=tmp_path/'status.json'
atomic_json(path,{'runId':'a'});atomic_json(path,{'runId':'b'})
assert json.loads(path.read_text())=={'runId':'b'}
assert not (tmp_path/'status.json.tmp').exists()
log=tmp_path/'events.jsonl';log.write_text('x'*(4*1024*1024+1))
append_events(log,[{'type':'process_started','item':{'pid':22}}])
assert log.with_suffix('.previous.jsonl').is_file()
assert json.loads(log.read_text())['item']['pid']==22
def test_status_write_survives_windows_reader_lock(tmp_path, monkeypatch):
import wxwork_process_monitor as m
real_replace=m.os.replace
attempts=[]
def locked_twice(source,target):
attempts.append(1)
if len(attempts)<3:
raise PermissionError('file open by reader')
real_replace(source,target)
monkeypatch.setattr(m.os,'replace',locked_twice)
monkeypatch.setattr(m.time,'sleep',lambda seconds:None)
m.atomic_json(tmp_path/'status.json',{'state':'running'})
assert len(attempts)==3
assert json.loads((tmp_path/'status.json').read_text())['state']=='running'
assert list(tmp_path.glob('*.tmp-*'))==[]