'Test that client killed messages are handled correctly.'

def testAlertEmailIsSentWhenClientKilled(self):

    self.email_messages = []
    def SendEmail(address, sender, title, message, **_):
        self.email_messages.append(dict(address=address, sender=sender, title=title, message=message))
    with utils.Stubber(email_alerts.EMAIL_ALERTER, 'SendEmail', SendEmail):
        client = flow_test_lib.CrashClientMock(self.client_id, self.token)
        for _ in flow_test_lib.TestFlowHelper(flow_test_lib.FlowWithOneClientRequest.__name__, client, client_id=self.client_id, token=self.token, check_flow_errors=False):
            pass
    self.assertEqual(len(self.email_messages), 1)
    email_message = self.email_messages[0]
    self.assertEqual(email_message.get('address', ''), config.CONFIG['Monitoring.alert_email'])
    self.assertTrue((str(self.client_id) in email_message['title']))
    for s in ['flow_name', flow_test_lib.FlowWithOneClientRequest.__name__, 'current_state']:
        self.assertTrue((s in email_message['message']))
    flow_obj = aff4.FACTORY.Open(client.flow_id, age=aff4.ALL_TIMES, token=self.token)
    self.assertEqual(flow_obj.context.state, rdf_flows.FlowContext.State.ERROR)
    client_obj = aff4.FACTORY.Open(self.client_id, token=self.token)
    crash = client_obj.Get(client_obj.Schema.LAST_CRASH)
    self.CheckCrash(crash, flow_obj.session_id)
    client_crashes = sorted(list(aff4_grr.VFSGRRClient.CrashCollectionForCID(self.client_id, token=self.token)), key=(lambda x: x.timestamp))
    self.assertTrue((len(client_crashes) >= 1))
    crash = list(client_crashes)[0]
    self.CheckCrash(crash, flow_obj.session_id)
    flow_crashes = sorted(list(flow_obj.GetValuesForAttribute(flow_obj.Schema.CLIENT_CRASH)), key=(lambda x: x.timestamp))
    self.assertEqual(len(flow_crashes), len(client_crashes))
    for (a, b) in zip(flow_crashes, client_crashes):
        self.assertEqual(a, b)
