<commit_before>import { expect } from 'chai';
import { describe, it } from 'mocha';
import schema from '../server/schema';
import { graphql } from 'graphql';

import * as utils from './utils';
import models from '../server/models';

describe.only('Query Tests', () => {
  let host, member, otherUser, group1, group2, group3, event1, event2, event3, tier1, tier2, tier3;

  /* SETUP
    group1: 2 events
      event1: 2 tiers
        tier1: 2 responses
        tier2: 1 response
      event2: 1 tier
        tier3: no response
    group2: 1 event
      event3: no tiers
    group3: no events
  */

  beforeEach(() => utils.resetTestDB());

  beforeEach(() => models.User.create(utils.data('user1')).tap(u => host = u));

  beforeEach(() => models.User.create(utils.data('user2')).tap(u => member = u));

  beforeEach(() => models.User.create(utils.data('user3')).tap(u => otherUser = u));

  beforeEach(() => models.Group.create(utils.data('group1')).tap(g => group1 = g));

  beforeEach(() => models.Group.create(utils.data('group2')).tap(g => group2 = g));

  beforeEach(() => models.Group.create(utils.data('group4')).tap(g => group3 = g));

  describe('Root query tests', () => {

    beforeEach(() => models.Event.create(
      Object.assign(utils.data('event1'), { CreatorId: member.id, GroupId: group1.id }))
      .tap(e => event1 = e));

    beforeEach(() => models.Event.create(
      Object.assign(utils.data('event2'), { CreatorId: member.id, GroupId: group1.id }))
      .tap(e => event2 = e));

    beforeEach(() => models.Event.create(
      Object.assign(utils.data('event2'), { CreatorId: host.id, GroupId: group2.id }))
      .tap(e => event2 = e));

    describe('throws an error', () => {

      it('when given only an existing event slug', async () => {
        const query = `
          query getOneEvent {
            getEvents(slug: "jan-meetup") {
              id,
              name,
              description
            }
          }
        `;
        const result = await graphql(schema, query);
        expect(result.errors.length).to.equal(1);
        expect(result.errors[0].message).to.equal('Field \"getEvents\" argument \"groupSlug\" of type \"String!\" is required but not provided.');
      })
    })

    describe('returns nothing', () => {

      it('when given a non-existent slug', async () => {
        const query = `
          query getOneEvent {
            getEvents(groupSlug: "non-existent-slug") {
              id,
              name,
              description
            }
          }
        `;
        const result = await graphql(schema, query);
        expect(result).to.deep.equal({
          data: {
            getEvents: []
          }
        });
      });

      it('when given an existing group slug when it has no events', async () => {
        const query = `
          query getOneEvent {
            getEvents(groupSlug: "meetups") {
              id,
              name,
              description
            }
          }
        `;
        const result = await graphql(schema, query);
        expect(result).to.deep.equal({
          data: {
            getEvents: []
          }
        });
      });
    });

    describe('returns event(s)', () => {

      it('when given an event slug and groupSlug', async () => {
        const query = `
          query getOneEvent {
            getEvents(groupSlug: "scouts", slug:"jan-meetup") {
              id,
              name,
              description
            }
          }
        `;
        const result = await graphql(schema, query);
        expect(result).to.deep.equal({
          data: {
            getEvents: [
              {
                description: "January monthly meetup",
                id: 1,
                name: "January meetup",
              }
            ]
          }
        });
      });

      describe('returns multiple events', () => {

        it('when given only a group slug', async () => {
          const query = `
            query getOneEvent {
              getEvents(groupSlug: "scouts") {
                id,
                name,
                description
              }
            }
          `;
          const result = await graphql(schema, query);
          expect(result).to.deep.equal({
            data: {
              getEvents: [
                {
                  description: "January monthly meetup",
                  id: 1,
                  name: "January meetup"
                },
                {
                  description: "February monthly meetup",
                  id: 2,
                  name: "Feb meetup"
                }
              ]
            }
          });
        });
      });

      describe('returns multiple events with associations', () => {

        beforeEach(() => models.Tier.create(
          Object.assign(utils.data('tier1'), { EventId: event1.id }))
          .tap(t => tier1 = t));

        beforeEach(() => models.Tier.create(
          Object.assign(utils.data('tier2'), { EventId: event1.id }))
          .tap(t => tier2 = t));

        beforeEach(() => models.Tier.create(
          Object.assign(utils.data('tier1'), { EventId: event2.id }))
          .tap(t => tier3 = t));

        beforeEach(() => models.Response.create(
          Object.assign(utils.data('response1'), {
            EventId: event1.id,
            TierId: tier1.id,
            GroupId: group1.id,
            UserId: host.id
          })));

        beforeEach(() => models.Response.create(
          Object.assign(utils.data('response2'), {
            EventId: event1.id,
            TierId: tier1.id,
            GroupId: group1.id,
            UserId: otherUser.id
          })));

        beforeEach(() => models.Response.create(
          Object.assign(utils.data('response3'), {
            EventId: event1.id,
            TierId: tier2.id,
            GroupId: group1.id,
            UserId: otherUser.id
          })));

        it('when given only a group slug', async () => {
          const query = `
            query getOneEvent {
              getEvents(groupSlug: "scouts") {
                id,
                name,
                description,
                createdBy {
                  id,
                  name
                }
                tiers {
                  id,
                  name,
                  description,
                  responses {
                    id,
                    status,
                    user {
                      id,
                      name
                    }
                  }
                }
              }
            }
          `;
          const result = await graphql(schema, query);
          console.log(result);
          expect(result).to.deep.equal({
            data: {
              getEvents: [
                {
                  description: "January monthly meetup",
                  id: 1,
                  name: "January meetup"
                },
                {
                  description: "February monthly meetup",
                  id: 2,
                  name: "Feb meetup"
                }
              ]
            }
          });
        });
      });
    });
  });
});
<commit_msg>update all tests<commit_after>import { expect } from 'chai';
import { describe, it } from 'mocha';
import schema from '../server/schema';
import { graphql } from 'graphql';

import * as utils from './utils';
import models from '../server/models';

describe('Query Tests', () => {
  let user1, user2, user3, group1, group2, group3, event1, event2, event3, tier1, tier2, tier3;

  /* SETUP
    group1: 2 events
      event1: 2 tiers
        tier1: 2 responses
        tier2: 1 response
      event2: 1 tier
        tier3: no response
    group2: 1 event
      event3: no tiers
    group3: no events
  */

  beforeEach(() => utils.resetTestDB());

  beforeEach(() => models.User.create(utils.data('user1')).tap(u => user1 = u));

  beforeEach(() => models.User.create(utils.data('user2')).tap(u => user2 = u));

  beforeEach(() => models.User.create(utils.data('user3')).tap(u => user3 = u));

  beforeEach(() => models.Group.create(utils.data('group1')).tap(g => group1 = g));

  beforeEach(() => models.Group.create(utils.data('group2')).tap(g => group2 = g));

  beforeEach(() => models.Group.create(utils.data('group4')).tap(g => group3 = g));

  describe('Root query tests', () => {

    beforeEach(() => models.Event.create(
      Object.assign(utils.data('event1'), { createdById: user1.id, GroupId: group1.id }))
      .tap(e => event1 = e));

    beforeEach(() => models.Event.create(
      Object.assign(utils.data('event2'), { createdById: user1.id, GroupId: group1.id }))
      .tap(e => event2 = e));

    beforeEach(() => models.Event.create(
      Object.assign(utils.data('event2'), { createdById: user2.id, GroupId: group2.id }))
      .tap(e => event2 = e));

    describe('throws an error', () => {

      it('when given only an existing event slug', async () => {
        const query = `
          query getOneEvent {
            getEvents(slug: "jan-meetup") {
              id,
              name,
              description
            }
          }
        `;
        const result = await graphql(schema, query);
        expect(result.errors.length).to.equal(1);
        expect(result.errors[0].message).to.equal('Field \"getEvents\" argument \"groupSlug\" of type \"String!\" is required but not provided.');
      })
    })

    describe('returns nothing', () => {

      it('when given a non-existent slug', async () => {
        const query = `
          query getOneEvent {
            getEvents(groupSlug: "non-existent-slug") {
              id,
              name,
              description
            }
          }
        `;
        const result = await graphql(schema, query);
        expect(result).to.deep.equal({
          data: {
            getEvents: []
          }
        });
      });

      it('when given an existing group slug when it has no events', async () => {
        const query = `
          query getOneEvent {
            getEvents(groupSlug: "meetups") {
              id,
              name,
              description
            }
          }
        `;
        const result = await graphql(schema, query);
        expect(result).to.deep.equal({
          data: {
            getEvents: []
          }
        });
      });
    });

    describe('returns event(s)', () => {

      it('when given an event slug and groupSlug', async () => {
        const query = `
          query getOneEvent {
            getEvents(groupSlug: "scouts", slug:"jan-meetup") {
              id,
              name,
              description
            }
          }
        `;
        const result = await graphql(schema, query);
        expect(result).to.deep.equal({
          data: {
            getEvents: [
              {
                description: "January monthly meetup",
                id: 1,
                name: "January meetup",
              }
            ]
          }
        });
      });

      describe('returns multiple events', () => {

        it('when given only a group slug', async () => {
          const query = `
            query getOneEvent {
              getEvents(groupSlug: "scouts") {
                id,
                name,
                description
              }
            }
          `;
          const result = await graphql(schema, query);
          expect(result).to.deep.equal({
            data: {
              getEvents: [
                {
                  description: "January monthly meetup",
                  id: 1,
                  name: "January meetup"
                },
                {
                  description: "February monthly meetup",
                  id: 2,
                  name: "Feb meetup"
                }
              ]
            }
          });
        });
      });

      describe('returns multiple events with associations', () => {

        beforeEach(() => models.Tier.create(
          Object.assign(utils.data('tier1'), { EventId: event1.id }))
          .tap(t => tier1 = t));

        beforeEach(() => models.Tier.create(
          Object.assign(utils.data('tier2'), { EventId: event1.id }))
          .tap(t => tier2 = t));

        beforeEach(() => models.Tier.create(
          Object.assign(utils.data('tier1'), { EventId: event2.id }))
          .tap(t => tier3 = t));

        beforeEach(() => models.Response.create(
          Object.assign(utils.data('response1'), {
            EventId: event1.id,
            TierId: tier1.id,
            GroupId: group1.id,
            UserId: user2.id
          })));

        beforeEach(() => models.Response.create(
          Object.assign(utils.data('response2'), {
            EventId: event1.id,
            TierId: tier1.id,
            GroupId: group1.id,
            UserId: user3.id
          })));

        beforeEach(() => models.Response.create(
          Object.assign(utils.data('response3'), {
            EventId: event1.id,
            TierId: tier2.id,
            GroupId: group1.id,
            UserId: user3.id
          })));

        it('when given only a group slug', async () => {
          const query = `
            query getOneEvent {
              getEvents(groupSlug: "scouts") {
                id,
                name,
                description,
                createdBy {
                  id,
                  name
                }
                tiers {
                  id,
                  name,
                  description,
                  responses {
                    id,
                    status,
                    user {
                      id,
                      name
                    }
                  }
                }
              }
            }
          `;
          const result = await graphql(schema, query);
          expect(result).to.deep.equal({
            data: {
              getEvents: [
                {
                  id: 1,
                  name: "January meetup",
                  "description":"January monthly meetup",
                  "createdBy": {
                    "id":1,
                    "name":"Phil Mod"
                  },
                  "tiers": [
                    {
                      "id":1,
                      "name":"Free tier",
                      "description":"free tickets for all",
                      "responses": [
                        {
                          "id":1,
                          "status":"INTERESTED",
                          "user": {
                            "id":2,
                            "name":
                            "Anish Bas"
                          }
                        },
                        {
                          "id":2,
                          "status":"YES",
                          "user": {
                            "id":3,
                            "name":"Xavier Damman"
                          }
                        }
                      ]
                    },
                    {
                      "id":2,
                      "name":"paid tier",
                      "description":"$20 ticket",
                      "responses": [
                        {
                          "id":3,
                          "status":"NO",
                          "user": {
                            "id":3,
                            "name":"Xavier Damman"
                          }
                        }
                      ]
                    }
                  ]
                },
                {
                  "id":2,
                  "name":"Feb meetup",
                  "description":"February monthly meetup",
                  "createdBy": {
                    "id":1,
                    "name":"Phil Mod"
                  },
                  "tiers":[]
                }
              ]
            }
          });
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>var expect = require('chai').expect;
const assert = require('chai').assert;
const _ = require('lodash');
var mother = require('../health_modules/mother/motherProgramEncounterDecision');
const ProgramEncounter = require("./Entities").ProgramEncounter;
const ProgramEnrolment = require("./Entities").ProgramEnrolment;
const C = require('../health_modules/common');
const concepts = require('./Concepts');

describe('High Risk Pregnancy Determination', () => {
    let enrolment, programEncounter, referenceDate;

    beforeEach(() => {
        referenceDate = new Date(2017, 6, 6);
        programEncounter = new ProgramEncounter("ANC", referenceDate);
        enrolment = new ProgramEnrolment('Mother', [programEncounter]);
        programEncounter.programEnrolment = enrolment;
    });

    describe("Less than 20 weeks of pregnancy", () => {
        let systolicConcept, diastolicConcept;

        beforeEach(() => {
            enrolment.setObservation('Last Menstrual Period', new Date(2017, 5, 10));
            systolicConcept = concepts['Systolic'];
            diastolicConcept = concepts['Diastolic'];
        });

        describe('Chronic Hypertension', () => {

            it("Should not mark Chronic Hypertension as if BP is normal", () => {
                enrolment.setObservation(systolicConcept.name, systolicConcept.highNormal - 1)
                    .setObservation(diastolicConcept.name, diastolicConcept.highNormal - 1);
                const decisions = mother.getDecisions(programEncounter, referenceDate).encounterDecisions;
                const complications = C.findValue(decisions, "High Risk Conditions");
                expect(complications).to.not.exist;
            });

            it("Should mark Chronic Hypertension as High Risk If Systolic is abnormal high", () => {
                enrolment.setObservation(systolicConcept.name, systolicConcept.highNormal + 1)
                    .setObservation(diastolicConcept.name, diastolicConcept.highNormal - 1);
                const decisions = mother.getDecisions(programEncounter, referenceDate).encounterDecisions;
                const complications = C.findValue(decisions, "High Risk Conditions");
                expect(complications).to.exist;
                expect(complications).to.be.an('array').that.includes('Chronic Hypertension');
            });

            it("Should mark Chronic Hypertension as High Risk If Diastolic is abnormal high", () => {
                enrolment.setObservation(systolicConcept.name, systolicConcept.highNormal - 1)
                    .setObservation(diastolicConcept.name, diastolicConcept.highNormal + 1);
                const decisions = mother.getDecisions(programEncounter, referenceDate).encounterDecisions;
                const complications = C.findValue(decisions, "High Risk Conditions");
                expect(complications).to.exist;
                expect(complications).to.be.an('array').that.includes('Chronic Hypertension');
            });

            it("Should mark Chronic Hypertension as High Risk If Diastolic and Systolic is abnormal high", () => {
                enrolment.setObservation(systolicConcept.name, systolicConcept.highNormal + 1)
                    .setObservation(diastolicConcept.name, diastolicConcept.highNormal + 1);
                const decisions = mother.getDecisions(programEncounter, referenceDate).encounterDecisions;
                const complications = C.findValue(decisions, "High Risk Conditions");
                expect(complications).to.exist;
                expect(complications).to.be.an('array').that.includes('Chronic Hypertension');
            });
        });

        describe("Chronic Hypertension with Superimposed Pre-Eclampsia", () => {
            let urineAlbumin;

            beforeEach(() => {
                urineAlbumin = concepts['Urine Albumin'];
            });

            it('Should not mark superimposed pre-eclampsia and Hypertension with Absent Urine Albumin and normal BP', () => {
                enrolment.setObservation(systolicConcept.name, systolicConcept.highNormal - 1)
                    .setObservation(diastolicConcept.name, diastolicConcept.highNormal - 1)
                    .setObservation(urineAlbumin.name, "Absent");
                const decisions = mother.getDecisions(programEncounter, referenceDate).encounterDecisions;
                const complications = C.findValue(decisions, 'High Risk Conditions');
                expect(complications).to.be.null;
            });

            it('Should not mark superimposed pre-eclampsia and Hypertension with Absent Urine Albumin', () => {
                enrolment.setObservation(systolicConcept.name, systolicConcept.highNormal + 1)
                    .setObservation(diastolicConcept.name, diastolicConcept.highNormal - 1)
                    .setObservation(urineAlbumin.name, "Absent");
                const decisions = mother.getDecisions(programEncounter, referenceDate).encounterDecisions;
                const complications = C.findValue(decisions, 'High Risk Conditions');
                expect(complications).to.exist;
                expect(complications).to.be.an('array').to.not.include('Chronic Hypertension with Superimposed Pre-Eclampsia');
            });

            describe('Presence of Urine Albumin', () => {
                beforeEach(() => {
                    enrolment.setObservation(systolicConcept.name, systolicConcept.highNormal - 1)
                        .setObservation(diastolicConcept.name, diastolicConcept.highNormal + 1);

                });

                afterEach(() => {
                    const decisions = mother.getDecisions(programEncounter, referenceDate).encounterDecisions;
                    const complications = C.findValue(decisions, 'High Risk Conditions');
                    expect(complications).to.exist;
                    expect(complications).to.be.an('array').that.includes('Chronic Hypertension with Superimposed Pre-Eclampsia');
                });

                it('Should mark superimposed pre-eclampsia with Trace Urine Albumin ', () => {
                    enrolment.setObservation("Urine Albumin", 'Trace');
                });

                it('Should mark superimposed pre-eclampsia with +1 Urine Albumin ', () => {
                    enrolment.setObservation("Urine Albumin", '+1');
                });

                it('Should mark superimposed pre-eclampsia with +2 Urine Albumin ', () => {
                    enrolment.setObservation("Urine Albumin", '+2');
                });

                it('Should mark superimposed pre-eclampsia with +3 Urine Albumin ', () => {
                    enrolment.setObservation("Urine Albumin", '+3');
                });

                it('Should mark superimposed pre-eclampsia with +4 Urine Albumin ', () => {
                    enrolment.setObservation("Urine Albumin", '+4');
                });

            });
        });

    });

    it('Check for Anemia based on Hb result', () => {
        programEncounter.setObservation("Hb", 4).setObservation("Systolic", 150).setObservation("Diastolic", 90);
        var decisions = mother.getDecisions(programEncounter, referenceDate).encounterDecisions;
        var complicationValues = C.findValue(decisions, 'High Risk Conditions');
        expect(complicationValues.indexOf("Severe Anemia")).is.not.equal(-1);
    });

    it('no high risk condition', () => {
        var decisions = mother.getDecisions(programEncounter, new Date(2017, 2, 10)).encounterDecisions;
        var complicationValues = C.findValue(decisions, 'High Risk Conditions');
        expect(complicationValues).is.equal(null);
    });

});
<commit_msg>ADding another level of heirarchy<commit_after>var expect = require('chai').expect;
const assert = require('chai').assert;
const _ = require('lodash');
var mother = require('../health_modules/mother/motherProgramEncounterDecision');
const ProgramEncounter = require("./Entities").ProgramEncounter;
const ProgramEnrolment = require("./Entities").ProgramEnrolment;
const C = require('../health_modules/common');
const concepts = require('./Concepts');

describe('High Risk Pregnancy Determination', () => {
    let enrolment, programEncounter, referenceDate;

    beforeEach(() => {
        referenceDate = new Date(2017, 6, 6);
        programEncounter = new ProgramEncounter("ANC", referenceDate);
        enrolment = new ProgramEnrolment('Mother', [programEncounter]);
        programEncounter.programEnrolment = enrolment;
    });

    describe("Less than 20 weeks of pregnancy", () => {
        let systolicConcept, diastolicConcept;

        beforeEach(() => {
            enrolment.setObservation('Last Menstrual Period', new Date(2017, 5, 10));
            systolicConcept = concepts['Systolic'];
            diastolicConcept = concepts['Diastolic'];
        });

        describe('Chronic Hypertension', () => {

            it("Should not mark Chronic Hypertension as if BP is normal", () => {
                enrolment.setObservation(systolicConcept.name, systolicConcept.highNormal - 1)
                    .setObservation(diastolicConcept.name, diastolicConcept.highNormal - 1);
                const decisions = mother.getDecisions(programEncounter, referenceDate).encounterDecisions;
                const complications = C.findValue(decisions, "High Risk Conditions");
                expect(complications).to.not.exist;
            });

            it("Should mark Chronic Hypertension as High Risk If Systolic is abnormal high", () => {
                enrolment.setObservation(systolicConcept.name, systolicConcept.highNormal + 1)
                    .setObservation(diastolicConcept.name, diastolicConcept.highNormal - 1);
                const decisions = mother.getDecisions(programEncounter, referenceDate).encounterDecisions;
                const complications = C.findValue(decisions, "High Risk Conditions");
                expect(complications).to.exist;
                expect(complications).to.be.an('array').that.includes('Chronic Hypertension');
            });

            it("Should mark Chronic Hypertension as High Risk If Diastolic is abnormal high", () => {
                enrolment.setObservation(systolicConcept.name, systolicConcept.highNormal - 1)
                    .setObservation(diastolicConcept.name, diastolicConcept.highNormal + 1);
                const decisions = mother.getDecisions(programEncounter, referenceDate).encounterDecisions;
                const complications = C.findValue(decisions, "High Risk Conditions");
                expect(complications).to.exist;
                expect(complications).to.be.an('array').that.includes('Chronic Hypertension');
            });

            it("Should mark Chronic Hypertension as High Risk If Diastolic and Systolic is abnormal high", () => {
                enrolment.setObservation(systolicConcept.name, systolicConcept.highNormal + 1)
                    .setObservation(diastolicConcept.name, diastolicConcept.highNormal + 1);
                const decisions = mother.getDecisions(programEncounter, referenceDate).encounterDecisions;
                const complications = C.findValue(decisions, "High Risk Conditions");
                expect(complications).to.exist;
                expect(complications).to.be.an('array').that.includes('Chronic Hypertension');
            });
        });

        describe("Chronic Hypertension with Superimposed Pre-Eclampsia", () => {
            let urineAlbumin;

            beforeEach(() => {
                urineAlbumin = concepts['Urine Albumin'];
            });

            describe('Absence of Urine Albumin', () => {
                beforeEach(() => {
                    enrolment.setObservation(systolicConcept.name, systolicConcept.highNormal - 1)
                        .setObservation(diastolicConcept.name, diastolicConcept.highNormal - 1)
                        .setObservation(urineAlbumin.name, "Absent");

                });

                it('Should not mark superimposed pre-eclampsia and Hypertension with Absent Urine Albumin and normal BP', () => {
                    const decisions = mother.getDecisions(programEncounter, referenceDate).encounterDecisions;
                    const complications = C.findValue(decisions, 'High Risk Conditions');
                    expect(complications).to.be.null;
                });

                it('Should not mark superimposed pre-eclampsia and Hypertension with Absent Urine Albumin', () => {
                    enrolment.setObservation(diastolicConcept.name, diastolicConcept.highNormal + 1);
                    const decisions = mother.getDecisions(programEncounter, referenceDate).encounterDecisions;
                    const complications = C.findValue(decisions, 'High Risk Conditions');
                    expect(complications).to.exist;
                    expect(complications).to.be.an('array').to.not.include('Chronic Hypertension with Superimposed Pre-Eclampsia');
                });

            });

            describe('Presence of Urine Albumin', () => {
                beforeEach(() => {
                    enrolment.setObservation(systolicConcept.name, systolicConcept.highNormal - 1)
                        .setObservation(diastolicConcept.name, diastolicConcept.highNormal + 1);

                });

                afterEach(() => {
                    const decisions = mother.getDecisions(programEncounter, referenceDate).encounterDecisions;
                    const complications = C.findValue(decisions, 'High Risk Conditions');
                    expect(complications).to.exist;
                    expect(complications).to.be.an('array').that.includes('Chronic Hypertension with Superimposed Pre-Eclampsia');
                });

                it('Should mark superimposed pre-eclampsia with Trace Urine Albumin ', () => {
                    enrolment.setObservation("Urine Albumin", 'Trace');
                });

                it('Should mark superimposed pre-eclampsia with +1 Urine Albumin ', () => {
                    enrolment.setObservation("Urine Albumin", '+1');
                });

                it('Should mark superimposed pre-eclampsia with +2 Urine Albumin ', () => {
                    enrolment.setObservation("Urine Albumin", '+2');
                });

                it('Should mark superimposed pre-eclampsia with +3 Urine Albumin ', () => {
                    enrolment.setObservation("Urine Albumin", '+3');
                });

                it('Should mark superimposed pre-eclampsia with +4 Urine Albumin ', () => {
                    enrolment.setObservation("Urine Albumin", '+4');
                });

            });
        });

    });

    it('Check for Anemia based on Hb result', () => {
        programEncounter.setObservation("Hb", 4).setObservation("Systolic", 150).setObservation("Diastolic", 90);
        var decisions = mother.getDecisions(programEncounter, referenceDate).encounterDecisions;
        var complicationValues = C.findValue(decisions, 'High Risk Conditions');
        expect(complicationValues.indexOf("Severe Anemia")).is.not.equal(-1);
    });

    it('no high risk condition', () => {
        var decisions = mother.getDecisions(programEncounter, new Date(2017, 2, 10)).encounterDecisions;
        var complicationValues = C.findValue(decisions, 'High Risk Conditions');
        expect(complicationValues).is.equal(null);
    });

});
<|endoftext|>


<commit_before>import React from "react";
import FinalizedHeader from "../Sidebars/FinalizedHeader";
import "../../styles/TimeLine.css";
import { travelObjectStartDateComparator } from "../../scripts/HelperFunctions";
import { getEmptySlots, handleClickedTimePoint } from "./HandleClickedTimePoint";
import { sameDate } from "../../scripts/HelperFunctions";
import OneHourInterval from "./OneHourInterval";
import { Grid } from "@material-ui/core"
import TravelObject from "../TravelObjects/TravelObject"

export default class TimeLine extends React.Component {
  constructor(props) {
    super(props);
    this.date2Items = new Map();
    this.emptySlots = [];
    this.displayItems = [];
    this.displayItemsExcludeHotel = [];
    this.startOfDisplayDate = new Date(
      this.props.displayDate.getFullYear(),
      this.props.displayDate.getMonth(),
      this.props.displayDate.getDate(),
      0,
      0,
      0
    );
    this.endOfDisplayDate = new Date(
      this.props.displayDate.getFullYear(),
      this.props.displayDate.getMonth(),
      this.props.displayDate.getDate(),
      23,
      59,
      59
    );
    this.handleOnClickInterval = this.handleOnClickInterval.bind(this);
  }

  componentDidUpdate(prevProps) {
    if (prevProps.displayDate.toDateString() !== this.props.displayDate.toDateString) {
      this.setState()
    }
  }

  /*Given a date and an item, put the item to the list of items belonging to the given date. */
  addItemToDate(item, dateKey) {
    if (!this.date2Items.has(dateKey)) {
      this.date2Items.set(dateKey, [item]);
    } else {
      let items = this.date2Items.get(dateKey);
      items.push(item);
    }
  }

  /*Given a list of items (props.list), split the items into the its dates */
  separateDates() {
    for (let i = 0; i < this.props.list.length; i++) {
      let item = this.props.list[i];
      let startDate = item.startDate;
      let endDate = item.endDate;
      this.addItemToDate(item, startDate.toDateString());

      if (!sameDate(startDate, endDate)) {
        this.addItemToDate(item, endDate.toDateString());
      }
    }
  }

  handleOnClickInterval(idV) {
    idV = idV.length < 5 ? "0" + idV : idV;

    return handleClickedTimePoint(idV, this.startOfDisplayDate, this.endOfDisplayDate, this.displayItemsExcludeHotel, this.emptySlots)
  }

  /* Handling rendering starts HERE */
  getIntervals() {
    let intervals = [];
    if (this.props.displayDate !== undefined) {
      this.date2Items = new Map();
      this.displayItems = [];
      this.emptySlots = [];
      this.separateDates();
      this.displayItems = this.date2Items.has(
        this.props.displayDate.toDateString()
      )
        ? this.date2Items.get(this.props.displayDate.toDateString())
        : [];
      this.props.setTodaysEvents(
        this.displayItems,
        this.props.displayDate.toDateString()
      );

      this.displayItems.sort(travelObjectStartDateComparator);
      this.displayItemsExcludeHotel = this.displayItems.filter((item) => item.type !== "hotel");

      this.emptySlots = getEmptySlots(this.startOfDisplayDate, this.endOfDisplayDate, this.displayItemsExcludeHotel)

      var nextItemIndex = 0;
      var hotel = null; // flags hotel until finds right place to palce in timeline

      for (var i = 0; i < 24; i++) {
        // if there are still travel objects that haven't been rendered
        if (hotel || nextItemIndex < this.displayItems.length) {
          // End date within current display date for catching checkout time for flight
          // Renders interval from midnight until arrival time
          var nextItem = this.displayItems[nextItemIndex];
          if (nextItem !== undefined && (!sameDate(this.props.displayDate, nextItem.startDate) && nextItem.type === "flight")) {
            intervals.push(
              <OneHourInterval
                idV={
                  nextItem.type === "hotel" ? nextItem.endDate.getHours() : 0
                }
                items={[{ data: nextItem, div: ":00" }]}
                zIndex={nextItemIndex}
                displayDate={this.props.displayDate}
                onRemoveItem={this.props.onRemoveItem}
                onEditItem={this.props.onEditItem}
                onAddItem={this.props.onAddItem}
                onClickObject={this.props.onClickObject}
                onClickInterval={this.handleOnClickInterval}
                onClickTimeslot={this.props.onClickTimeslot}
                onOpenSuggestions={this.props.onOpenSuggestions}
                startDate={this.props.startDate}
              />
            );
          } else {
            var items = [];
            var div = null;

            var item = this.displayItems[nextItemIndex];

            // found hotel who's checkout time isn't in the current hour block --> flags it and moves index
            if (!hotel && item.type === "hotel" && !sameDate(item.startDate, this.props.displayDate) && item.endDate.getHours() !== i) {
              hotel = item;
              item = this.displayItems[++nextItemIndex];
            }

            if (hotel && this.displayItems.length === 1) {
              if (hotel.endDate.getHours() === i) {
                items.push({ data: hotel, div: hotel.endDate.getMinutes() < 30 ? ":00" : ":30"})
              }
            } else {
              // loops through all travelobjects within this one hour period
              while (
                (nextItemIndex < this.displayItems.length &&
                  this.displayItems[nextItemIndex].startDate.getHours() === i) || (hotel && hotel.endDate.getHours() === i)
              ) {
                // found proper location for previously flagged hotel.
                if (hotel && hotel.endDate.getHours() === i) {
                  item = hotel;
                  hotel = null;
                } else {
                  nextItemIndex++;
                }

                let nextItemStartDate = item.startDate;
                var nextItemMinutes = nextItemStartDate.getMinutes();

                if (nextItemMinutes < 30) {
                  div = ":00";
                } else {
                  div = ":30";
                }

                items.push({ data: item, div: div });
                item = this.displayItems[nextItemIndex];
              }
            }

            intervals.push(
              <OneHourInterval
                idV={i.toString()}
                items={items.length === 0 ? null : items}
                zIndex={nextItemIndex}
                displayDate={this.props.displayDate}
                onRemoveItem={this.props.onRemoveItem}
                onEditItem={this.props.onEditItem}
                onAddItem={this.props.onAddItem}
                onClickObject={this.props.onClickObject}
                onClickInterval={this.handleOnClickInterval}
                onClickTimeslot={this.props.onClickTimeslot}
                onOpenSuggestions={this.props.onOpenSuggestions}
                startDate={this.props.startDate}
              />
            );
          }
          // No more travel objects in the day, just render empty slots
        } else {
          intervals.push(
            <OneHourInterval
              idV={i.toString()}
              items={null}
              zIndex={0}
              displayDate={this.props.displayDate}
              onRemoveItem={this.props.onRemoveItem}
              onEditItem={this.props.onEditItem}
              onAddItem={this.props.onAddItem}
              onClickObject={this.props.onClickObject}
              onClickInterval={this.handleOnClickInterval}
              onClickTimeslot={this.props.onClickTimeslot}
              onOpenSuggestions={this.props.onOpenSuggestions}
              startDate={this.props.startDate}
            />
          );
        }
      }
    }
    return intervals;
  }

  getTodaysHotel() {
    return this.props.hotelMap.get(this.props.displayDate.toDateString());
  }

  getMorningHotel() {
    let hotel = this.getTodaysHotel()
    if (hotel && this.getTodaysHotel().morningHotel !== undefined) {
      return this.getHotelBar(this.getTodaysHotel().morningHotel);
    }
    return null;
  }

  getNightHotel() {
    let hotel = this.getTodaysHotel()
    if (hotel && this.getTodaysHotel().nightHotel !== undefined) {
      return this.getHotelBar(this.getTodaysHotel().nightHotel);
    }
    return null;
  }

  getHotelBar(object) {
    return (

        < TravelObject
          key={object.id}
          data={object}
          onRemoveItem={this.props.onRemoveItem}
          onAddItem={this.props.onAddItem}
          onClickObject={this.props.onClickObject}
          onEditItem={this.props.onEditItem}
        />

    )
  }

  render() {
    return (

        <FinalizedHeader
          displayDate={this.props.displayDate}
          onChangeDisplayDate={this.props.onChangeDisplayDate}
        />

              {this.getMorningHotel()}

{this.getIntervals()}

              {this.getNightHotel()}

    );
  }
}
<commit_msg>Add comment for clarification<commit_after>import React from "react";
import FinalizedHeader from "../Sidebars/FinalizedHeader";
import "../../styles/TimeLine.css";
import { travelObjectStartDateComparator } from "../../scripts/HelperFunctions";
import { getEmptySlots, handleClickedTimePoint } from "./HandleClickedTimePoint";
import { sameDate } from "../../scripts/HelperFunctions";
import OneHourInterval from "./OneHourInterval";
import { Grid } from "@material-ui/core"
import TravelObject from "../TravelObjects/TravelObject"

export default class TimeLine extends React.Component {
  constructor(props) {
    super(props);
    this.date2Items = new Map();
    this.emptySlots = [];
    this.displayItems = [];
    this.displayItemsExcludeHotel = [];
    this.startOfDisplayDate = new Date(
      this.props.displayDate.getFullYear(),
      this.props.displayDate.getMonth(),
      this.props.displayDate.getDate(),
      0,
      0,
      0
    );
    this.endOfDisplayDate = new Date(
      this.props.displayDate.getFullYear(),
      this.props.displayDate.getMonth(),
      this.props.displayDate.getDate(),
      23,
      59,
      59
    );
    this.handleOnClickInterval = this.handleOnClickInterval.bind(this);
  }

  componentDidUpdate(prevProps) {
    if (prevProps.displayDate.toDateString() !== this.props.displayDate.toDateString) {
      this.setState()
    }
  }

  /*Given a date and an item, put the item to the list of items belonging to the given date. */
  addItemToDate(item, dateKey) {
    if (!this.date2Items.has(dateKey)) {
      this.date2Items.set(dateKey, [item]);
    } else {
      let items = this.date2Items.get(dateKey);
      items.push(item);
    }
  }

  /*Given a list of items (props.list), split the items into the its dates */
  separateDates() {
    for (let i = 0; i < this.props.list.length; i++) {
      let item = this.props.list[i];
      let startDate = item.startDate;
      let endDate = item.endDate;
      this.addItemToDate(item, startDate.toDateString());

      if (!sameDate(startDate, endDate)) {
        this.addItemToDate(item, endDate.toDateString());
      }
    }
  }

  handleOnClickInterval(idV) {
    idV = idV.length < 5 ? "0" + idV : idV;

    return handleClickedTimePoint(idV, this.startOfDisplayDate, this.endOfDisplayDate, this.displayItemsExcludeHotel, this.emptySlots)
  }

  /* Handling rendering starts HERE */
  getIntervals() {
    let intervals = [];
    if (this.props.displayDate !== undefined) {
      this.date2Items = new Map();
      this.displayItems = [];
      this.emptySlots = [];
      this.separateDates();
      this.displayItems = this.date2Items.has(
        this.props.displayDate.toDateString()
      )
        ? this.date2Items.get(this.props.displayDate.toDateString())
        : [];
      this.props.setTodaysEvents(
        this.displayItems,
        this.props.displayDate.toDateString()
      );

      this.displayItems.sort(travelObjectStartDateComparator);
      this.displayItemsExcludeHotel = this.displayItems.filter((item) => item.type !== "hotel");

      this.emptySlots = getEmptySlots(this.startOfDisplayDate, this.endOfDisplayDate, this.displayItemsExcludeHotel)

      var nextItemIndex = 0;
      var hotel = null; // flags hotel until finds right place to palce in timeline

      for (var i = 0; i < 24; i++) {
        // if there are still travel objects that haven't been rendered
        if (hotel || nextItemIndex < this.displayItems.length) {
          // End date within current display date for catching checkout time for flight
          // Renders interval from midnight until arrival time
          var nextItem = this.displayItems[nextItemIndex];
          if (nextItem !== undefined && (!sameDate(this.props.displayDate, nextItem.startDate) && nextItem.type === "flight")) {
            intervals.push(
              <OneHourInterval
                idV={
                  nextItem.type === "hotel" ? nextItem.endDate.getHours() : 0
                }
                items={[{ data: nextItem, div: ":00" }]}
                zIndex={nextItemIndex}
                displayDate={this.props.displayDate}
                onRemoveItem={this.props.onRemoveItem}
                onEditItem={this.props.onEditItem}
                onAddItem={this.props.onAddItem}
                onClickObject={this.props.onClickObject}
                onClickInterval={this.handleOnClickInterval}
                onClickTimeslot={this.props.onClickTimeslot}
                onOpenSuggestions={this.props.onOpenSuggestions}
                startDate={this.props.startDate}
              />
            );
          } else {
            var items = [];
            var div = null;

            var item = this.displayItems[nextItemIndex];

            // found hotel who's checkout time isn't in the current hour block --> flags it and moves index
            if (!hotel && item.type === "hotel" && !sameDate(item.startDate, this.props.displayDate) && item.endDate.getHours() !== i) {
              hotel = item;
              item = this.displayItems[++nextItemIndex];
            }

            // special case: no travel objects except for checkout for hotel
            if (hotel && this.displayItems.length === 1) {
              if (hotel.endDate.getHours() === i) {
                items.push({ data: hotel, div: hotel.endDate.getMinutes() < 30 ? ":00" : ":30"})
              }
            } else {
              // loops through all travelobjects within this one hour period
              while (
                (nextItemIndex < this.displayItems.length &&
                  this.displayItems[nextItemIndex].startDate.getHours() === i) || (hotel && hotel.endDate.getHours() === i)
              ) {
                // found proper location for previously flagged hotel.
                if (hotel && hotel.endDate.getHours() === i) {
                  item = hotel;
                  hotel = null;
                } else {
                  nextItemIndex++;
                }

                let nextItemStartDate = item.startDate;
                var nextItemMinutes = nextItemStartDate.getMinutes();

                if (nextItemMinutes < 30) {
                  div = ":00";
                } else {
                  div = ":30";
                }

                items.push({ data: item, div: div });
                item = this.displayItems[nextItemIndex];
              }
            }

            intervals.push(
              <OneHourInterval
                idV={i.toString()}
                items={items.length === 0 ? null : items}
                zIndex={nextItemIndex}
                displayDate={this.props.displayDate}
                onRemoveItem={this.props.onRemoveItem}
                onEditItem={this.props.onEditItem}
                onAddItem={this.props.onAddItem}
                onClickObject={this.props.onClickObject}
                onClickInterval={this.handleOnClickInterval}
                onClickTimeslot={this.props.onClickTimeslot}
                onOpenSuggestions={this.props.onOpenSuggestions}
                startDate={this.props.startDate}
              />
            );
          }
          // No more travel objects in the day, just render empty slots
        } else {
          intervals.push(
            <OneHourInterval
              idV={i.toString()}
              items={null}
              zIndex={0}
              displayDate={this.props.displayDate}
              onRemoveItem={this.props.onRemoveItem}
              onEditItem={this.props.onEditItem}
              onAddItem={this.props.onAddItem}
              onClickObject={this.props.onClickObject}
              onClickInterval={this.handleOnClickInterval}
              onClickTimeslot={this.props.onClickTimeslot}
              onOpenSuggestions={this.props.onOpenSuggestions}
              startDate={this.props.startDate}
            />
          );
        }
      }
    }
    return intervals;
  }

  getTodaysHotel() {
    return this.props.hotelMap.get(this.props.displayDate.toDateString());
  }

  getMorningHotel() {
    let hotel = this.getTodaysHotel()
    if (hotel && this.getTodaysHotel().morningHotel !== undefined) {
      return this.getHotelBar(this.getTodaysHotel().morningHotel);
    }
    return null;
  }

  getNightHotel() {
    let hotel = this.getTodaysHotel()
    if (hotel && this.getTodaysHotel().nightHotel !== undefined) {
      return this.getHotelBar(this.getTodaysHotel().nightHotel);
    }
    return null;
  }

  getHotelBar(object) {
    return (

        < TravelObject
          key={object.id}
          data={object}
          onRemoveItem={this.props.onRemoveItem}
          onAddItem={this.props.onAddItem}
          onClickObject={this.props.onClickObject}
          onEditItem={this.props.onEditItem}
        />

    )
  }

  render() {
    return (

        <FinalizedHeader
          displayDate={this.props.displayDate}
          onChangeDisplayDate={this.props.onChangeDisplayDate}
        />

              {this.getMorningHotel()}

{this.getIntervals()}

              {this.getNightHotel()}

    );
  }
}
<|endoftext|>


<commit_before>const {contractId} = require("../utils/helpers")
const config = require("../migrations/migrations.config.js")
const genesisConfig = require("../migrations/genesis.config.js")

const Controller = artifacts.require("Controller")
const BondingManager = artifacts.require("BondingManager")
const JobsManager = artifacts.require("JobsManager")
const RoundsManager = artifacts.require("RoundsManager")
const Minter = artifacts.require("Minter")
const LivepeerVerifier = artifacts.require("LivepeerVerifier")
const LivepeerToken = artifacts.require("LivepeerToken")
const GenesisManager = artifacts.require("GenesisManager")
const TokenDistributionMock = artifacts.require("TokenDistributionMock")
const TokenVesting = artifacts.require("TokenVesting")
const TokenTimelock = artifacts.require("TokenTimelock")

contract("Verify deployment and genesis", accounts => {
    let controller
    let bondingManager
    let jobsManager
    let roundsManager
    let minter
    let verifier
    let token
    let genesisManager

    let dummyTokenDistribution

    before(async () => {
        controller = await Controller.deployed()

        const bondingManagerAddr = await controller.getContract(contractId("BondingManager"))
        bondingManager = await BondingManager.at(bondingManagerAddr)

        const jobsManagerAddr = await controller.getContract(contractId("JobsManager"))
        jobsManager = await JobsManager.at(jobsManagerAddr)

        const roundsManagerAddr = await controller.getContract(contractId("RoundsManager"))
        roundsManager = await RoundsManager.at(roundsManagerAddr)

        const minterAddr = await controller.getContract(contractId("Minter"))
        minter = await Minter.at(minterAddr)

        const verifierAddr = await controller.getContract(contractId("Verifier"))
        verifier = await LivepeerVerifier.at(verifierAddr)

        const tokenAddr = await controller.getContract(contractId("LivepeerToken"))
        token = await LivepeerToken.at(tokenAddr)

        genesisManager = await GenesisManager.deployed()

        const dummyTokenDistributionAddr = await genesisManager.tokenDistribution.call()
        dummyTokenDistribution = await TokenDistributionMock.at(dummyTokenDistributionAddr)
    })

    it("checks contract system state post-deployment", async () => {
        // Check BondingManager parameters
        assert.equal(await bondingManager.controller.call(), controller.address, "should be correct Controller for BondingManager")
        assert.equal(await bondingManager.unbondingPeriod.call(), config.bondingManager.unbondingPeriod, "should be correct unbondingPeriod")
        assert.equal(await bondingManager.getTranscoderPoolMaxSize(), config.bondingManager.numTranscoders, "should be correct max transcoder pool size")
        assert.equal(await bondingManager.numActiveTranscoders.call(), config.bondingManager.numActiveTranscoders, "should be correct numActiveTranscoders")
        assert.equal(await bondingManager.maxEarningsClaimsRounds.call(), config.bondingManager.maxEarningsClaimsRounds, "should be correct maxEarningsClaimsRounds")
        // Check BondingManager balances
        assert.equal(web3.eth.getBalance(bondingManager.address), 0, "BondingManager should have 0 ETH")
        assert.equal(await token.balanceOf(bondingManager.address), 0, "BondingManager should have 0 LPT")

        // Check JobsManager parameters
        assert.equal(await jobsManager.controller.call(), controller.address, "should be correct Controller for JobsManager")
        assert.equal(await jobsManager.verificationRate.call(), config.jobsManager.verificationRate, "should be correct verificationRate")
        assert.equal(await jobsManager.verificationPeriod.call(), config.jobsManager.verificationPeriod, "should be correct verificationPeriod")
        assert.equal(await jobsManager.verificationSlashingPeriod.call(), config.jobsManager.verificationSlashingPeriod, "should be correct verificationSlashingPeriod")
        assert.equal(await jobsManager.failedVerificationSlashAmount.call(), config.jobsManager.failedVerificationSlashAmount, "should be correct failedVerificationSlashAmount")
        assert.equal(await jobsManager.missedVerificationSlashAmount.call(), config.jobsManager.missedVerificationSlashAmount, "should be correct missedVerificationSlashAmount")
        assert.equal(await jobsManager.doubleClaimSegmentSlashAmount.call(), config.jobsManager.doubleClaimSegmentSlashAmount, "should be correct doubleClaimSegmentSlashAmount")
        assert.equal(await jobsManager.finderFee.call(), config.jobsManager.finderFee, "should be correct finderFee")
        // Check JobsManager balances
        assert.equal(web3.eth.getBalance(jobsManager.address), 0, "JobsManager should have 0 ETH")
        assert.equal(await token.balanceOf(jobsManager.address), 0, "JobsManager should have 0 LPT")

        // Check RoundsManager parameters
        assert.equal(await roundsManager.controller.call(), controller.address, "should be correct Controller for RoundsManager")
        assert.equal(await roundsManager.roundLength.call(), config.roundsManager.roundLength, "should be correct roundLength")
        assert.equal(await roundsManager.roundLockAmount.call(), config.roundsManager.roundLockAmount, "should be correct roundLockAmount")
        // Check RoundsManager balances
        assert.equal(web3.eth.getBalance(roundsManager.address), 0, "RoundsManager should have 0 ETH")
        assert.equal(await token.balanceOf(roundsManager.address), 0, "RoundManager should have 0 LPT")

        // Check Minter parameters
        assert.equal(await minter.controller.call(), controller.address, "should be correct Controller for Minter")
        assert.equal(await minter.inflation.call(), config.minter.inflation, "should be correct inflation")
        assert.equal(await minter.inflationChange.call(), config.minter.inflationChange, "should be correct inflationChange")
        assert.equal(await minter.targetBondingRate.call(), config.minter.targetBondingRate, "should be correct targetBondingRate")
        // Check Minter balances
        assert.equal(web3.eth.getBalance(minter.address), 0, "Minter should have 0 ETH")
        assert.equal(await token.balanceOf(minter.address), 0, "Minter should have 0 LPT")

        // Check LivepeerVerifier parameters
        assert.equal(await verifier.controller.call(), controller.address, "should be correct Controller for LivepeerVerifier")
        assert.equal(await verifier.verificationCodeHash.call(), config.verifier.verificationCodeHash, "should be correct verificationCodeHash")
        config.verifier.solvers.forEach(async solver => {
            assert.isOk(await verifier.isSolver(solver), "should have whitelisted solver")
        })
        // Check LivepeerVerifier balances
        assert.equal(web3.eth.getBalance(verifier.address), 0, "LivepeerVerifier should have 0 ETH")
        assert.equal(await token.balanceOf(verifier.address), 0, "LivepeerVerifier should have 0 LPT")
    })

    it("checks system state post-genesis", async () => {
        assert.equal(await token.totalSupply(), genesisConfig.initialSupply.toNumber(), "should be correct initial total supply")
        assert.equal(await token.balanceOf(genesisConfig.bankMultisig), genesisConfig.companySupply.toNumber(), "bank multisig should have correct company supply")
        assert.equal(genesisConfig.crowdSupply, 0, "genesis crowd supply should have been 0")
        assert.equal(await token.balanceOf(dummyTokenDistribution.address), genesisConfig.crowdSupply.toNumber(), "dummy token distribution should have 0 crowd supply")

        const dummyTokenDistributionEndTime = await dummyTokenDistribution.getEndTime()

        // Check vesting team grants
        genesisConfig.teamGrants.forEach(async grant => {
            const vestingHolderAddr = await genesisManager.vestingHolders.call(grant.receiver)
            const vestingHolder = await TokenVesting.at(vestingHolderAddr)
            assert.equal(await vestingHolder.beneficiary.call(), grant.receiver, "should be correct vesting grant receiver")
            assert.equal(await vestingHolder.start.call(), dummyTokenDistributionEndTime.toNumber(), "should be correct vesting start time")
            assert.equal(await vestingHolder.cliff.call(), dummyTokenDistributionEndTime.plus(grant.timeToCliff).toNumber(), "should be correct vesting cliff time")
            assert.equal(await vestingHolder.duration.call(), grant.vestingDuration.toNumber(), "should be correct vesting duration")
            assert.equal(await token.balanceOf(vestingHolderAddr), grant.amount.toNumber(), "should be correct vesting grant amount")
        })

        // Check vesting investor grants
        genesisConfig.investorGrants.forEach(async grant => {
            const vestingHolderAddr = await genesisManager.vestingHolders.call(grant.receiver)
            const vestingHolder = await TokenVesting.at(vestingHolderAddr)
            assert.equal(await vestingHolder.beneficiary.call(), grant.receiver, "should be correct vesting grant receiver")
            assert.equal(await vestingHolder.start.call(), dummyTokenDistributionEndTime.toNumber(), "should be correct vesting start time")
            assert.equal(await vestingHolder.cliff.call(), dummyTokenDistributionEndTime.plus(grant.timeToCliff).toNumber(), "should be correct vesting cliff time")
            assert.equal(await vestingHolder.duration.call(), grant.vestingDuration.toNumber(), "should be correct vesting duration")
            assert.equal(await token.balanceOf(vestingHolderAddr), grant.amount.toNumber(), "should be correct vesting grant amount")
        })

        // Check timelock community grants
        genesisConfig.communityGrants.forEach(async grant => {
            const timeLockedHolderAddr = await genesisManager.timeLockedHolders.call(grant.receiver)
            const timeLockedHolder = await TokenTimelock.at(timeLockedHolderAddr)
            assert.equal(await timeLockedHolder.beneficiary.call(), grant.receiver, "should be correct timelocked grant receiver")
            assert.equal(await timeLockedHolder.releaseTime.call(), dummyTokenDistributionEndTime.toNumber(), "should be correct lock release time")
            assert.equal(await token.balanceOf(timeLockedHolderAddr), grant.amount.toNumber(), "should be correct timelocked grant amount")
        })
    })
})
<commit_msg>Add tests for Controller in deployment/genesis verification script<commit_after>const {contractId} = require("../utils/helpers")
const config = require("../migrations/migrations.config.js")
const genesisConfig = require("../migrations/genesis.config.js")

const Controller = artifacts.require("Controller")
const BondingManager = artifacts.require("BondingManager")
const JobsManager = artifacts.require("JobsManager")
const RoundsManager = artifacts.require("RoundsManager")
const Minter = artifacts.require("Minter")
const LivepeerVerifier = artifacts.require("LivepeerVerifier")
const LivepeerToken = artifacts.require("LivepeerToken")
const GenesisManager = artifacts.require("GenesisManager")
const TokenDistributionMock = artifacts.require("TokenDistributionMock")
const TokenVesting = artifacts.require("TokenVesting")
const TokenTimelock = artifacts.require("TokenTimelock")

contract("Verify deployment and genesis", accounts => {
    let controller
    let bondingManager
    let jobsManager
    let roundsManager
    let minter
    let verifier
    let token
    let genesisManager

    let dummyTokenDistribution

    before(async () => {
        controller = await Controller.deployed()

        const bondingManagerAddr = await controller.getContract(contractId("BondingManager"))
        bondingManager = await BondingManager.at(bondingManagerAddr)

        const jobsManagerAddr = await controller.getContract(contractId("JobsManager"))
        jobsManager = await JobsManager.at(jobsManagerAddr)

        const roundsManagerAddr = await controller.getContract(contractId("RoundsManager"))
        roundsManager = await RoundsManager.at(roundsManagerAddr)

        const minterAddr = await controller.getContract(contractId("Minter"))
        minter = await Minter.at(minterAddr)

        const verifierAddr = await controller.getContract(contractId("Verifier"))
        verifier = await LivepeerVerifier.at(verifierAddr)

        const tokenAddr = await controller.getContract(contractId("LivepeerToken"))
        token = await LivepeerToken.at(tokenAddr)

        genesisManager = await GenesisManager.deployed()

        const dummyTokenDistributionAddr = await genesisManager.tokenDistribution.call()
        dummyTokenDistribution = await TokenDistributionMock.at(dummyTokenDistributionAddr)
    })

    it("checks contract system state post-deployment", async () => {
        assert.equal(await controller.owner.call(), accounts[0], "Controller's owner should be the configured sender account used by Truffle")
        assert.equal(await controller.paused.call(), true, "Controller should be paused")

        // Check BondingManager parameters
        assert.equal(await bondingManager.controller.call(), controller.address, "should be correct Controller for BondingManager")
        assert.equal(await bondingManager.unbondingPeriod.call(), config.bondingManager.unbondingPeriod, "should be correct unbondingPeriod")
        assert.equal(await bondingManager.getTranscoderPoolMaxSize(), config.bondingManager.numTranscoders, "should be correct max transcoder pool size")
        assert.equal(await bondingManager.numActiveTranscoders.call(), config.bondingManager.numActiveTranscoders, "should be correct numActiveTranscoders")
        assert.equal(await bondingManager.maxEarningsClaimsRounds.call(), config.bondingManager.maxEarningsClaimsRounds, "should be correct maxEarningsClaimsRounds")
        // Check BondingManager balances
        assert.equal(web3.eth.getBalance(bondingManager.address), 0, "BondingManager should have 0 ETH")
        assert.equal(await token.balanceOf(bondingManager.address), 0, "BondingManager should have 0 LPT")

        // Check JobsManager parameters
        assert.equal(await jobsManager.controller.call(), controller.address, "should be correct Controller for JobsManager")
        assert.equal(await jobsManager.verificationRate.call(), config.jobsManager.verificationRate, "should be correct verificationRate")
        assert.equal(await jobsManager.verificationPeriod.call(), config.jobsManager.verificationPeriod, "should be correct verificationPeriod")
        assert.equal(await jobsManager.verificationSlashingPeriod.call(), config.jobsManager.verificationSlashingPeriod, "should be correct verificationSlashingPeriod")
        assert.equal(await jobsManager.failedVerificationSlashAmount.call(), config.jobsManager.failedVerificationSlashAmount, "should be correct failedVerificationSlashAmount")
        assert.equal(await jobsManager.missedVerificationSlashAmount.call(), config.jobsManager.missedVerificationSlashAmount, "should be correct missedVerificationSlashAmount")
        assert.equal(await jobsManager.doubleClaimSegmentSlashAmount.call(), config.jobsManager.doubleClaimSegmentSlashAmount, "should be correct doubleClaimSegmentSlashAmount")
        assert.equal(await jobsManager.finderFee.call(), config.jobsManager.finderFee, "should be correct finderFee")
        // Check JobsManager balances
        assert.equal(web3.eth.getBalance(jobsManager.address), 0, "JobsManager should have 0 ETH")
        assert.equal(await token.balanceOf(jobsManager.address), 0, "JobsManager should have 0 LPT")

        // Check RoundsManager parameters
        assert.equal(await roundsManager.controller.call(), controller.address, "should be correct Controller for RoundsManager")
        assert.equal(await roundsManager.roundLength.call(), config.roundsManager.roundLength, "should be correct roundLength")
        assert.equal(await roundsManager.roundLockAmount.call(), config.roundsManager.roundLockAmount, "should be correct roundLockAmount")
        // Check RoundsManager balances
        assert.equal(web3.eth.getBalance(roundsManager.address), 0, "RoundsManager should have 0 ETH")
        assert.equal(await token.balanceOf(roundsManager.address), 0, "RoundManager should have 0 LPT")

        // Check Minter parameters
        assert.equal(await minter.controller.call(), controller.address, "should be correct Controller for Minter")
        assert.equal(await minter.inflation.call(), config.minter.inflation, "should be correct inflation")
        assert.equal(await minter.inflationChange.call(), config.minter.inflationChange, "should be correct inflationChange")
        assert.equal(await minter.targetBondingRate.call(), config.minter.targetBondingRate, "should be correct targetBondingRate")
        // Check Minter balances
        assert.equal(web3.eth.getBalance(minter.address), 0, "Minter should have 0 ETH")
        assert.equal(await token.balanceOf(minter.address), 0, "Minter should have 0 LPT")

        // Check LivepeerVerifier parameters
        assert.equal(await verifier.controller.call(), controller.address, "should be correct Controller for LivepeerVerifier")
        assert.equal(await verifier.verificationCodeHash.call(), config.verifier.verificationCodeHash, "should be correct verificationCodeHash")
        config.verifier.solvers.forEach(async solver => {
            assert.isOk(await verifier.isSolver(solver), "should have whitelisted solver")
        })
        // Check LivepeerVerifier balances
        assert.equal(web3.eth.getBalance(verifier.address), 0, "LivepeerVerifier should have 0 ETH")
        assert.equal(await token.balanceOf(verifier.address), 0, "LivepeerVerifier should have 0 LPT")
    })

    it("checks system state post-genesis", async () => {
        assert.equal(await token.totalSupply(), genesisConfig.initialSupply.toNumber(), "should be correct initial total supply")
        assert.equal(await token.balanceOf(genesisConfig.bankMultisig), genesisConfig.companySupply.toNumber(), "bank multisig should have correct company supply")
        assert.equal(genesisConfig.crowdSupply, 0, "genesis crowd supply should have been 0")
        assert.equal(await token.balanceOf(dummyTokenDistribution.address), genesisConfig.crowdSupply.toNumber(), "dummy token distribution should have 0 crowd supply")

        const dummyTokenDistributionEndTime = await dummyTokenDistribution.getEndTime()

        // Check vesting team grants
        genesisConfig.teamGrants.forEach(async grant => {
            const vestingHolderAddr = await genesisManager.vestingHolders.call(grant.receiver)
            const vestingHolder = await TokenVesting.at(vestingHolderAddr)
            assert.equal(await vestingHolder.beneficiary.call(), grant.receiver, "should be correct vesting grant receiver")
            assert.equal(await vestingHolder.start.call(), dummyTokenDistributionEndTime.toNumber(), "should be correct vesting start time")
            assert.equal(await vestingHolder.cliff.call(), dummyTokenDistributionEndTime.plus(grant.timeToCliff).toNumber(), "should be correct vesting cliff time")
            assert.equal(await vestingHolder.duration.call(), grant.vestingDuration.toNumber(), "should be correct vesting duration")
            assert.equal(await token.balanceOf(vestingHolderAddr), grant.amount.toNumber(), "should be correct vesting grant amount")
        })

        // Check vesting investor grants
        genesisConfig.investorGrants.forEach(async grant => {
            const vestingHolderAddr = await genesisManager.vestingHolders.call(grant.receiver)
            const vestingHolder = await TokenVesting.at(vestingHolderAddr)
            assert.equal(await vestingHolder.beneficiary.call(), grant.receiver, "should be correct vesting grant receiver")
            assert.equal(await vestingHolder.start.call(), dummyTokenDistributionEndTime.toNumber(), "should be correct vesting start time")
            assert.equal(await vestingHolder.cliff.call(), dummyTokenDistributionEndTime.plus(grant.timeToCliff).toNumber(), "should be correct vesting cliff time")
            assert.equal(await vestingHolder.duration.call(), grant.vestingDuration.toNumber(), "should be correct vesting duration")
            assert.equal(await token.balanceOf(vestingHolderAddr), grant.amount.toNumber(), "should be correct vesting grant amount")
        })

        // Check timelock community grants
        genesisConfig.communityGrants.forEach(async grant => {
            const timeLockedHolderAddr = await genesisManager.timeLockedHolders.call(grant.receiver)
            const timeLockedHolder = await TokenTimelock.at(timeLockedHolderAddr)
            assert.equal(await timeLockedHolder.beneficiary.call(), grant.receiver, "should be correct timelocked grant receiver")
            assert.equal(await timeLockedHolder.releaseTime.call(), dummyTokenDistributionEndTime.toNumber(), "should be correct lock release time")
            assert.equal(await token.balanceOf(timeLockedHolderAddr), grant.amount.toNumber(), "should be correct timelocked grant amount")
        })
    })
})
<|endoftext|>


<commit_before>
describe("geo.map", function() {

  describe('cdb.geo.MapLayer', function() {
    var layer;
    beforeEach(function() {
      layer  = new cdb.geo.MapLayer();
      layer.url = function() {return true};
      layer.sync = function() {return true};
    });

    it("should update the style when a new table name is set", function() {
      layer.set({tile_style: '#table_name {}'});
      layer.updateCartoCss('table_name', 'map_of_name');
      expect(layer.get('tile_style')).toEqual('#map_of_name {}');
    });

  });

  describe('GMapsBaseLayer', function() {
    it("should be type GMapsBase", function() {
      var layer = new cdb.geo.GMapsBaseLayer();
      expect(layer.get('type')).toEqual("GMapsBase");
    });

    it("should unset maxzoom", function() {
      var layer = new cdb.geo.GMapsBaseLayer();

      layer.set('maxZoom', 10)
      expect(layer.get('maxZoom')).toEqual(40);

      layer.set({'maxZoom': 10 })
      expect(layer.get('maxZoom')).toEqual(40);
    });

  });

  describe('TileLayer', function() {
    it("should be type tiled", function() {
      var layer = new cdb.geo.TileLayer();
      expect(layer.get('type')).toEqual("Tiled");
    });
  });

  describe('CartoDBLayer', function() {
    it("should be type CartoDB", function() {
      var layer = new cdb.geo.CartoDBLayer();
      expect(layer.get('type')).toEqual("CartoDB");
    });
  });

  describe('CartoDBGroupLayer', function() {
    it("should be type layergroup", function() {
      var layer = new cdb.geo.CartoDBGroupLayer();
      expect(layer.get('type')).toEqual("layergroup");
    });
  });

  describe("Layers", function() {
    var layers;
    beforeEach(function() {
      layers = new cdb.geo.Layers();
    });

    it("should compare equal layers correctly", function() {
      var layer1 = new cdb.geo.PlainLayer({color: '#zipote'});
      var layer2 = new cdb.geo.PlainLayer({});
      var layer3 = new cdb.geo.PlainLayer({});
      var layer4 = new cdb.geo.PlainLayer({});

      expect(layer3.isEqual(layer4)).toBeTruthy();
      expect(layer1.isEqual(layer2)).not.toBeTruthy();

      layers.add(layer4);
      layers.add(layer3);

      expect(layer3.isEqual(layer4)).toBeTruthy();
    })

    it("should assign indices", function() {
      var layer1 = new cdb.geo.PlainLayer({order: 10, color: '#zipote'});
      var layer2 = new cdb.geo.PlainLayer({});
      var layer3 = new cdb.geo.PlainLayer({});
      layers.add(layer1);
      expect(layer1.get('order')).toEqual(0);
      layers.add(layer2);
      expect(layer2.get('order')).toEqual(1);
      layers.add(layer3, { at: 1});
      expect(layer2.get('order')).toEqual(2);
      expect(layer3.get('order')).toEqual(1);
    });

  });
  describe("Map", function() {
    var map;
    beforeEach(function() {
      map = new cdb.geo.Map();
    });

    it("should raise only one change event on setBounds", function() {
      var c = 0;
      map.bind('change:view_bounds_ne', function() {
        c++;
      });
      map.setBounds([[1,2],[1,2]]);
      expect(c).toEqual(1);
    });

    it("should not change center or zoom when the bounds are not ok", function() {
      var c = 0;
      map.bind('change:center', function() {
        c++;
      });
      map.setBounds([[1,2],[1,2]]);
      expect(c).toEqual(0);
    });

  });

  describe('MapView', function() {
    beforeEach(function() {
      this.container = $('<div>').css('height', '200px');

      this.map = new cdb.geo.Map();
      this.mapView = new cdb.geo.MapView({
        el: this.container,
        map: this.map
      });
    });

    it('should be able to add a infowindow', function() {
      var infow = new cdb.geo.ui.Infowindow({mapView: this.mapView, model: new Backbone.Model()});
      this.mapView.addInfowindow(infow);

      expect(this.mapView._subviews[infow.cid]).toBeTruthy()
      expect(this.mapView._subviews[infow.cid] instanceof cdb.geo.ui.Infowindow).toBeTruthy()

    });

    it('should be able to retrieve the infowindows', function() {
      var infow = new cdb.geo.ui.Infowindow({mapView: this.mapView, model: new Backbone.Model()});
      this.mapView._subviews['irrelevant'] = new Backbone.View();
      this.mapView.addInfowindow(infow);

      var infowindows = this.mapView.getInfoWindows()

      expect(infowindows.length).toEqual(1);
      expect(infowindows[0]).toEqual(infow);
    });
  });

});
<commit_msg>Fixes spec<commit_after>
describe("geo.map", function() {

  describe('cdb.geo.MapLayer', function() {
    var layer;
    beforeEach(function() {
      layer  = new cdb.geo.MapLayer();
      layer.url = function() {return true};
      layer.sync = function() {return true};
    });

    it("should update the style when a new table name is set", function() {
      layer.set({tile_style: '#table_name {}'});
      layer.updateCartoCss('table_name', 'map_of_name');
      expect(layer.get('tile_style')).toEqual('#map_of_name {}');
    });

  });

  describe('GMapsBaseLayer', function() {

    it("should be type GMapsBase", function() {
      var layer = new cdb.geo.GMapsBaseLayer();
      expect(layer.get('type')).toEqual("GMapsBase");
    });

  });

  describe('TileLayer', function() {
    it("should be type tiled", function() {
      var layer = new cdb.geo.TileLayer();
      expect(layer.get('type')).toEqual("Tiled");
    });
  });

  describe('CartoDBLayer', function() {
    it("should be type CartoDB", function() {
      var layer = new cdb.geo.CartoDBLayer();
      expect(layer.get('type')).toEqual("CartoDB");
    });
  });

  describe('CartoDBGroupLayer', function() {
    it("should be type layergroup", function() {
      var layer = new cdb.geo.CartoDBGroupLayer();
      expect(layer.get('type')).toEqual("layergroup");
    });
  });

  describe("Layers", function() {
    var layers;
    beforeEach(function() {
      layers = new cdb.geo.Layers();
    });

    it("should compare equal layers correctly", function() {
      var layer1 = new cdb.geo.PlainLayer({color: '#zipote'});
      var layer2 = new cdb.geo.PlainLayer({});
      var layer3 = new cdb.geo.PlainLayer({});
      var layer4 = new cdb.geo.PlainLayer({});

      expect(layer3.isEqual(layer4)).toBeTruthy();
      expect(layer1.isEqual(layer2)).not.toBeTruthy();

      layers.add(layer4);
      layers.add(layer3);

      expect(layer3.isEqual(layer4)).toBeTruthy();
    })

    it("should assign indices", function() {
      var layer1 = new cdb.geo.PlainLayer({order: 10, color: '#zipote'});
      var layer2 = new cdb.geo.PlainLayer({});
      var layer3 = new cdb.geo.PlainLayer({});
      layers.add(layer1);
      expect(layer1.get('order')).toEqual(0);
      layers.add(layer2);
      expect(layer2.get('order')).toEqual(1);
      layers.add(layer3, { at: 1});
      expect(layer2.get('order')).toEqual(2);
      expect(layer3.get('order')).toEqual(1);
    });

  });
  describe("Map", function() {
    var map;
    beforeEach(function() {
      map = new cdb.geo.Map();
    });

    it("should raise only one change event on setBounds", function() {
      var c = 0;
      map.bind('change:view_bounds_ne', function() {
        c++;
      });
      map.setBounds([[1,2],[1,2]]);
      expect(c).toEqual(1);
    });

    it("should not change center or zoom when the bounds are not ok", function() {
      var c = 0;
      map.bind('change:center', function() {
        c++;
      });
      map.setBounds([[1,2],[1,2]]);
      expect(c).toEqual(0);
    });

  });

  describe('MapView', function() {
    beforeEach(function() {
      this.container = $('<div>').css('height', '200px');

      this.map = new cdb.geo.Map();
      this.mapView = new cdb.geo.MapView({
        el: this.container,
        map: this.map
      });
    });

    it('should be able to add a infowindow', function() {
      var infow = new cdb.geo.ui.Infowindow({mapView: this.mapView, model: new Backbone.Model()});
      this.mapView.addInfowindow(infow);

      expect(this.mapView._subviews[infow.cid]).toBeTruthy()
      expect(this.mapView._subviews[infow.cid] instanceof cdb.geo.ui.Infowindow).toBeTruthy()

    });

    it('should be able to retrieve the infowindows', function() {
      var infow = new cdb.geo.ui.Infowindow({mapView: this.mapView, model: new Backbone.Model()});
      this.mapView._subviews['irrelevant'] = new Backbone.View();
      this.mapView.addInfowindow(infow);

      var infowindows = this.mapView.getInfoWindows()

      expect(infowindows.length).toEqual(1);
      expect(infowindows[0]).toEqual(infow);
    });
  });

});
<|endoftext|>


<commit_before>
describe("Overlay", function() {

  it("should register and create a type", function() {
    var _data;
    cdb.vis.Overlay.register('test', function(data) {
      _data = data;
      return new cdb.core.View();
    });

    var opt = {a : 1, b:2, pos: [10, 20]};
    var v = cdb.vis.Overlay.create('test', null, opt);
    expect(_data).toEqual(opt);

  });

});

describe("Vis", function() {

  beforeEach(function(){
    this.container = $('<div>').css('height', '200px');
    this.mapConfig = {
      title: "irrelevant",
      center: [40.044, -101.95],
      bounding_box_sw: [20, -140],
      bounding_box_ne: [ 55, -50],
      zoom: 4,
      bounds: [
        [1, 2],
        [3, 4],
      ]
    };

    this.vis = new cdb.vis.Vis({el: this.container});
    this.vis.load(this.mapConfig);

  })

  it("should insert  default max and minZoom values when not provided", function() {
    expect(this.vis.mapView.map_leaflet.options.maxZoom).toEqual(20);
    expect(this.vis.mapView.map_leaflet.options.minZoom).toEqual(0);
  });

  it("should insert user max and minZoom values when provided", function() {
    this.container = $('<div>').css('height', '200px');
    this.mapConfig.maxZoom = 10;
    this.mapConfig.minZoom = 5;
    this.vis.load(this.mapConfig);

    expect(this.vis.mapView.map_leaflet.options.maxZoom).toEqual(10);
    expect(this.vis.mapView.map_leaflet.options.minZoom).toEqual(5);
  })

  it("should insert the max boundaries when provided", function() {
    this.container = $('<div>').css('height', '200px');
    this.mapConfig.bounding_box_sw = [1,2];
    this.mapConfig.bounding_box_ne = [3,5];
    this.vis.load(this.mapConfig);

    expect(this.vis.map.get('bounding_box_sw')).toEqual([1,2]);
    expect(this.vis.map.get('bounding_box_ne')).toEqual([3,5]);
  })

  it("should create a google maps map when provider is google maps", function() {
    this.container = $('<div>').css('height', '200px');
    this.mapConfig.map_provider = "googlemaps";
    this.vis.load(this.mapConfig);
    expect(this.vis.mapView.map_googlemaps).not.toEqual(undefined);
  });

})
<commit_msg>added some tests<commit_after>
describe("Overlay", function() {

  it("should register and create a type", function() {
    var _data;
    cdb.vis.Overlay.register('test', function(data) {
      _data = data;
      return new cdb.core.View();
    });

    var opt = {a : 1, b:2, pos: [10, 20]};
    var v = cdb.vis.Overlay.create('test', null, opt);
    expect(_data).toEqual(opt);

  });

});

describe("Vis", function() {

  beforeEach(function(){
    this.container = $('<div>').css('height', '200px');
    this.mapConfig = {
      title: "irrelevant",
      center: [40.044, -101.95],
      bounding_box_sw: [20, -140],
      bounding_box_ne: [ 55, -50],
      zoom: 4,
      bounds: [
        [1, 2],
        [3, 4],
      ]
    };

    this.vis = new cdb.vis.Vis({el: this.container});
    this.vis.load(this.mapConfig);

  })

  it("should insert  default max and minZoom values when not provided", function() {
    expect(this.vis.mapView.map_leaflet.options.maxZoom).toEqual(20);
    expect(this.vis.mapView.map_leaflet.options.minZoom).toEqual(0);
  });

  it("should insert user max and minZoom values when provided", function() {
    this.container = $('<div>').css('height', '200px');
    this.mapConfig.maxZoom = 10;
    this.mapConfig.minZoom = 5;
    this.vis.load(this.mapConfig);

    expect(this.vis.mapView.map_leaflet.options.maxZoom).toEqual(10);
    expect(this.vis.mapView.map_leaflet.options.minZoom).toEqual(5);
  })

  it("should insert the max boundaries when provided", function() {
    this.container = $('<div>').css('height', '200px');
    this.mapConfig.bounding_box_sw = [1,2];
    this.mapConfig.bounding_box_ne = [3,5];
    this.vis.load(this.mapConfig);

    expect(this.vis.map.get('bounding_box_sw')).toEqual([1,2]);
    expect(this.vis.map.get('bounding_box_ne')).toEqual([3,5]);
  })

  it("should create a google maps map when provider is google maps", function() {
    this.container = $('<div>').css('height', '200px');
    this.mapConfig.map_provider = "googlemaps";
    this.vis.load(this.mapConfig);
    expect(this.vis.mapView.map_googlemaps).not.toEqual(undefined);
  });

  it("should pass map to overlays", function() {
    var _map;
    cdb.vis.Overlay.register('jaja', function(data, vis){
      _map = vis.map
      return new cdb.core.View()
    })
    var vis = new cdb.vis.Vis({el: this.container});
    this.mapConfig.overlays = [ {type: 'jaja'}];
    vis.load(this.mapConfig);
    expect(_map).not.toEqual(undefined);
  });

})
<|endoftext|>


<commit_before>var app = angular.module('rdb', [])

app.controller('MainCtrl', function($scope, $http) {
  var self = this;

  $scope.process = null;
  $scope.running = true;
  $scope.activeThread = null;
  $scope.activeFrame = null;
  $scope.locals = {};
  self.liveThread = null;

  var source = new EventSource('/events');
  source.addEventListener('message', function(e) {
    $scope.$apply(function() {
      var message = JSON.parse(e.data);
      if (message.event == 'breakpoint') {
        updateThreads();
        updateRunning();
      }
    });
  }, false);

  $scope.showSettings = function() {
  };

  $scope.pause = function() {
    $http.put('/pause')
      .success(function(res) {
        $scope.running = res.running;
        updateThreads();
      });
  };

  $scope.resume = function() {
    $http.put('/resume')
      .success(function(res) {
        $scope.running = res.running;
      });
  };

  $scope.stepIn = function() {
    $http.put('/step-in')
      .success(function(res) {
        updateThreads();
        updateLocals();
      });
  };

  $scope.stepOver = function() {
    $http.put('/step-over')
      .success(function(res) {
        updateThreads();
        updateLocals();
      });
  };

  $scope.stepOut = function() {
    $http.put('/step-out')
      .success(function(res) {
        updateThreads();
        updateLocals();
      });
  };

  $scope.openFile = function(path, line) {
    $http.post('/open', { path: path, line: line })
      .success(function() {
      });
  }

  $scope.setActiveThread = function(thread) {
    $scope.activeThread = thread;
    $scope.setActiveFrame(thread.backtrace[0]);
  };

  $scope.setActiveFrame = function(frame) {
    $scope.activeFrame = frame;
    $scope.$broadcast('active-frame', frame);
  };

  function updateThreads() {
    $http.get('/threads')
      .success(function(res) {
        $scope.threads = res;

        for (var i = 0; i < $scope.threads.length; ++i) {
          var thread = $scope.threads[i];
          if (thread.main) {
            self.liveThread = thread;
            $scope.setActiveThread(self.liveThread);
            break;
          }
        }
      });
  }

  function updateLocals() {
    $http.get('/locals')
      .success(function(res) {
        $scope.locals = res;
      });
  }

  function updateRunning() {
    $http.get('/running')
      .success(function(res) {
        $scope.running = res.running;
      });
  }

  function connect() {
    $http.get('/process')
      .success(function(res) {
        $scope.process = res.process;
      });

    updateRunning();
    updateThreads();
    updateLocals();
  }

  connect();
});

app.controller('SourceEditCtrl', function($scope, $http) {
  var self = this;

  // Maps line number to breakpoint ID.
  self.breakpoints = {};
  self.activeMarker = null;

  self.editor = ace.edit('source-editor');
  self.editor.setTheme('ace/theme/clouds');
  self.editor.session.setMode("ace/mode/ruby");
  self.editor.setReadOnly(true);
  self.editor.setShowPrintMargin(false);

  self.editor.on('guttermousedown', function(e) {
    var target = e.domEvent.target;
    if (target.className.indexOf('ace_gutter-cell') < 0) {
      return;
    }

    var row = e.getDocumentPosition().row;
    var line = row + 1;
    var breakpoints = e.editor.session.getBreakpoints();
    var exists = breakpoints[row] != null;

    if (exists) {
      removeBreakpoint(line);
    } else {
      addBreakpoint(line);
    }

    e.stop();
  });

  $scope.$on('active-frame', function(event, frame) {
    // TODO: Avoid requesting source constantly if we already have it locally.
    // TODO: Cache source locally (in-mem, localStorage).
    $http.get('/source', { params: { path: frame.path } })
      .success(function(res) {
        $scope.currentSource = res;
        self.editor.setValue($scope.currentSource, 100);
        setActiveLine(frame.line);
      });
  });

  function setActiveLine(line) {
    if (!self.editor)
      return;

    setTimeout(function() {
      self.editor.scrollToLine(line, true, true, function() {});

      var lineText = self.editor.session.getLine(line - 1);
      var endCol = lineText.length;
      var startCol = 1;
      var match = /\S/.exec(lineText);
      if (match) {
        startCol = match.index;
      }

      if (self.activeMarker != null) {
        self.editor.session.removeMarker(self.activeMarker);
      }

      var aceRange = ace.require('ace/range').Range;
      var range = new aceRange(line - 1, startCol, line - 1, endCol);
      self.activeMarker = self.editor.session.addMarker(range, 'live-command', 'text');
    }, 0);
  };

  function addBreakpoint(line) {
    var params = { file: $scope.activeFrame.path, line: line };
    $http.post('/breakpoints', params)
      .success(function(res) {
        var row = line - 1;
        self.editor.session.setBreakpoint(row);

        var breakpointId = res.id;
        self.breakpoints[line] = breakpointId;
      });
  }

  function removeBreakpoint(line) {
    var breakpointId = self.breakpoints[line];
    if (breakpointId == null) {
      return;
    }

    $http.delete('/breakpoints/' + breakpointId)
      .success(function(res) {
        var row = line - 1;
        self.editor.session.clearBreakpoint(row);

        delete self.breakpoints[line];
      });
  }

  function updateBreakpoints() {
    $http.get('/breakpoints')
      .success(function(res) {
        for (var i = 0; i < res.length; ++i) {
          var breakpoint = res[i];
          var row = breakpoint.line - 1;
          self.editor.session.setBreakpoint(row);
          self.breakpoints[breakpoint.line] = breakpoint.id;
        }
      });
  }

  updateBreakpoints();
});

app.controller('ExpressionEditCtrl', function($scope, $http) {
  // TODO: Should be a directive?
  var editor = ace.edit('expr-editor');
  editor.renderer.setShowGutter(false);
  editor.renderer.setShowPrintMargin(false);
  editor.setValue('> ');
  editor.navigateLineEnd();
  editor.navigateRight(1);
  editor.session.setUseWrapMode(true);

  editor.keyBinding.realOnCommandKey = editor.keyBinding.onCommandKey;
  editor.keyBinding.onCommandKey = function(e, hashId, keyCode) {
    if (e.ctrlKey && (keyCode == 76)) {
      editor.setValue('> ');
      editor.navigateLineEnd();
      editor.navigateRight(1);
      e.preventDefault();
    } else if (keyCode == 13) {
      var lineNumber = editor.selection.getCursor().row;
      var line = editor.session.getLine(lineNumber);
      var match = /\s*>\s*(.*)/.exec(line);
      if (match) {
        var expr = match[1];
        var params = { expr: match[1], frame: getFrameIndex($scope.activeFrame) };
        $http.put('/eval', params)
          .success(function(res) {
            var result = res.success || res.failure;
            editor.insert(result);
            editor.insert('\n> ');
          });
      }
    } else {
      this.realOnCommandKey(e, hashId, keyCode);
    }
  }

  function getFrameIndex(frame) {
    var frames = $scope.activeThread.backtrace;
    for (var i = 0; i < frames.length; ++i) {
      if (frames[i] == frame) {
        return i;
      }
    }

    return null;
  }
});
<commit_msg>Better handling of source refresh on frame change.<commit_after>var app = angular.module('rdb', [])

app.controller('MainCtrl', function($scope, $http) {
  var self = this;

  $scope.process = null;
  $scope.running = true;
  $scope.activeThread = null;
  $scope.activeFrame = null;
  $scope.locals = {};
  self.liveThread = null;

  var source = new EventSource('/events');
  source.addEventListener('message', function(e) {
    $scope.$apply(function() {
      var message = JSON.parse(e.data);
      if (message.event == 'breakpoint') {
        updateThreads();
        updateRunning();
      }
    });
  }, false);

  $scope.showSettings = function() {
  };

  $scope.pause = function() {
    $http.put('/pause')
      .success(function(res) {
        $scope.running = res.running;
        updateThreads();
      });
  };

  $scope.resume = function() {
    $http.put('/resume')
      .success(function(res) {
        $scope.running = res.running;
      });
  };

  $scope.stepIn = function() {
    $http.put('/step-in')
      .success(function(res) {
        updateThreads();
        updateLocals();
      });
  };

  $scope.stepOver = function() {
    $http.put('/step-over')
      .success(function(res) {
        updateThreads();
        updateLocals();
      });
  };

  $scope.stepOut = function() {
    $http.put('/step-out')
      .success(function(res) {
        updateThreads();
        updateLocals();
      });
  };

  $scope.openFile = function(path, line) {
    $http.post('/open', { path: path, line: line })
      .success(function() {
      });
  }

  $scope.setActiveThread = function(thread) {
    $scope.activeThread = thread;
    $scope.setActiveFrame(thread.backtrace[0]);
  };

  $scope.setActiveFrame = function(frame) {
    $scope.activeFrame = frame;
  };

  function updateThreads() {
    $http.get('/threads')
      .success(function(res) {
        $scope.threads = res;

        for (var i = 0; i < $scope.threads.length; ++i) {
          var thread = $scope.threads[i];
          if (thread.main) {
            self.liveThread = thread;
            $scope.setActiveThread(self.liveThread);
            break;
          }
        }
      });
  }

  function updateLocals() {
    $http.get('/locals')
      .success(function(res) {
        $scope.locals = res;
      });
  }

  function updateRunning() {
    $http.get('/running')
      .success(function(res) {
        $scope.running = res.running;
      });
  }

  function connect() {
    $http.get('/process')
      .success(function(res) {
        $scope.process = res.process;
      });

    updateRunning();
    updateThreads();
    updateLocals();
  }

  connect();
});

app.controller('SourceEditCtrl', function($scope, $http) {
  var self = this;

  // Maps line number to breakpoint ID.
  self.breakpoints = {};
  self.activeMarker = null;

  self.editor = ace.edit('source-editor');
  self.editor.setTheme('ace/theme/clouds');
  self.editor.session.setMode("ace/mode/ruby");
  self.editor.setReadOnly(true);
  self.editor.setShowPrintMargin(false);

  self.editor.on('guttermousedown', function(e) {
    var target = e.domEvent.target;
    if (target.className.indexOf('ace_gutter-cell') < 0) {
      return;
    }

    var row = e.getDocumentPosition().row;
    var line = row + 1;
    var breakpoints = e.editor.session.getBreakpoints();
    var exists = breakpoints[row] != null;

    if (exists) {
      removeBreakpoint(line);
    } else {
      addBreakpoint(line);
    }

    e.stop();
  });

  $scope.$watch('activeFrame', function(newFrame, oldFrame) {
    if (newFrame == null) {
      return;
    }

    if ((oldFrame == null) || (newFrame.path != oldFrame.path)) {
      // TODO: Avoid requesting source constantly if we already have it locally.
      // TODO: Cache source locally (in-mem, localStorage).
      $http.get('/source', { params: { path: newFrame.path } })
        .success(function(res) {
          $scope.currentSource = res;
          self.editor.setValue($scope.currentSource, newFrame.line);
          setActiveLine(newFrame.line);
        });
    } else {
      setActiveLine(newFrame.line);
    }
  });

  function setActiveLine(line) {
    if (!self.editor)
      return;

    setTimeout(function() {
      self.editor.scrollToLine(line, true, true, function() {});

      var lineText = self.editor.session.getLine(line - 1);
      var endCol = lineText.length;
      var startCol = 1;
      var match = /\S/.exec(lineText);
      if (match) {
        startCol = match.index;
      }

      if (self.activeMarker != null) {
        self.editor.session.removeMarker(self.activeMarker);
      }

      var aceRange = ace.require('ace/range').Range;
      var range = new aceRange(line - 1, startCol, line - 1, endCol);
      self.activeMarker = self.editor.session.addMarker(range, 'live-command', 'text');
    }, 0);
  };

  function addBreakpoint(line) {
    var params = { file: $scope.activeFrame.path, line: line };
    $http.post('/breakpoints', params)
      .success(function(res) {
        var row = line - 1;
        self.editor.session.setBreakpoint(row);

        var breakpointId = res.id;
        self.breakpoints[line] = breakpointId;
      });
  }

  function removeBreakpoint(line) {
    var breakpointId = self.breakpoints[line];
    if (breakpointId == null) {
      return;
    }

    $http.delete('/breakpoints/' + breakpointId)
      .success(function(res) {
        var row = line - 1;
        self.editor.session.clearBreakpoint(row);

        delete self.breakpoints[line];
      });
  }

  function updateBreakpoints() {
    $http.get('/breakpoints')
      .success(function(res) {
        for (var i = 0; i < res.length; ++i) {
          var breakpoint = res[i];
          var row = breakpoint.line - 1;
          self.editor.session.setBreakpoint(row);
          self.breakpoints[breakpoint.line] = breakpoint.id;
        }
      });
  }

  updateBreakpoints();
});

app.controller('ExpressionEditCtrl', function($scope, $http) {
  // TODO: Should be a directive?
  var editor = ace.edit('expr-editor');
  editor.renderer.setShowGutter(false);
  editor.renderer.setShowPrintMargin(false);
  editor.setValue('> ');
  editor.navigateLineEnd();
  editor.navigateRight(1);
  editor.session.setUseWrapMode(true);

  editor.keyBinding.realOnCommandKey = editor.keyBinding.onCommandKey;
  editor.keyBinding.onCommandKey = function(e, hashId, keyCode) {
    if (e.ctrlKey && (keyCode == 76)) {
      editor.setValue('> ');
      editor.navigateLineEnd();
      editor.navigateRight(1);
      e.preventDefault();
    } else if (keyCode == 13) {
      var lineNumber = editor.selection.getCursor().row;
      var line = editor.session.getLine(lineNumber);
      var match = /\s*>\s*(.*)/.exec(line);
      if (match) {
        var expr = match[1];
        var params = { expr: match[1], frame: getFrameIndex($scope.activeFrame) };
        $http.put('/eval', params)
          .success(function(res) {
            var result = res.success || res.failure;
            editor.insert(result);
            editor.insert('\n> ');
          });
      }
    } else {
      this.realOnCommandKey(e, hashId, keyCode);
    }
  }

  function getFrameIndex(frame) {
    var frames = $scope.activeThread.backtrace;
    for (var i = 0; i < frames.length; ++i) {
      if (frames[i] == frame) {
        return i;
      }
    }

    return null;
  }
});
<|endoftext|>