TestML.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. from utils import transport
  2. from utils.ml import ML, AnomalyDetection, AnalyzeAnomaly
  3. import unittest
  4. import json
  5. import os
  6. path = os.environ['MONITOR_CONFIG_PATH']
  7. f = open(path)
  8. CONFIG = json.loads( f.read())
  9. f.close()
  10. factory = transport.DataSourceFactory()
  11. class TestML(unittest.TestCase):
  12. def setUp(self):
  13. ref = CONFIG['store']['class']['read']
  14. p = CONFIG['store']['args']
  15. p['qid'] = ['apps']
  16. self.greader = factory.instance(type=ref,args=p)
  17. def test_has_date(self):
  18. r = self.greader.read()
  19. self.assertTrue(r)
  20. def test_Filter(self):
  21. r = self.greader.read()
  22. r = r['apps']
  23. #
  24. # To make this test case extensible we need to pull apps from the configuration
  25. #
  26. app = CONFIG['monitor']['processes']['config']['apps'][0]
  27. x = ML.Filter('label',app,r)
  28. app = ML.CleanupName(app)
  29. for row in x:
  30. self.assertTrue(row['label'] == app)
  31. def test_Extract(self):
  32. r = self.greader.read()
  33. r = r['apps']
  34. app = CONFIG['monitor']['processes']['config']['apps'][0]
  35. x = ML.Filter('label',app,r)
  36. features = CONFIG['learner']['anomalies']['features']
  37. self.assertTrue(features)
  38. x_ = ML.Extract(features, x)
  39. self.assertTrue (len (x) == len(x_))
  40. pass
  41. def test_Learn(self):
  42. ref = CONFIG['store']['class']['read']
  43. p = CONFIG['store']['args']
  44. greader = factory.instance(type=ref,args=p)
  45. data = greader.read()
  46. data = data['apps']
  47. app = CONFIG['monitor']['processes']['config']['apps'][0]
  48. lhandler = AnomalyDetection()
  49. features = CONFIG['learner']['anomalies']['features']
  50. label = CONFIG['learner']['anomalies']['label']
  51. x = lhandler.learn(data,'label',app,features,label)
  52. def test_Predict(self):
  53. ref = CONFIG['store']['class']['read']
  54. p = CONFIG['store']['args']
  55. greader = factory.instance(type=ref,args=p)
  56. data = greader.read()
  57. if 'learn' in data :
  58. info = data['learn']
  59. app = CONFIG['monitor']['processes']['config']['apps'][0]
  60. lhandler = AnalyzeAnomaly()
  61. features = CONFIG['learner']['anomalies']['features']
  62. label = CONFIG['learner']['anomalies']['label']
  63. #x = lhandler.learn(data,'label',app,features,label)
  64. data = data['apps']
  65. xo = ML.Filter('label',app,data)
  66. info = ML.Filter('label',app,info)
  67. lhandler.predict(xo,info[0])
  68. if __name__ == '__main__' :
  69. unittest.main()