<commit_before>Meteor.methods({
    deactivateJob: function(jobId, filled) {
        check(jobId, String);
        check(filled, Boolean);

        var job = Jobs.findOne({
            _id: jobId
        });
        if (!job)
            throw new Meteor.Error("Could not find job.");

        if (this.userId !== job.userId)
            throw new Meteor.Error("You can only deactivate your own job.");

		if (job.status !== "active")
            throw new Meteor.Error("You can only deactivate an active job.");

        Jobs.update({
            _id: jobId
        }, {
            $set: {
            	status:(filled ? "filled" : "inactive")
            }
        });

    },
    adminSetJobStatus: function(jobId, status) {
        check(jobId, String);
        check(status, String);

        var job = Jobs.findOne({
            _id: jobId
        });
        if (!job)
            throw new Meteor.Error("Could not find job.");

        if (!Roles.userIsInRole(this.userId, ['admin']))
            throw new Meteor.Error("Only admins can set job status");

        var setObject = {
            status: status
        };

        if (Meteor.isServer && status === "active" && job.featured())
            setObject.featuredThrough = moment().add(30,"days").toDate();

        Jobs.update({
            _id: jobId
        }, {
            $set: setObject
        });

    },
    adminSetProfileStatus: function(profileId, status) {
        check(profileId, String);
        check(status, String);

        var job = Profiles.findOne({
            _id: profileId
        });
        if (!job)
            throw new Meteor.Error("Could not find profile.");

        if (!Roles.userIsInRole(this.userId, ['admin']))
            throw new Meteor.Error("Only admins can set profile status");

        var setObject = {
            status: status
        };

        Profiles.update({
            _id: profileId
        }, {
            $set: setObject
        });

    },
    createFeaturedJobCharge: function(tokenId, jobId) {
        check(tokenId, String);
        check(jobId, String);

        var job = Jobs.findOne({_id:jobId});
        if(!job)
        	throw new Meteor.Error("Could not find job.");

        if(job.userId !== this.userId)
        	throw new Meteor.Error("You can only pay for you own job post.");

        if(Meteor.isServer){
        	var result = Stripe.charges.create({
	        	source:tokenId,
	        	amount:10000,
	        	currency:"usd",
	        	description:"We Work Meteor - Featured Job Post - 30 Days"
	        });

	        if(result && result.status === "succeeded"){
	        	Jobs.update({_id:job._id},{
	        		$set:{
	        			featuredThrough:moment().add(30,"days").toDate()
	        		},
	        		$push:{
	        			featuredChargeHistory:result.id
	        		}
	        	});
	        }else{
	        	throw new Meteor.Error("Payment Failed!", "Stripe result not as expected", JSON.stringify(result));
	        }
        }else{
        	Jobs.update({
	            _id: jobId
	        }, {
	            $set: {
	                featuredThrough: moment().add(30, "days").toDate()
	            }
	        });
        }
    }
});
<commit_msg>fixes #108<commit_after>Meteor.methods({
    deactivateJob: function(jobId, filled) {
        check(jobId, String);
        check(filled, Boolean);

        var job = Jobs.findOne({
            _id: jobId
        });
        if (!job)
            throw new Meteor.Error("Could not find job.");

        if (this.userId !== job.userId)
            throw new Meteor.Error("You can only deactivate your own job.");

		if (job.status !== "active")
            throw new Meteor.Error("You can only deactivate an active job.");

        Jobs.update({
            _id: jobId
        }, {
            $set: {
            	status:(filled ? "filled" : "inactive")
            }
        });

    },
    adminSetJobStatus: function(jobId, status) {
        check(jobId, String);
        check(status, String);

        var job = Jobs.findOne({
            _id: jobId
        });
        if (!job)
            throw new Meteor.Error("Could not find job.");

        if (!Roles.userIsInRole(this.userId, ['admin']))
            throw new Meteor.Error("Only admins can set job status");

        var setObject = {
            status: status
        };

        if (Meteor.isServer && status === "active" && job.featured())
            setObject.featuredThrough = moment().add(30,"days").toDate();

        Jobs.update({
            _id: jobId
        }, {
            $set: setObject
        });

    },
    adminSetProfileStatus: function(profileId, status) {
        check(profileId, String);
        check(status, String);

        var job = Profiles.findOne({
            _id: profileId
        });
        if (!job)
            throw new Meteor.Error("Could not find profile.");

        if (!Roles.userIsInRole(this.userId, ['admin']))
            throw new Meteor.Error("Only admins can set profile status");

        var setObject = {
            status: status
        };

        Profiles.update({
            _id: profileId
        }, {
            $set: setObject
        });

    },
    createFeaturedJobCharge: function(tokenId, jobId) {
        check(tokenId, String);
        check(jobId, String);

        var job = Jobs.findOne({_id:jobId});
        if(!job)
        	throw new Meteor.Error("Could not find job.");

        if(job.userId !== this.userId)
        	throw new Meteor.Error("You can only pay for you own job post.");

        if(Meteor.isServer){
        	var result = Stripe.charges.create({
	        	source:tokenId,
	        	amount:10000,
	        	currency:"usd",
	        	description:"We Work Meteor - Featured Job Post - 30 Days"
	        });

            if(result && (result.status === "succeeded" || result.status === "paid")){ //'paid' status is not in stripe docs, but is occuring - see https://github.com/nate-strauser/wework/issues/108
	        	Jobs.update({_id:job._id},{
	        		$set:{
	        			featuredThrough:moment().add(30,"days").toDate()
	        		},
	        		$push:{
	        			featuredChargeHistory:result.id
	        		}
	        	});
	        }else{
	        	throw new Meteor.Error("Payment Failed!", "Stripe result not as expected", JSON.stringify(result));
	        }
        }else{
        	Jobs.update({
	            _id: jobId
	        }, {
	            $set: {
	                featuredThrough: moment().add(30, "days").toDate()
	            }
	        });
        }
    }
});
<|endoftext|>


<commit_before>var log = document.querySelector("#log");
var LogType = {
    Error: 0,
    Header: 1,
    Info: 2,
    SubHeader: 3,
    Pass: 4,
    Text: 5,
    Warning: 6
}

function assert(obj, action, property, value) {
    // Test success
    if(obj) {
        // Success
        if(obj.hasOwnProperty(property) && obj[property] == value) {
            writeToLog("Method '" + action + "' passed the test.", LogType.Pass);
        }
        // Error
        else {
            writeToLog("Method '" + action + "' failed the test.", LogType.Error);
            writeToLog(obj.response, LogType.Error);
        }
    }
    else {
        writeToLog("Error: Object does not exist.", LogType.Error);
    }
}

function cbAll_Click(cb) {
    var isChecked = cb.checked;

    // Parse the check boxes
    var checkboxes = document.querySelectorAll("input[name='test']");
    for(var i=0; i<checkboxes.length; i++) {
        checkboxes[i].checked = isChecked;
    }
}

function runTests() {
    // Clear the log
    document.querySelector("#log").innerHTML = "";

    // Parse the check boxes
    var checkboxes = document.querySelectorAll("input[name='test']");
    for(var i=0; i<checkboxes.length; i++) {
        // Ensure it's checked
        if(checkboxes[i].checked) {
            // Run the selected test
            switch(checkboxes[i].value) {
                case "file":
                    testFile();
                break;
                case "list":
                    testList();
                    break;
                case "listAsync":
                    testListAsync();
                break;
                case "security":
                    testSecurity();
                break;
            }
        }
    }
}

function testContentType(list) {
    // Log
    writeToLog("Content Type", LogType.Header);

    // Log
    writeToLog("Creating the content type", LogType.SubHeader);

    // Create the content type
    var web = new $REST.Web();
    var ct = web.ContentTypes()
        .add({
            Name: "SPRest" + SP.Guid.newGuid().toString()
        })
        .executeAndWait();

    // Test
    assert(ct, "create", "existsFl", true);

    // See if the content type exists
    if(ct.existsFl) {
        // Log
        writeToLog("Updating the content type", LogType.SubHeader);

        // Update the content type
        ct.update({
            Group: "Dev"
        }).executeAndWait();

        // Read the content types
        ct = (new $REST.Web()).ContentTypes(ct.Id.StringValue).executeAndWait();

        // Test
        assert(ct, "update", "Group", "Dev");

        // Log
        writeToLog("Creating a field", LogType.SubHeader);

        // Get the test field
        var field = (new $REST.Web()).Fields("SPRestText").executeAndWait();
        if(!field.existsFl) {
            // Create the test field
            field = web.Fields().createFieldAsXml('<Field ID="{AA3AF8EA-2D8D-4345-8BD9-6017205F2212}" Name="SPRestText" StaticName="SPRestText" DisplayName="SPREST Test Text" Type="Text" />').executeAndWait();
        }

        // Test
        assert(field, "create field", "existsFl", true);

        // Log
        writeToLog("Add List Field", LogType.SubHeader);

        // Add the field to the list
        var listField = list.Fields().createFieldAsXml('<Field ID="{AA3AF8EA-2D8D-4345-8BD9-6017205F2212}" Name="SPRestText" StaticName="SPRestText" DisplayName="SPREST Test Text" Type="Text" />').executeAndWait();

        // Test
        assert(listField, "add list field", "existsFl", true);

        // Log
        writeToLog("Add Field Link", LogType.SubHeader);

        // Note - This is a bug with the REST api
        writeToLog("Note - Failure to add a field link is a known bug with the REST API.", LogType.Info);

        // Add the field to the content type
        var fieldLink = ct.FieldLinks().add({ FieldInternalName: field.InternalName }).executeAndWait();

        // Test
        assert(fieldLink, "add field link", "existsFl", true);

        // Log
        writeToLog("Add List Content Type", LogType.SubHeader);

        // Add the content type to the list
        var ctList = list.ContentTypes().addAvailableContentType(ct.Id.StringValue).executeAndWait();

        // Test
        assert(ctList, "add list content type", "existsFl", true);

        // Log
        writeToLog("Deleting the list content type", LogType.SubHeader);

        // Delete the content type from the list
        ctList = ctList.delete().executeAndWait();

        // Test
        assert(ctList.d, "delete", "DeleteObject", null);

        // Log
        writeToLog("Deleting the content type", LogType.SubHeader);

        // Delete the content type
        ct = ct.delete().executeAndWait();

        // Test
        assert(ct.d, "delete", "DeleteObject", null);

        // Log
        writeToLog("Deleting the field", LogType.SubHeader);

        // Delete the content type
        field = field.delete().executeAndWait();

        // Test
        assert(field.d, "delete", "DeleteObject", null);
    }
    else {
        // Log
        writeToLog("Content Type was not created.", LogType.Error);
        writeToLog(ct.response, LogType.Error);
    }
}

function testField() {
    // TO DO
}

function testFile() {
    // Log
    writeToLog("File", LogType.Header);

    // Log
    writeToLog("Getting this file.", LogType.SubHeader);

    // Get this file
    var file = (new $REST.Web()).getFileByServerRelativeUrl(_spPageContextInfo.serverRequestPath).executeAndWait();

    // Test
    assert(file, "read file", "Exists", true);

    // Log
    writeToLog("Getting the parent folder", LogType.SubHeader);

    // Get the parent folder
    var folder = (new $REST.Web()).getFolderByServerRelativeUrl(file.ServerRelativeUrl.substr(0, file.ServerRelativeUrl.length - file.Name.length - 1)).executeAndWait();

    // Test
    assert(folder, "read folder", "Exists", true);

    // Log
    writeToLog("Create a folder", LogType.SubHeader);

    // Create a sub-folder
    var subFolder = folder.Folders().add("Test").executeAndWait();

    // Test
    assert(subFolder, "create folder", "Exists", true);

    // Log
    writeToLog("Copy a file", LogType.SubHeader);

    // Read the content types of this file
    var fileContent = file.content().executeAndWait();

    // Test
    assert(fileContent, "read file buffer", "existsFl", true);

    // Note - The content will be a string, since I'm executing this synchronously.
    // We will need to convert the content to a buffer
    var buffer = new ArrayBuffer(fileContent.length * 2);
    var bufferView = new Uint16Array(buffer);
    for(var i=0; i<fileContent.length; i++) {
        bufferView[i] = fileContent.charCodeAt(i);
    }

    // Copy the file
    file = subFolder.Files().add(true, "test.aspx", buffer).executeAndWait();

    // Test
    assert(file, "copy file", "Exists", true);

    // Log
    writeToLog("Delete the file", LogType.SubHeader);

    // Delete the file
    file = file.delete().executeAndWait();

    // Test
    assert(file.d, "delete file", "DeleteObject", null);

    // Log
    writeToLog("Delete the folder", LogType.SubHeader);

    // Delete the sub-folder
    subFolder = subFolder.delete().executeAndWait();

    // Test
    assert(subFolder.d, "delete folder", "DeleteObject", null);
}

function testList() {
    // Log
    writeToLog("List", LogType.Header);

    // Log
    writeToLog("Creating the list", LogType.SubHeader);

    // Create the list
    var web = new $REST.Web();
    var list = web.Lists()
        .add({
            BaseTemplate: 100,
            Description: "This is a test list.",
            Title: "SPRest" + SP.Guid.newGuid().toString()
        })
        .executeAndWait();

    // Test
    assert(list, "create", "existsFl", true);

    // See if the list exists
    if(list.existsFl) {
        // Log
        writeToLog("Updating the list", LogType.SubHeader);

        // Update the list
        list.update({
            Description: "Updated description"
        }).executeAndWait();

        // Read the updated list
        list = new $REST.List(list.Title).executeAndWait();

        // Test
        assert(list, "update", "Description", "Updated description");

        // Test the list item
        testListItem(list);

        // Test the list items
        testListItems(list);

        // Test the list view
        testListView(list);

        // Test the content type
        testContentType(list);

        // Log
        writeToLog("Deleting the list", LogType.SubHeader);

        // Delete the list
        list = list.delete().executeAndWait();

        // Test
        assert(list.d, "delete", "DeleteObject", null);
    }
    else {
        // Log
        writeToLog("List was not created.", LogType.Error);
        writeToLog(list.response, LogType.Error);
    }
}

function testListAsync() {
    // Log
    writeToLog("List", LogType.Header);

    // Log
    writeToLog("Creating the list", LogType.SubHeader);

    // Create a list
    (new $REST.Web()).Lists().add({
        BaseTemplate: 100,
        Description: "This is a test list.",
        Title: "SPRest" + SP.Guid.newGuid().toString()
    }).execute(function(list) {
        // Test
        assert(list, "create", "existsFl", true);

        // Log
        writeToLog("Creating the list items", LogType.SubHeader);

        // Create a counter
        for(var i=0; i<5; i++) {
            // Get the item collection
            list.Items()
                // Add the item
                .add({ Title: "New Item " + i})
                // Execute and wait for the previous item
                .execute(true);
        }

        // Wait for the requests to complete
        list.done(function() {
            var idx = 0;

            // Assert the items
            for(var i=arguments.length-5; i<arguments.length; i++) {
                // Test
                assert(arguments[i], "create item " + idx, "Title", "New Item " + idx++);
            }

            // Log
            writeToLog("Deleting the list", LogType.SubHeader);

            // Delete the list
            list.delete().execute(function(result) {
                // Test
                assert(result.d, "delete", "DeleteObject", null);
            });
        });
    });
}

function testListItem(list) {
    // Log
    writeToLog("List Item", LogType.Header);

    // Log
    writeToLog("Creating the list item", LogType.SubHeader);

    // Create the item
    item = list.Items().add({
        Title: "New Item"
    }).executeAndWait();
    assert(item, "create", "existsFl", true);

    // Log
    writeToLog("Update the list item", LogType.SubHeader);

    // Update the item
    item.update({
        Title: "Updated Item"
    }).executeAndWait();

    // Read the updated item
    item = (new $REST.List(list.Title)).Items(item.ID).executeAndWait();

    // Test
    assert(item, "update", "Title", "Updated Item");

    // Log
    writeToLog("Deleting the list item", LogType.SubHeader);

    // Delete the item
    item = item.delete().executeAndWait();

    // Test
    assert(item.d, "delete", "DeleteObject", null);
}

function testListItems(list) {
    var items = [];
    var maxNumber = 5;

    // Log
    writeToLog("List Items", LogType.Header);

    // Log
    writeToLog("Creating the list items", LogType.SubHeader);

    // Create the items
    for(var i=1; i<=maxNumber; i++) {
        var title = "New Item " + i;

        // Create the item
        var item = list.Items().add({
            Title: title
        }).executeAndWait();

        // Test
        assert(item, "create item " + i, "Title", title);

        // Save a reference to the items
        items.push(item);
    }

    // Log
    writeToLog("Query the list items", LogType.SubHeader);

    // Generate the caml query
    var template = "<{{Type}}><FieldRef Name='ID' /><Value Type='Integer'>{{Value}}</Value></{{Type}}>";
    var caml = "<Query><Where><And>{{Min}}{{Max}}</And></Where></Query>"
        .replace(/{{Min}}/g, template.replace(/{{Type}}/g, "Geq").replace(/{{Value}}/g, items[0].ID))
        .replace(/{{Max}}/g, template.replace(/{{Type}}/g, "Leq").replace(/{{Value}}/g, items[items.length-1].ID));

    // Get the items
    items = (new $REST.List(list.Title, false)).getItemsByQuery(caml).executeAndWait();

    // Test
    assert(items.results, "query list items", "length", maxNumber);
}

function testListView(list) {
    // Log
    writeToLog("List View", LogType.Header);

    // Log
    writeToLog("Creating the list view", LogType.SubHeader);

    // Create the item
    view = list.Views().add({
        Title: "New View",
        ViewQuery: '<OrderBy><FieldRef Name="Title" /></OrderBy>'
    }).executeAndWait();
    assert(view, "create", "existsFl", true);

    // Log
    writeToLog("Deleting the list view", LogType.SubHeader);

    // Delete the item
    view = view.delete().executeAndWait();

    // Test
    assert(view.d, "delete", "DeleteObject", null);
}

function testSecurity() {
    // Log
    writeToLog("Security", LogType.Header);

    // Log
    writeToLog("Querying the permissions", LogType.SubHeader);

    // Get the web
    var web = new $REST.Web();

    // Get the 'View Only' permission
    var permission = web.RoleDefinitions().query({ Filter: "Name eq 'View Only'" }).executeAndWait();

    // Test
    assert(permission, "query", "existsFl", true);

    // Ensure the permission exists
    if(!permission.existsFl) { return; }

    // Log
    writeToLog("Creating the site group", LogType.SubHeader);

    // Get the test group
    var group = web.SiteGroups("Test Group").executeAndWait();
    if(!group.existsFl) {
        // Create a new group
        group = web.SiteGroups().add({ Title: "Test Group" }).executeAndWait();
    }

    // Test
    assert(group, "create group", "existsFl", true);

    // Log
    writeToLog("Adding user to site group", LogType.SubHeader);

    // Ensure the permission exists
    if(!group.existsFl) { return; }

    // Add the current user to the group
    var user = group.Users().add({ LoginName: web.CurrentUser().executeAndWait().LoginName }).executeAndWait();

    // Test
    assert(user, "create user", "existsFl", true);

    // Remove the user from the group
    user = group.Users().removeByLoginName(user.LoginName).executeAndWait();

    // Test
    assert(user.d, "delete user", "RemoveByLoginName", null);

    // Log
    writeToLog("Deleting the group", LogType.SubHeader);

    // Delete the group
    group = web.SiteGroups().removeById(group.Id).executeAndWait();

    // Test
    assert(group.d, "delete group", "RemoveById", null);
}

function writeToLog(text, logType) {
    var el = "";

    // Ensure text exists
    if(typeof(text) !== "string" || text == "") { return; }

    // Set the element tag
    switch(logType) {
        case LogType.Header:
            el = "h1";
        break;
        case LogType.SubHeader:
            el = "h3";
        break;
        default:
            el = "p";
        break;
    }

    // Set the style
    switch(logType) {
        case LogType.Error:
            text = "" + text + "";
        break;
        case LogType.Info:
            text = "" + text + "";
        break;
        case LogType.Pass:
            text = "" + text + "";
        break;
        case LogType.Warning:
            text = "" + text + "";
        break;
    }

    // Append the text to the log
    log.innerHTML += "<{{el}}>{{text}}</{{el}}>".replace("{{el}}", el).replace("{{text}}", text);
}
<commit_msg>Updated the test script.<commit_after>var log = document.querySelector("#log");
var LogType = {
    Error: 0,
    Header: 1,
    Info: 2,
    SubHeader: 3,
    Pass: 4,
    Text: 5,
    Warning: 6
}

function assert(obj, action, property, value) {
    // Test success
    if (obj) {
        // Success
        if (obj.hasOwnProperty(property) && obj[property] == value) {
            writeToLog("Method '" + action + "' passed the test.", LogType.Pass);
        }
        // Error
        else {
            writeToLog("Method '" + action + "' failed the test.", LogType.Error);
            writeToLog(obj.response, LogType.Error);
        }
    }
    else {
        writeToLog("Error: Object does not exist.", LogType.Error);
    }
}

function cbAll_Click(cb) {
    var isChecked = cb.checked;

    // Parse the check boxes
    var checkboxes = document.querySelectorAll("input[name='test']");
    for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].checked = isChecked;
    }
}

function runTests() {
    // Clear the log
    document.querySelector("#log").innerHTML = "";

    // Parse the check boxes
    var checkboxes = document.querySelectorAll("input[name='test']");
    for (var i = 0; i < checkboxes.length; i++) {
        // Ensure it's checked
        if (checkboxes[i].checked) {
            // Run the selected test
            switch (checkboxes[i].value) {
                case "file":
                    testFile();
                    break;
                case "list":
                    testList();
                    break;
                case "listAsync":
                    testListAsync();
                    break;
                case "security":
                    testSecurity();
                    break;
            }
        }
    }
}

function testContentType(list) {
    // Log
    writeToLog("Content Type", LogType.Header);

    // Log
    writeToLog("Creating the content type", LogType.SubHeader);

    // Create the content type
    var web = new $REST.Web();
    var ct = web.ContentTypes()
        .add({
            Name: "SPRest" + SP.Guid.newGuid().toString()
        })
        .executeAndWait();

    // Test
    assert(ct, "create", "existsFl", true);

    // See if the content type exists
    if (ct.existsFl) {
        // Log
        writeToLog("Updating the content type", LogType.SubHeader);

        // Update the content type
        ct.update({
            Group: "Dev"
        }).executeAndWait();

        // Read the content types
        ct = $REST.Web().ContentTypes(ct.Id.StringValue).executeAndWait();

        // Test
        assert(ct, "update", "Group", "Dev");

        // Log
        writeToLog("Creating a field", LogType.SubHeader);

        // Get the test field
        var field = $REST.Web().Fields("SPRestText").executeAndWait();
        if (!field.existsFl) {
            // Create the test field
            field = web.Fields().createFieldAsXml('<Field ID="{AA3AF8EA-2D8D-4345-8BD9-6017205F2212}" Name="SPRestText" StaticName="SPRestText" DisplayName="SPREST Test Text" Type="Text" />').executeAndWait();
        }

        // Test
        assert(field, "create field", "existsFl", true);

        // Log
        writeToLog("Add List Field", LogType.SubHeader);

        // Add the field to the list
        var listField = list.Fields().createFieldAsXml('<Field ID="{AA3AF8EA-2D8D-4345-8BD9-6017205F2212}" Name="SPRestText" StaticName="SPRestText" DisplayName="SPREST Test Text" Type="Text" />').executeAndWait();

        // Test
        assert(listField, "add list field", "existsFl", true);

        // Log
        writeToLog("Add Field Link", LogType.SubHeader);

        // Note - This is a bug with the REST api
        writeToLog("Note - Failure to add a field link is a known bug with the REST API.", LogType.Info);

        // Add the field to the content type
        var fieldLink = ct.FieldLinks().add({ FieldInternalName: field.InternalName }).executeAndWait();

        // Test
        assert(fieldLink, "add field link", "existsFl", true);

        // Log
        writeToLog("Add List Content Type", LogType.SubHeader);

        // Add the content type to the list
        var ctList = list.ContentTypes().addAvailableContentType(ct.Id.StringValue).executeAndWait();

        // Test
        assert(ctList, "add list content type", "existsFl", true);

        // Log
        writeToLog("Deleting the list content type", LogType.SubHeader);

        // Delete the content type from the list
        ctList = ctList.delete().executeAndWait();

        // Test
        assert(ctList.d, "delete", "DeleteObject", null);

        // Log
        writeToLog("Deleting the content type", LogType.SubHeader);

        // Delete the content type
        ct = ct.delete().executeAndWait();

        // Test
        assert(ct.d, "delete", "DeleteObject", null);

        // Log
        writeToLog("Deleting the field", LogType.SubHeader);

        // Delete the content type
        field = field.delete().executeAndWait();

        // Test
        assert(field.d, "delete", "DeleteObject", null);
    }
    else {
        // Log
        writeToLog("Content Type was not created.", LogType.Error);
        writeToLog(ct.response, LogType.Error);
    }
}

function testField() {
    // TO DO
}

function testFile() {
    // Log
    writeToLog("File", LogType.Header);

    // Log
    writeToLog("Getting this file.", LogType.SubHeader);

    // Get this file
    var file = $REST.Web().getFileByServerRelativeUrl(_spPageContextInfo.serverRequestPath).executeAndWait();

    // Test
    assert(file, "read file", "Exists", true);

    // Log
    writeToLog("Getting the parent folder", LogType.SubHeader);

    // Get the parent folder
    var folder = $REST.Web().getFolderByServerRelativeUrl(file.ServerRelativeUrl.substr(0, file.ServerRelativeUrl.length - file.Name.length - 1)).executeAndWait();

    // Test
    assert(folder, "read folder", "Exists", true);

    // Log
    writeToLog("Create a folder", LogType.SubHeader);

    // Create a sub-folder
    var subFolder = folder.Folders().add("Test").executeAndWait();

    // Test
    assert(subFolder, "create folder", "Exists", true);

    // Log
    writeToLog("Copy a file", LogType.SubHeader);

    // Read the content types of this file
    var fileContent = file.content().executeAndWait();

    // Test
    assert(fileContent, "read file buffer", "existsFl", true);

    // Note - The content will be a string, since I'm executing this synchronously.
    // We will need to convert the content to a buffer
    var buffer = new ArrayBuffer(fileContent.length * 2);
    var bufferView = new Uint16Array(buffer);
    for (var i = 0; i < fileContent.length; i++) {
        bufferView[i] = fileContent.charCodeAt(i);
    }

    // Copy the file
    file = subFolder.Files().add(true, "test.aspx", buffer).executeAndWait();

    // Test
    assert(file, "copy file", "Exists", true);

    // Log
    writeToLog("Delete the file", LogType.SubHeader);

    // Delete the file
    file = file.delete().executeAndWait();

    // Test
    assert(file.d, "delete file", "DeleteObject", null);

    // Log
    writeToLog("Delete the folder", LogType.SubHeader);

    // Delete the sub-folder
    subFolder = subFolder.delete().executeAndWait();

    // Test
    assert(subFolder.d, "delete folder", "DeleteObject", null);
}

function testList() {
    // Log
    writeToLog("List", LogType.Header);

    // Log
    writeToLog("Creating the list", LogType.SubHeader);

    // Create the list
    var web = new $REST.Web();
    var list = web.Lists()
        .add({
            BaseTemplate: 100,
            Description: "This is a test list.",
            Title: "SPRest" + SP.Guid.newGuid().toString()
        })
        .executeAndWait();

    // Test
    assert(list, "create", "existsFl", true);

    // See if the list exists
    if (list.existsFl) {
        // Log
        writeToLog("Updating the list", LogType.SubHeader);

        // Update the list
        list.update({
            Description: "Updated description"
        }).executeAndWait();

        // Read the updated list
        list = new $REST.List(list.Title).executeAndWait();

        // Test
        assert(list, "update", "Description", "Updated description");

        // Test the list item
        testListItem(list);

        // Test the list items
        testListItems(list);

        // Test the list view
        testListView(list);

        // Test the content type
        testContentType(list);

        // Log
        writeToLog("Deleting the list", LogType.SubHeader);

        // Delete the list
        list = list.delete().executeAndWait();

        // Test
        assert(list.d, "delete", "DeleteObject", null);
    }
    else {
        // Log
        writeToLog("List was not created.", LogType.Error);
        writeToLog(list.response, LogType.Error);
    }
}

function testListAsync() {
    // Log
    writeToLog("List", LogType.Header);

    // Log
    writeToLog("Creating the list", LogType.SubHeader);

    // Create a list
    $REST.Web().Lists().add({
        BaseTemplate: 100,
        Description: "This is a test list.",
        Title: "SPRest" + SP.Guid.newGuid().toString()
    }).execute(function (list) {
        // Test
        assert(list, "create", "existsFl", true);

        // Log
        writeToLog("Creating the list items", LogType.SubHeader);

        // Create a counter
        for (var i = 0; i < 5; i++) {
            // Get the item collection
            list.Items()
                // Add the item
                .add({ Title: "New Item " + i })
                // Execute and wait for the previous item
                .execute(true);
        }

        // Wait for the requests to complete
        list.done(function () {
            var idx = 0;

            // Assert the items
            for (var i = arguments.length - 5; i < arguments.length; i++) {
                // Test
                assert(arguments[i], "create item " + idx, "Title", "New Item " + idx++);
            }

            // Log
            writeToLog("Deleting the list", LogType.SubHeader);

            // Delete the list
            list.delete().execute(function (result) {
                // Test
                assert(result.d, "delete", "DeleteObject", null);
            });
        });
    });
}

function testListItem(list) {
    // Log
    writeToLog("List Item", LogType.Header);

    // Log
    writeToLog("Creating the list item", LogType.SubHeader);

    // Create the item
    item = list.Items().add({
        Title: "New Item"
    }).executeAndWait();
    assert(item, "create", "existsFl", true);

    // Log
    writeToLog("Update the list item", LogType.SubHeader);

    // Update the item
    item.update({
        Title: "Updated Item"
    }).executeAndWait();

    // Read the updated item
    item = $REST.List(list.Title).Items(item.ID).executeAndWait();

    // Test
    assert(item, "update", "Title", "Updated Item");

    // Log
    writeToLog("Deleting the list item", LogType.SubHeader);

    // Delete the item
    item = item.delete().executeAndWait();

    // Test
    assert(item.d, "delete", "DeleteObject", null);
}

function testListItems(list) {
    var items = [];
    var maxNumber = 5;

    // Log
    writeToLog("List Items", LogType.Header);

    // Log
    writeToLog("Creating the list items", LogType.SubHeader);

    // Create the items
    for (var i = 1; i <= maxNumber; i++) {
        var title = "New Item " + i;

        // Create the item
        var item = list.Items().add({
            Title: title
        }).executeAndWait();

        // Test
        assert(item, "create item " + i, "Title", title);

        // Save a reference to the items
        items.push(item);
    }

    // Log
    writeToLog("Query the list items", LogType.SubHeader);

    // Generate the caml query
    var template = "<{{Type}}><FieldRef Name='ID' /><Value Type='Integer'>{{Value}}</Value></{{Type}}>";
    var caml = "<Query><Where><And>{{Min}}{{Max}}</And></Where></Query>"
        .replace(/{{Min}}/g, template.replace(/{{Type}}/g, "Geq").replace(/{{Value}}/g, items[0].ID))
        .replace(/{{Max}}/g, template.replace(/{{Type}}/g, "Leq").replace(/{{Value}}/g, items[items.length - 1].ID));

    // Get the items
    items = $REST.List(list.Title, false).getItemsByQuery(caml).executeAndWait();

    // Test
    assert(items.results, "query list items", "length", maxNumber);
}

function testListView(list) {
    // Log
    writeToLog("List View", LogType.Header);

    // Log
    writeToLog("Creating the list view", LogType.SubHeader);

    // Create the item
    view = list.Views().add({
        Title: "New View",
        ViewQuery: '<OrderBy><FieldRef Name="Title" /></OrderBy>'
    }).executeAndWait();
    assert(view, "create", "existsFl", true);

    // Log
    writeToLog("Deleting the list view", LogType.SubHeader);

    // Delete the item
    view = view.delete().executeAndWait();

    // Test
    assert(view.d, "delete", "DeleteObject", null);
}

function testSecurity() {
    // Log
    writeToLog("Security", LogType.Header);

    // Log
    writeToLog("Querying the permissions", LogType.SubHeader);

    // Get the web
    var web = new $REST.Web();

    // Get the 'View Only' permission
    var permission = web.RoleDefinitions().query({ Filter: "Name eq 'View Only'" }).executeAndWait();

    // Test
    assert(permission, "query", "existsFl", true);

    // Ensure the permission exists
    if (!permission.existsFl) { return; }

    // Log
    writeToLog("Creating the site group", LogType.SubHeader);

    // Get the test group
    var group = web.SiteGroups("Test Group").executeAndWait();
    if (!group.existsFl) {
        // Create a new group
        group = web.SiteGroups().add({ Title: "Test Group" }).executeAndWait();
    }

    // Test
    assert(group, "create group", "existsFl", true);

    // Log
    writeToLog("Adding user to site group", LogType.SubHeader);

    // Ensure the permission exists
    if (!group.existsFl) { return; }

    // Add the current user to the group
    var user = group.Users().add({ LoginName: web.CurrentUser().executeAndWait().LoginName }).executeAndWait();

    // Test
    assert(user, "create user", "existsFl", true);

    // Remove the user from the group
    user = group.Users().removeByLoginName(user.LoginName).executeAndWait();

    // Test
    assert(user.d, "delete user", "RemoveByLoginName", null);

    // Log
    writeToLog("Deleting the group", LogType.SubHeader);

    // Delete the group
    group = web.SiteGroups().removeById(group.Id).executeAndWait();

    // Test
    assert(group.d, "delete group", "RemoveById", null);
}

function writeToLog(text, logType) {
    var el = "";

    // Ensure text exists
    if (typeof (text) !== "string" || text == "") { return; }

    // Set the element tag
    switch (logType) {
        case LogType.Header:
            el = "h1";
            break;
        case LogType.SubHeader:
            el = "h3";
            break;
        default:
            el = "p";
            break;
    }

    // Set the style
    switch (logType) {
        case LogType.Error:
            text = "" + text + "";
            break;
        case LogType.Info:
            text = "" + text + "";
            break;
        case LogType.Pass:
            text = "" + text + "";
            break;
        case LogType.Warning:
            text = "" + text + "";
            break;
    }

    // Append the text to the log
    log.innerHTML += "<{{el}}>{{text}}</{{el}}>".replace("{{el}}", el).replace("{{text}}", text);
}
<|endoftext|>


<commit_before>define(["solv/abstract/emitter"], function () {
	"use strict";

	describe("Emitter", function () {
		// TODO: write Emitter suite
	});
});<commit_msg>finishing Emitter test suite<commit_after>define(["solv/abstract/emitter"], function (Emitter) {
	"use strict";

	describe("Emitter", function () {
		var emitter,
			handler;

		beforeEach(function () {
			emitter = new Emitter();
			handler = jasmine.createSpy("handler");
		});

		it("should return a listenerKey from .on", function () {
			var listenerKey = emitter.on("message", handler);

			expect(listenerKey).toBeDefined();
		});

		it("should return a listenerKey from .once", function () {
			var listenerKey = emitter.once("message", handler);

			expect(listenerKey).toBeDefined();
		});

		it("should execute handler functions when event is triggered", function () {
			emitter.on("message", handler);
			emitter.trigger("message");

			expect(handler).toHaveBeenCalled();
		});

		it("should trigger event with options object", function () {
			emitter.on("message", handler);
			emitter.trigger("message");

			expect(handler).toHaveBeenCalled();
		});

		it("should pass additional trigger arguments to handler functions", function () {
			emitter.on("message", handler);
			emitter.trigger("message", 1, 2, 3);

			expect(handler).toHaveBeenCalledWith(1, 2, 3);
		});

		it("should validate additional arguments with params meta is passed", function () {
			var message = {
					name: "message",
					when: "a message is received",
					params: [{
						name: "status",
						type: "string"
					}, {
						name: "data",
						type: "object",
						required: false
					}]
				},
				data = {};

			emitter.on("message", handler);
			emitter.trigger(message, "success");
			emitter.trigger(message, "success", data);

			expect(wrongParams).toThrow();
			expect(handler).toHaveBeenCalledWith("success");
			expect(handler).toHaveBeenCalledWith("success", data);

			function wrongParams () {
				emitter.trigger(message, 1, 2, 3);
			}
		});

		it("should only execute handler function once when added with .once", function () {
			var listenerKey = emitter.once("message", handler);

			emitter.trigger("message");
			expect(handler).toHaveBeenCalled();

			emitter.trigger("message");
			expect(handler.calls.length).toBe(1);
		});

		it("should remove listeners added with .on", function () {
			var listenerKey = emitter.on("message", handler);
			emitter.off(listenerKey);
			emitter.trigger("message");

			expect(handler.calls.length).toBe(0);
		});

		it("should remove listeners added with .once", function () {
			var listenerKey = emitter.once("message", handler);
			emitter.off(listenerKey);
			emitter.trigger("message");

			expect(handler.calls.length).toBe(0);
		});

		it("should remove listeners by event name", function () {
			emitter.on("message", handler);
			emitter.off("message");
			emitter.trigger("message");

			expect(handler.calls.length).toBe(0);
		});

		it("should remove listeners by event name when added with once", function () {
			emitter.once("message", handler);
			emitter.off("message");
			emitter.trigger("message");

			expect(handler.calls.length).toBe(0);
		});

		it("should remove all listeners", function () {
			emitter.on("message", handler);
			emitter.off();
			emitter.trigger("message");

			expect(handler.calls.length).toBe(0);
		});

		it("should remove all listeners when added with once", function () {
			emitter.once("message", handler);
			emitter.off();
			emitter.trigger("message");

			expect(handler.calls.length).toBe(0);
		});

		it("should remove all listeners when more than one listener", function () {
			var listenerKey = emitter.on("message", handler);

			emitter.on("message", handler);
			emitter.once("message", handler);
			emitter.once("top-secret", handler);
			emitter.off();
			emitter.off(listenerKey);
			emitter.trigger("message");

			expect(handler.calls.length).toBe(0);
		});
	});
});<|endoftext|>


<commit_before>'use strict';

var Track = require('../lib').Track;
var assert = require('proclaim');

describe('Track', function() {
  var args = {
    userId: 'calvin@segment.io',
    sessionId: 'abc123',
    properties: {
      revenue: '$50',
      referrer: 'http://segment.io',
      username: 'calvinfo',
      email: 'test@segment.io'
    },
    options: {
      query: 'segmentio',
      traits: {
        someTrait: 'y'
      }
    }
  };

  var track = new Track(args);

  describe('.repeat()', function() {
    it('should proxy properties.repeat', function() {
      var msg = new Track({ properties: { repeat: true } });
      assert.strictEqual(msg.repeat(), true);
    });
  });

  describe('.type()', function() {
    it('should have the proper .type()', function() {
      assert.strictEqual(track.type(), 'track');
    });

    it('should equal .action()', function() {
      assert.strictEqual(track.type(), track.action());
    });
  });

  describe('.userId()', function() {
    it('should proxy the userId', function() {
      assert.strictEqual(track.userId(), args.userId);
    });
  });

  describe('.sessionId()', function() {
    it('should proxy the sessionId', function() {
      assert.strictEqual(track.sessionId(), args.sessionId);
    });
  });

  describe('.event()', function() {
    it('should proxy the event', function() {
      assert.strictEqual(track.event(), args.event);
    });
  });

  describe('.quantity()', function() {
    it('should return the quantity', function() {
      var track = new Track({ properties: { quantity: 2 } });
      assert.strictEqual(track.quantity(), 2);
    });

    it('should default quantity to 1', function() {
      var track = new Track({});
      assert.strictEqual(track.quantity(), 1);
    });
  });

  describe('.currency()', function() {
    it('should return the currency code', function() {
      var track = new Track({ properties: { currency: 'EUR' } });
      assert.strictEqual(track.currency(), 'EUR');
    });

    it('should default currency to `USD`', function() {
      var track = new Track({});
      assert.strictEqual(track.currency(), 'USD');
    });
  });

  describe('.subtotal()', function() {
    it('should get subtotal', function() {
      var track = new Track({ properties: { subtotal: 10 } });
      assert.strictEqual(track.subtotal(), 10);
    });

    it('should compute subtotal from total', function() {
      var track = new Track({ properties: { total: 10, tax: 2, shipping: 2 } });
      assert.strictEqual(track.subtotal(), 6);
    });

    it('should compute subtotal from .tax, .shipping, .discount and .total', function() {
      var track = new Track({ properties: { Total: 10, Tax: 2, Shipping: 2, Discount: 1 } });
      assert.strictEqual(track.subtotal(), 7);
    });

    it('should lookup .subtotal properly', function() {
      var track = new Track({ properties: { Subtotal: 10 } });
      assert.strictEqual(track.subtotal(), 10);
    });
  });

  describe('.category()', function() {
    it('should proxy category', function() {
      var track = new Track({ properties: { category: 'category' } });
      assert.strictEqual(track.category(), 'category');
    });
  });

  describe('.state()', function() {
    it('should proxy state', function() {
      var track = new Track({ properties: { state: 'state' } });
      assert.strictEqual(track.state(), 'state');
    });
  });

  describe('.city()', function() {
    it('should proxy city', function() {
      var track = new Track({ properties: { city: 'city' } });
      assert.strictEqual(track.city(), 'city');
    });
  });

  describe('.zip()', function() {
    it('should proxy zip', function() {
      var track = new Track({ properties: { zip: 'zip' } });
      assert.strictEqual(track.zip(), 'zip');
    });
  });

  describe('.tax()', function() {
    it('should proxy tax', function() {
      var track = new Track({ properties: { tax: 'tax' } });
      assert.strictEqual(track.tax(), 'tax');
    });
  });

  describe('.name()', function() {
    it('should proxy name', function() {
      var track = new Track({ properties: { name: 'name' } });
      assert.strictEqual(track.name(), 'name');
    });
  });

  describe('.country()', function() {
    it('should proxy country', function() {
      var track = new Track({ properties: { country: 'country' } });
      assert.strictEqual(track.country(), 'country');
    });

    it('should proxy context.traits', function() {
      var track = new Track({
        context: {
          traits: {
            address: {
              country: 'country'
            }
          }
        }
      });

      assert.strictEqual(track.country(), 'country');
    });
  });

  describe('.price()', function() {
    it('should proxy price', function() {
      var track = new Track({ properties: { price: 'price' } });
      assert.strictEqual(track.price(), 'price');
    });
  });

  describe('.total()', function() {
    it('should proxy total', function() {
      var track = new Track({ properties: { total: 'total' } });
      assert.strictEqual(track.total(), 'total');
    });
  });

  describe('.coupon()', function() {
    it('should proxy coupon', function() {
      var track = new Track({ properties: { coupon: 'coupon' } });
      assert.strictEqual(track.coupon(), 'coupon');
    });
  });

  describe('.shipping()', function() {
    it('should proxy shipping', function() {
      var track = new Track({ properties: { shipping: 'shipping' } });
      assert.strictEqual(track.shipping(), 'shipping');
    });
  });

  describe('.discount()', function() {
    it('should proxy discount', function() {
      var track = new Track({ properties: { discount: 'discount' } });
      assert.strictEqual(track.discount(), 'discount');
    });
  });

  describe('.products()', function() {
    it('should proxy products', function() {
      var track = new Track({ properties: { products: [{}] } });
      assert.deepEqual(track.products(), [{}]);
    });

    it('should return array', function() {
      var track = new Track({});
      assert.strictEqual(Object.prototype.toString.call(track.products()), '[object Array]');
    });

    it('should always return an array', function() {
      var track = new Track({ properties: { products: 'products' } });
      assert.deepEqual(track.products(), []);
    });

    it('should lookup products properly', function() {
      var track = new Track({ properties: { Products: [{}] } });
      assert.deepEqual(track.products(), [{}]);
    });
  });

  describe('.orderId()', function() {
    it('should proxy orderId', function() {
      var track = new Track({ properties: { orderId: 'orderId' } });
      assert.strictEqual(track.orderId(), 'orderId');
    });

    it('should proxy `id`', function() {
      var track = new Track({ properties: { id: 'id' } });
      assert.strictEqual(track.orderId(), 'id');
    });
  });

  describe('.properties()', function() {
    it('should proxy the properties', function() {
      assert.deepEqual(track.properties(), args.properties);
    });

    it('should respect aliases', function() {
      assert.deepEqual(track.properties({ revenue: 'amount' }), { referrer: 'http://segment.io', email: 'test@segment.io', username: 'calvinfo', amount: 50 });
    });

    it('should traverse isodate', function() {
      var date = new Date(Date.UTC(2013, 9, 5));
      var track = new Track({ properties: { date: '2013-10-05T00:00:00.000Z' } });
      var time = track.properties().date.getTime();
      assert.strictEqual(time, date.getTime());
    });
  });

  describe('.referrer()', function() {
    it('should proxy the referrer', function() {
      assert.strictEqual(track.referrer(), args.properties.referrer);
    });

    it('should proxy context.referrer.url', function() {
      var track = new Track({ context: { referrer: { url: 'url' } } });
      assert.strictEqual(track.referrer(), 'url');
    });

    it('should proxy context.page.referrer', function() {
      var track = new Track({ context: { page: { referrer: 'url' } } });
      assert.strictEqual(track.referrer(), 'url');
    });
  });

  describe('.username()', function() {
    it('should proxy the username', function() {
      assert.strictEqual(track.username(), args.properties.username);
    });

    it('should proxy the username from the userId', function() {
      assert.strictEqual(new Track({ userId: 'aaa' }).username(), 'aaa');
    });

    it('should proxy the username from the sessionId', function() {
      assert.strictEqual(new Track({ sessionId: 'bbb' }).username(), 'bbb');
    });
  });

  describe('.query()', function() {
    it('should proxy the query', function() {
      assert.strictEqual(track.query(), args.options.query);
    });
  });

  describe('.revenue()', function() {
    it('should proxy the revenue', function() {
      assert.strictEqual(track.revenue(), 50);
    });

    it('should return a number', function() {
      var track = new Track({ properties: { revenue: 10 } });
      assert.strictEqual(track.revenue(), 10);
    });

    it('should intelligently convert strings to numbers if possible', function() {
      var track = new Track({ properties: { revenue: '$10' } });
      assert.strictEqual(track.revenue(), 10);
    });

    it('should return undefined for unknown format', function() {
      var track = new Track({ properties: { revenue: '$hello' } });
      assert.strictEqual(track.revenue(), undefined);
    });

    it('should fallback to total, only during "completed order" event', function() {
      var track = new Track({ properties: { total: 75 } });
      assert.strictEqual(track.revenue(), undefined);
      track = new Track({ properties: { total: 75 }, event: 'completed order' });
      assert.strictEqual(track.revenue(), 75);
    });
  });

  describe('.value()', function() {
    it('should proxy value', function() {
      var track = new Track({ properties: { value: 90 } });
      assert.strictEqual(track.value(), 90);
    });
  });

  describe('.email()', function() {
    it('should proxy the email from properties.email', function() {
      assert.strictEqual(track.email(), args.properties.email);
    });

    it('should proxy the email from .userId', function() {
      var track = new Track({ userId: 'test@segment.io' });
      assert.strictEqual(track.email(), 'test@segment.io');
    });

    it('should fall back to context.traits.email', function() {
      var track = new Track({
        event: 'Email Bounced',
        properties: {
          email_id: '18vzF7u3z',
          email_subject: 'First shirt on us!',
          campaign_id: '123',
          campaign_name: 'New Customer Discount'
        },
        context: {
          ip: '67.207.109.102',
          user_agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36',
          traits: {
            email: 'pgibbons@initech.com'
          }
        }
      });

      assert.strictEqual(track.email(), 'pgibbons@initech.com');
    });
  });

  describe('.cents()', function() {
    it('should return revenue * 100 if available', function() {
      var track = new Track({ properties: { revenue: 9.99 } });
      assert.strictEqual(track.cents(), 999);
    });

    it('should return value if revenue is unavailable', function() {
      var track = new Track({ properties: { value: 9 } });
      assert.strictEqual(track.cents(), 9);
    });

    it('should prefer revenue', function() {
      var track = new Track({
        properties: {
          revenue: 9.99,
          value: 9
        }
      });
      assert.strictEqual(track.cents(), 999);
    });
  });

  describe('.description()', function() {
    it('should return the description', function() {
      var msg = new Track({ properties: { description: 'description' } });
      assert.strictEqual(msg.description(), 'description');
    });
  });

  describe('.plan()', function() {
    it('should return the description', function() {
      var msg = new Track({ properties: { plan: 'plan' } });
      assert.strictEqual(msg.plan(), 'plan');
    });
  });

  describe('.identify()', function() {
    it('should convert track to identify calls', function() {
      var track = new Track(args);
      var identify = track.identify();

      assert.deepEqual(identify.traits(), { id: 'calvin@segment.io', someTrait: 'y' });
    });
  });
});
<commit_msg>add property showing query aliasing from options<commit_after>'use strict';

var Track = require('../lib').Track;
var assert = require('proclaim');

describe('Track', function() {
  var args = {
    userId: 'calvin@segment.io',
    sessionId: 'abc123',
    properties: {
      revenue: '$50',
      query: 'Shangri La',
      referrer: 'http://segment.io',
      username: 'calvinfo',
      email: 'test@segment.io'
    },
    options: {
      query: 'segmentio',
      traits: {
        someTrait: 'y'
      }
    }
  };

  var track = new Track(args);

  describe('.repeat()', function() {
    it('should proxy properties.repeat', function() {
      var msg = new Track({ properties: { repeat: true } });
      assert.strictEqual(msg.repeat(), true);
    });
  });

  describe('.type()', function() {
    it('should have the proper .type()', function() {
      assert.strictEqual(track.type(), 'track');
    });

    it('should equal .action()', function() {
      assert.strictEqual(track.type(), track.action());
    });
  });

  describe('.userId()', function() {
    it('should proxy the userId', function() {
      assert.strictEqual(track.userId(), args.userId);
    });
  });

  describe('.sessionId()', function() {
    it('should proxy the sessionId', function() {
      assert.strictEqual(track.sessionId(), args.sessionId);
    });
  });

  describe('.event()', function() {
    it('should proxy the event', function() {
      assert.strictEqual(track.event(), args.event);
    });
  });

  describe('.quantity()', function() {
    it('should return the quantity', function() {
      var track = new Track({ properties: { quantity: 2 } });
      assert.strictEqual(track.quantity(), 2);
    });

    it('should default quantity to 1', function() {
      var track = new Track({});
      assert.strictEqual(track.quantity(), 1);
    });
  });

  describe('.currency()', function() {
    it('should return the currency code', function() {
      var track = new Track({ properties: { currency: 'EUR' } });
      assert.strictEqual(track.currency(), 'EUR');
    });

    it('should default currency to `USD`', function() {
      var track = new Track({});
      assert.strictEqual(track.currency(), 'USD');
    });
  });

  describe('.subtotal()', function() {
    it('should get subtotal', function() {
      var track = new Track({ properties: { subtotal: 10 } });
      assert.strictEqual(track.subtotal(), 10);
    });

    it('should compute subtotal from total', function() {
      var track = new Track({ properties: { total: 10, tax: 2, shipping: 2 } });
      assert.strictEqual(track.subtotal(), 6);
    });

    it('should compute subtotal from .tax, .shipping, .discount and .total', function() {
      var track = new Track({ properties: { Total: 10, Tax: 2, Shipping: 2, Discount: 1 } });
      assert.strictEqual(track.subtotal(), 7);
    });

    it('should lookup .subtotal properly', function() {
      var track = new Track({ properties: { Subtotal: 10 } });
      assert.strictEqual(track.subtotal(), 10);
    });
  });

  describe('.category()', function() {
    it('should proxy category', function() {
      var track = new Track({ properties: { category: 'category' } });
      assert.strictEqual(track.category(), 'category');
    });
  });

  describe('.state()', function() {
    it('should proxy state', function() {
      var track = new Track({ properties: { state: 'state' } });
      assert.strictEqual(track.state(), 'state');
    });
  });

  describe('.city()', function() {
    it('should proxy city', function() {
      var track = new Track({ properties: { city: 'city' } });
      assert.strictEqual(track.city(), 'city');
    });
  });

  describe('.zip()', function() {
    it('should proxy zip', function() {
      var track = new Track({ properties: { zip: 'zip' } });
      assert.strictEqual(track.zip(), 'zip');
    });
  });

  describe('.tax()', function() {
    it('should proxy tax', function() {
      var track = new Track({ properties: { tax: 'tax' } });
      assert.strictEqual(track.tax(), 'tax');
    });
  });

  describe('.name()', function() {
    it('should proxy name', function() {
      var track = new Track({ properties: { name: 'name' } });
      assert.strictEqual(track.name(), 'name');
    });
  });

  describe('.country()', function() {
    it('should proxy country', function() {
      var track = new Track({ properties: { country: 'country' } });
      assert.strictEqual(track.country(), 'country');
    });

    it('should proxy context.traits', function() {
      var track = new Track({
        context: {
          traits: {
            address: {
              country: 'country'
            }
          }
        }
      });

      assert.strictEqual(track.country(), 'country');
    });
  });

  describe('.price()', function() {
    it('should proxy price', function() {
      var track = new Track({ properties: { price: 'price' } });
      assert.strictEqual(track.price(), 'price');
    });
  });

  describe('.total()', function() {
    it('should proxy total', function() {
      var track = new Track({ properties: { total: 'total' } });
      assert.strictEqual(track.total(), 'total');
    });
  });

  describe('.coupon()', function() {
    it('should proxy coupon', function() {
      var track = new Track({ properties: { coupon: 'coupon' } });
      assert.strictEqual(track.coupon(), 'coupon');
    });
  });

  describe('.shipping()', function() {
    it('should proxy shipping', function() {
      var track = new Track({ properties: { shipping: 'shipping' } });
      assert.strictEqual(track.shipping(), 'shipping');
    });
  });

  describe('.discount()', function() {
    it('should proxy discount', function() {
      var track = new Track({ properties: { discount: 'discount' } });
      assert.strictEqual(track.discount(), 'discount');
    });
  });

  describe('.products()', function() {
    it('should proxy products', function() {
      var track = new Track({ properties: { products: [{}] } });
      assert.deepEqual(track.products(), [{}]);
    });

    it('should return array', function() {
      var track = new Track({});
      assert.strictEqual(Object.prototype.toString.call(track.products()), '[object Array]');
    });

    it('should always return an array', function() {
      var track = new Track({ properties: { products: 'products' } });
      assert.deepEqual(track.products(), []);
    });

    it('should lookup products properly', function() {
      var track = new Track({ properties: { Products: [{}] } });
      assert.deepEqual(track.products(), [{}]);
    });
  });

  describe('.orderId()', function() {
    it('should proxy orderId', function() {
      var track = new Track({ properties: { orderId: 'orderId' } });
      assert.strictEqual(track.orderId(), 'orderId');
    });

    it('should proxy `id`', function() {
      var track = new Track({ properties: { id: 'id' } });
      assert.strictEqual(track.orderId(), 'id');
    });
  });

  describe('.properties()', function() {
    it('should proxy the properties', function() {
      assert.deepEqual(track.properties(), args.properties);
    });

    it('should respect aliases', function() {
      assert.deepEqual(track.properties({ revenue: 'amount', query: 'searchString' }), { referrer: 'http://segment.io', email: 'test@segment.io', username: 'calvinfo', amount: 50, searchString: 'Shangri La' });
    });

    it('should traverse isodate', function() {
      var date = new Date(Date.UTC(2013, 9, 5));
      var track = new Track({ properties: { date: '2013-10-05T00:00:00.000Z' } });
      var time = track.properties().date.getTime();
      assert.strictEqual(time, date.getTime());
    });
  });

  describe('.referrer()', function() {
    it('should proxy the referrer', function() {
      assert.strictEqual(track.referrer(), args.properties.referrer);
    });

    it('should proxy context.referrer.url', function() {
      var track = new Track({ context: { referrer: { url: 'url' } } });
      assert.strictEqual(track.referrer(), 'url');
    });

    it('should proxy context.page.referrer', function() {
      var track = new Track({ context: { page: { referrer: 'url' } } });
      assert.strictEqual(track.referrer(), 'url');
    });
  });

  describe('.username()', function() {
    it('should proxy the username', function() {
      assert.strictEqual(track.username(), args.properties.username);
    });

    it('should proxy the username from the userId', function() {
      assert.strictEqual(new Track({ userId: 'aaa' }).username(), 'aaa');
    });

    it('should proxy the username from the sessionId', function() {
      assert.strictEqual(new Track({ sessionId: 'bbb' }).username(), 'bbb');
    });
  });

  describe('.query()', function() {
    it('should proxy the query', function() {
      assert.strictEqual(track.query(), args.options.query);
    });
  });

  describe('.revenue()', function() {
    it('should proxy the revenue', function() {
      assert.strictEqual(track.revenue(), 50);
    });

    it('should return a number', function() {
      var track = new Track({ properties: { revenue: 10 } });
      assert.strictEqual(track.revenue(), 10);
    });

    it('should intelligently convert strings to numbers if possible', function() {
      var track = new Track({ properties: { revenue: '$10' } });
      assert.strictEqual(track.revenue(), 10);
    });

    it('should return undefined for unknown format', function() {
      var track = new Track({ properties: { revenue: '$hello' } });
      assert.strictEqual(track.revenue(), undefined);
    });

    it('should fallback to total, only during "completed order" event', function() {
      var track = new Track({ properties: { total: 75 } });
      assert.strictEqual(track.revenue(), undefined);
      track = new Track({ properties: { total: 75 }, event: 'completed order' });
      assert.strictEqual(track.revenue(), 75);
    });
  });

  describe('.value()', function() {
    it('should proxy value', function() {
      var track = new Track({ properties: { value: 90 } });
      assert.strictEqual(track.value(), 90);
    });
  });

  describe('.email()', function() {
    it('should proxy the email from properties.email', function() {
      assert.strictEqual(track.email(), args.properties.email);
    });

    it('should proxy the email from .userId', function() {
      var track = new Track({ userId: 'test@segment.io' });
      assert.strictEqual(track.email(), 'test@segment.io');
    });

    it('should fall back to context.traits.email', function() {
      var track = new Track({
        event: 'Email Bounced',
        properties: {
          email_id: '18vzF7u3z',
          email_subject: 'First shirt on us!',
          campaign_id: '123',
          campaign_name: 'New Customer Discount'
        },
        context: {
          ip: '67.207.109.102',
          user_agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36',
          traits: {
            email: 'pgibbons@initech.com'
          }
        }
      });

      assert.strictEqual(track.email(), 'pgibbons@initech.com');
    });
  });

  describe('.cents()', function() {
    it('should return revenue * 100 if available', function() {
      var track = new Track({ properties: { revenue: 9.99 } });
      assert.strictEqual(track.cents(), 999);
    });

    it('should return value if revenue is unavailable', function() {
      var track = new Track({ properties: { value: 9 } });
      assert.strictEqual(track.cents(), 9);
    });

    it('should prefer revenue', function() {
      var track = new Track({
        properties: {
          revenue: 9.99,
          value: 9
        }
      });
      assert.strictEqual(track.cents(), 999);
    });
  });

  describe('.description()', function() {
    it('should return the description', function() {
      var msg = new Track({ properties: { description: 'description' } });
      assert.strictEqual(msg.description(), 'description');
    });
  });

  describe('.plan()', function() {
    it('should return the description', function() {
      var msg = new Track({ properties: { plan: 'plan' } });
      assert.strictEqual(msg.plan(), 'plan');
    });
  });

  describe('.identify()', function() {
    it('should convert track to identify calls', function() {
      var track = new Track(args);
      var identify = track.identify();

      assert.deepEqual(identify.traits(), { id: 'calvin@segment.io', someTrait: 'y' });
    });
  });
});
<|endoftext|>


<commit_before>import { shallow } from 'enzyme';
import * as React from 'react';
import { compose } from 'redux';

import GenericError from 'amo/components/ErrorPage/GenericError';
import NotFound from 'amo/components/ErrorPage/NotFound';
import {
  getErrorComponent,
  render404IfConfigKeyIsFalse,
} from 'amo/utils/errors';

describe(__filename, () => {
  describe('getErrorComponent', () => {
    it('returns the NotFound component when status is 404', () => {
      expect(getErrorComponent(404)).toEqual(NotFound);
    });

    it('returns the GenericError component when status is not 404', () => {
      expect(getErrorComponent(400)).toEqual(GenericError);
      expect(getErrorComponent(null)).toEqual(GenericError);
      expect(getErrorComponent(undefined)).toEqual(GenericError);
    });
  });

  describe('render404IfConfigKeyIsFalse', () => {
    const render = ({
      SomeComponent = () =>
,
      _config = { get: () => true },
      configKey = 'someConfigKey',
      props = {},
    } = {}) => {
      const WrappedComponent = compose(
        render404IfConfigKeyIsFalse(configKey, { _config }),
      )(SomeComponent);

      return shallow(<WrappedComponent {...props} />);
    };

    it('requires a config key', () => {
      expect(() => render404IfConfigKeyIsFalse()).toThrowError(
        /configKey cannot be empty/,
      );
    });

    it('returns a 404 when disabled by the config', () => {
      const configKey = 'customConfigKey';
      const _config = {
        get: sinon.spy(() => false),
      };
      const SomeComponent = sinon.spy(() =>
);

      const root = render({ _config, SomeComponent, configKey });

      expect(root.find(SomeComponent)).toHaveLength(0);
      expect(root.find(NotFound)).toHaveLength(1);
      sinon.assert.calledWith(_config.get, configKey);
    });

    it('passes through component and props when enabled', () => {
      const _config = { get: () => true };
      const SomeComponent = sinon.spy(() =>
);
      const props = { color: 'orange', size: 'large' };

      const root = render({ _config, SomeComponent, props });

      expect(root.find(NotFound)).toHaveLength(0);

      expect(root.find(SomeComponent)).toHaveLength(1);
      expect(root.find(SomeComponent)).toHaveProp(props);
    });
  });
});
<commit_msg>Migrate /utils/test_errors.js (#11622)<commit_after>import * as React from 'react';
import { compose } from 'redux';

import GenericError from 'amo/components/ErrorPage/GenericError';
import NotFound from 'amo/components/ErrorPage/NotFound';
import {
  getErrorComponent,
  render404IfConfigKeyIsFalse,
} from 'amo/utils/errors';
import { render as defaultRender, screen } from 'tests/unit/helpers';

describe(__filename, () => {
  describe('getErrorComponent', () => {
    it('returns the NotFound component when status is 404', () => {
      expect(getErrorComponent(404)).toEqual(NotFound);
    });

    it('returns the GenericError component when status is not 404', () => {
      expect(getErrorComponent(400)).toEqual(GenericError);
      expect(getErrorComponent(null)).toEqual(GenericError);
      expect(getErrorComponent(undefined)).toEqual(GenericError);
    });
  });

  describe('render404IfConfigKeyIsFalse', () => {
    const render = ({
      SomeComponent = () =>
,
      _config = { get: () => true },
      configKey = 'someConfigKey',
      props = {},
    } = {}) => {
      const WrappedComponent = compose(
        render404IfConfigKeyIsFalse(configKey, { _config }),
      )(SomeComponent);

      return defaultRender(<WrappedComponent {...props} />);
    };

    it('requires a config key', () => {
      expect(() => render404IfConfigKeyIsFalse()).toThrowError(
        /configKey cannot be empty/,
      );
    });

    it('returns a 404 when disabled by the config', () => {
      const className = 'MyClass';
      const configKey = 'customConfigKey';
      const _config = {
        get: jest.fn(() => false),
      };
      const SomeComponent = jest.fn(() =>
);

      render({ _config, SomeComponent, configKey });

      expect(screen.queryByClassName(className)).not.toBeInTheDocument();
      expect(
        screen.getByRole('heading', { name: 'Page not found' }),
      ).toBeInTheDocument();
      expect(_config.get).toHaveBeenCalledWith(configKey);
    });

    it('passes through component and props when enabled', () => {
      const _config = { get: () => true };
      const SomeComponent = jest.fn((props) =>
{props.color}
);
      const props = { color: 'orange', size: 'large' };

      render({ _config, SomeComponent, props });

      expect(
        screen.queryByRole('heading', { name: 'Page not found' }),
      ).not.toBeInTheDocument();
      expect(screen.getByText('orange')).toBeInTheDocument();
    });
  });
});
<|endoftext|>


<commit_before>"use strict";
var assert = require('assert');
var DataProbingBounds = require('../../dataProbingBounds');

describe('dataProbingBounds', function(){

  function getInstance(stopYear){
    return new DataProbingBounds(stopYear ? stopYear : 2000);
  }

  describe('#constructor', function(){
    it('throw if stopYear not number', function(){
      // assert
      assert.throws(
        function(){
          new DataProbingBounds("not a number ok?");
        }, Error);
    })
  });

  describe('#getProbingBounds', function() {
    it('parameter should accept string that can be parsed as date', function(){
      // arrange
      var inputDate = '2015-01-01';
      var probingBounds = getInstance();

      // assert
      assert.doesNotThrow(function(){
        probingBounds.getProbingBounds(inputDate);
      });
    });

    it('parameter should throw exception if not Date', function(){
      // arrange
      var invalidDate = "this is not a date";

      var probingBounds = getInstance();

      // assert
      assert.throws(
        function(){
          probingBounds.getProbingBounds(invalidDate);
        }, Error);
    });

    it('return last year as startYear if parameter is a date of this year', function(){
      // arrange
      var inputDate = "2015-01-17";
      var expectedStartYear = 2014;

      var probingBounds = getInstance();

      // act
      var result = probingBounds.getProbingBounds(inputDate);

      // assert
      assert.equal(result.startYear, expectedStartYear);
    });

    it('return the year of the input date when date not this year', function(){
      // arrange
      var inputDate = "2004-10-17";
      var expectedStartYear = 2004;
      var expectedStopYear = 2000;

      var probingBounds = getInstance(expectedStopYear);

      // act
      var result = probingBounds.getProbingBounds(inputDate);

      // assert
      assert.equal(result.startYear, expectedStartYear);
    });

    it('stopYear should always be expectedStopYear', function(){
      // arrange
      var inputDate = "2015-01-17";
      var expectedStopYear = 2000;

      var probingBounds = getInstance(expectedStopYear);

      // act
      var result = probingBounds.getProbingBounds(inputDate);

      // assert
      assert.equal(result.stopYear, expectedStopYear);
    });

    it('return last year if inputDate is less than stopYear', function(){
      // arrange
      var inputDate = "1999-10-23";
      var expectedStartYear = 2014;
      var expectedStopYear = 2000;

      var probingBounds = getInstance(expectedStopYear);

      // act
      var result = probingBounds.getProbingBounds(inputDate);

      // assert
      assert.equal(result.startYear, expectedStartYear);
      assert.equal(result.stopYear, expectedStopYear);
    });

  })
});<commit_msg>fixes failing unit tests due to assumption about system year<commit_after>"use strict";
var assert = require('assert');
var sinon = require('sinon');
var DataProbingBounds = require('../../dataProbingBounds');

describe('dataProbingBounds', function(){

  var clock;

  beforeEach(function() {
    clock = sinon.useFakeTimers();
    clock.now = '2015-01-01';
  });

  afterEach(function() {
    clock = clock.restore();
  });

  function getInstance(stopYear){
    return new DataProbingBounds(stopYear ? stopYear : 2000);
  }

  describe('#constructor', function(){
    it('throw if stopYear not number', function(){
      // assert
      assert.throws(
        function(){
          new DataProbingBounds("not a number ok?");
        }, Error);
    })
  });

  describe('#getProbingBounds', function() {
    it('parameter should accept string that can be parsed as date', function(){
      // arrange
      var inputDate = '2015-01-01';
      var probingBounds = getInstance();

      // assert
      assert.doesNotThrow(function(){
        probingBounds.getProbingBounds(inputDate);
      });
    });

    it('parameter should throw exception if not Date', function(){
      // arrange
      var invalidDate = "this is not a date";

      var probingBounds = getInstance();

      // assert
      assert.throws(
        function(){
          probingBounds.getProbingBounds(invalidDate);
        }, Error);
    });

    it('return last year as startYear if parameter is a date of this year', function(){
      // arrange
      var inputDate = "2015-01-17";
      var expectedStartYear = 2014;

      var probingBounds = getInstance();

      // act
      var result = probingBounds.getProbingBounds(inputDate);

      // assert
      assert.equal(result.startYear, expectedStartYear);
    });

    it('return the year of the input date when date not this year', function(){
      // arrange
      var inputDate = "2004-10-17";
      var expectedStartYear = 2004;
      var expectedStopYear = 2000;

      var probingBounds = getInstance(expectedStopYear);

      // act
      var result = probingBounds.getProbingBounds(inputDate);

      // assert
      assert.equal(result.startYear, expectedStartYear);
    });

    it('stopYear should always be expectedStopYear', function(){
      // arrange
      var inputDate = "2015-01-17";
      var expectedStopYear = 2000;

      var probingBounds = getInstance(expectedStopYear);

      // act
      var result = probingBounds.getProbingBounds(inputDate);

      // assert
      assert.equal(result.stopYear, expectedStopYear);
    });

    it('return last year if inputDate is less than stopYear', function(){
      // arrange
      var inputDate = "1999-10-23";
      var expectedStartYear = 2014;
      var expectedStopYear = 2000;

      var probingBounds = getInstance(expectedStopYear);

      // act
      var result = probingBounds.getProbingBounds(inputDate);

      // assert
      assert.equal(result.startYear, expectedStartYear);
      assert.equal(result.stopYear, expectedStopYear);
    });

  })
});
<|endoftext|>


<commit_before>import { module, test } from 'qunit';
import { ownTransform } from 'liquid-fire/transform';
import Measurement from 'liquid-fire/measurement';
import $ from 'jquery';

let environment, offsetParent, target, innerContent;

module("Unit | Measurement", {
  beforeEach(assert) {
    assert.sameBounds = function(target, fn) {
      let before = bounds(target);
      fn();
      let after = bounds(target);
      assert.deepEqual(after, before, 'bounds should not change');
    };

    let fixture = $('#qunit-fixture');
    fixture.html('

');
    environment = fixture.find('.environment');
    offsetParent = fixture.find('.offset-parent');
    target = fixture.find('.target');
    innerContent = fixture.find('.inner-content');
    environment.width(600);
    offsetParent.css('position', 'relative');
    innerContent.height(400);
  },
  afterEach() {
    $('#qunit-fixture').empty();
  }
});

test('Simple case', function(assert) {
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Scaled ancestor', function(assert) {
  environment.css('transform', 'scale(0.5)');
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Translated ancestor', function(assert) {
  environment.css('transform', 'translateX(500px) translateY(500px)');
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Scaled offsetParent', function(assert) {
  offsetParent.css('transform', 'scale(0.5)');
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Translated offsetParent', function(assert) {
  offsetParent.css('transform', 'translateX(500px) translateY(500px)');
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Target translated', function(assert) {
  target.css('transform', 'translateX(500px) translateY(500px)');
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Target scaled', function(assert) {
  target.css('transform', 'scale(0.5)');
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Target rotated', function(assert) {
  target.css('transform', 'rotate(45deg)');
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Margins on target', function(assert) {
  addMargins(target);
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Margins on offsetParent', function(assert) {
  addMargins(offsetParent);
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test("No leaked styles", function(assert) {
  let m = measure(target);
  m.lock();
  m.unlock();
  // TODO: we are clearing the styles, but we leave an empty attribute
  // behind. Seems likea jquery or browser bug.
  assert.equal(target.attr('style'), undefined);
});

test("Restores original styles", function(assert) {
  target.css({
    position: 'relative',
    top: '5px',
    left: '6px',
    width: '10px',
    height: '11px',
    transform: 'translateX(20px)'
  });
  let m = measure(target);
  m.lock();
  m.unlock();
  assert.equal(target.css('position'), 'relative', 'position');
  assert.equal(target.css('top'), '5px', 'top');
  assert.equal(target.css('left'), '6px', 'left');
  assert.equal(target.css('width'), '10px', 'width');
  assert.equal(target.css('height'), '11px', 'height');
  assert.equal(ownTransform(target[0]).tx, 20, 'translateX');
});

function bounds($elt) {
  return $elt[0].getBoundingClientRect();
}

function measure($elt) {
  return new Measurement($elt[0]);
}

function addMargins($elt) {
  $elt.css({
    marginTop: '4px',
    marginLeft: '5px',
    marginRight: '6px',
    marginBottom: '7px'
  });
}
<commit_msg>provide stable container for tests<commit_after>import { module, test } from 'qunit';
import { ownTransform } from 'liquid-fire/transform';
import Measurement from 'liquid-fire/measurement';
import $ from 'jquery';

let environment, offsetParent, target, innerContent;

module("Unit | Measurement", {
  beforeEach(assert) {
    assert.sameBounds = function(target, fn) {
      let before = bounds(target);
      fn();
      let after = bounds(target);
      assert.deepEqual(after, before, 'bounds should not change');
    };

    let fixture = $('#qunit-fixture');
    fixture.html('

');
    environment = fixture.find('.environment');
    offsetParent = fixture.find('.offset-parent');
    target = fixture.find('.target');
    innerContent = fixture.find('.inner-content');
    environment.width(600);
    offsetParent.css('position', 'relative');
    innerContent.height(400);
  },
  afterEach() {
    $('#qunit-fixture').empty();
  }
});

test('Simple case', function(assert) {
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Scaled ancestor', function(assert) {
  environment.css('transform', 'scale(0.5)');
  environment.css('transform-origin', '0 0');
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Translated ancestor', function(assert) {
  environment.css('transform', 'translateX(500px) translateY(500px)');
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Scaled offsetParent', function(assert) {
  offsetParent.css('transform', 'scale(0.5)');
  offsetParent.css('transform-origin', '0 0');
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Translated offsetParent', function(assert) {
  offsetParent.css('transform', 'translateX(500px) translateY(500px)');
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Target translated', function(assert) {
  target.css('transform', 'translateX(500px) translateY(500px)');
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Target scaled', function(assert) {
  target.css('transform', 'scale(0.5)');
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Target rotated', function(assert) {
  target.css('transform', 'rotate(45deg)');
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Margins on target', function(assert) {
  addMargins(target);
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test('Margins on offsetParent', function(assert) {
  addMargins(offsetParent);
  let m = measure(target);
  assert.sameBounds(target, () => m.lock());
});

test("No leaked styles", function(assert) {
  let m = measure(target);
  m.lock();
  m.unlock();
  // TODO: we are clearing the styles, but we leave an empty attribute
  // behind. Seems likea jquery or browser bug.
  assert.equal(target.attr('style'), undefined);
});

test("Restores original styles", function(assert) {
  target.css({
    position: 'relative',
    top: '5px',
    left: '6px',
    width: '10px',
    height: '11px',
    transform: 'translateX(20px)'
  });
  let m = measure(target);
  m.lock();
  m.unlock();
  assert.equal(target.css('position'), 'relative', 'position');
  assert.equal(target.css('top'), '5px', 'top');
  assert.equal(target.css('left'), '6px', 'left');
  assert.equal(target.css('width'), '10px', 'width');
  assert.equal(target.css('height'), '11px', 'height');
  assert.equal(ownTransform(target[0]).tx, 20, 'translateX');
});

function bounds($elt) {
  return $elt[0].getBoundingClientRect();
}

function measure($elt) {
  return new Measurement($elt[0]);
}

function addMargins($elt) {
  $elt.css({
    marginTop: '4px',
    marginLeft: '5px',
    marginRight: '6px',
    marginBottom: '7px'
  });
}
<|endoftext|>


<commit_before>'use strict';

const proxyquire = require('proxyquire');
const assert = require('assert');

describe('VersionEyeSlack class', function() {
    let sut;
    let versioneyeApiKey = 'versioneye-api-key-dummy';
    let slackWebhookUrl = 'https://hooks.slack.com/services/dummy/webhook/url';

    describe('postNotifications', function() {
        let actualOpts;

        beforeEach(function() {
            const VersionEyeSlack = proxyquire('../../index', {
                'versioneye-api-client': class {
                    constructor(apiKey, opt_baseUri) {
                        this.me = {
                            listNotifications: function() {
                                return Promise.resolve({
                                    "notifications": [
                                        {
                                            "read": true,
                                            "product": {
                                                "prod_key": "read_prod_key",
                                                "language": "read_language",
                                                "name": "read_name"
                                            },
                                            "version": "2.0.0"
                                        },
                                        {
                                            "read": false,
                                            "product": {
                                                "prod_key": "unread_prod_key",
                                                "language": "unread_language",
                                                "name": "unread_name"
                                            },
                                            "version": "1.0.0"
                                        }
                                    ]
                                });
                            }
                        }
                    }
                },
                'slack-incoming-webhook': function(opts) {
                    return function(message, opts, callback) {
                        actualOpts = opts;
                        process.nextTick(function() {
                            callback(null, 'mocked');
                        });
                    };
                }
            });
            sut = new VersionEyeSlack(versioneyeApiKey, slackWebhookUrl);
        });

        it.only('post unread notifications of VersionEye to Slack', function() {
            return sut.postNotifications().then(response => {
                assert(Array.isArray(actualOpts['attachments']));
                assert(actualOpts['attachments'].length === 1);
                assert(actualOpts['attachments'][0]['text'] === '<https://www.versioneye.com/unread_language/unread_prod_key|unread_name> (1.0.0)');
                assert(response === 'mocked');
            });
        });
    });
});
<commit_msg>test(VersionEyeSlack): add a unit test for postProjectSummary<commit_after>'use strict';

const proxyquire = require('proxyquire');
const assert = require('assert');

let actualMessage;
let actualOpts;
const mockSlack = function(opts) {
    return function(message, opts, callback) {
        actualMessage = message;
        actualOpts = opts;
        process.nextTick(function() {
            callback(null, 'mocked');
        });
    };
};

describe('VersionEyeSlack class', function() {
    let sut;
    let versioneyeApiKey = 'versioneye-api-key-dummy';
    let slackWebhookUrl = 'https://hooks.slack.com/services/dummy/webhook/url';

    beforeEach(function() {
        actualMessage = null;
        actualOpts = null;
    });

    describe('postNotifications', function() {
        beforeEach(function() {
            const VersionEyeSlack = proxyquire('../../index', {
                'versioneye-api-client': class {
                    constructor(apiKey, opt_baseUri) {
                        this.me = {
                            listNotifications: function() {
                                return Promise.resolve({
                                    "notifications": [
                                        {
                                            "read": true,
                                            "product": {
                                                "prod_key": "read_prod_key",
                                                "language": "read_language",
                                                "name": "read_name"
                                            },
                                            "version": "2.0.0"
                                        },
                                        {
                                            "read": false,
                                            "product": {
                                                "prod_key": "unread_prod_key",
                                                "language": "unread_language",
                                                "name": "unread_name"
                                            },
                                            "version": "1.0.0"
                                        }
                                    ]
                                });
                            }
                        }
                    }
                },
                'slack-incoming-webhook': mockSlack
            });
            sut = new VersionEyeSlack(versioneyeApiKey, slackWebhookUrl);
        });

        it('post unread notifications of VersionEye to Slack', function() {
            return sut.postNotifications().then(response => {
                assert(actualMessage === 'There are notifications for new releases!');
                assert.deepEqual(actualOpts, {
                    'attachments': [{
                        'text': '<https://www.versioneye.com/unread_language/unread_prod_key|unread_name> (1.0.0)'
                    }]
                });
                assert(response === 'mocked');
            });
        });
    });

    describe('postProjectSummary', function() {
        beforeEach(function() {
            const VersionEyeSlack = proxyquire('../../index', {
                'versioneye-api-client': class {
                    constructor(apiKey, opt_baseUri) {
                        this.projects = {
                            list: function() {
                                return Promise.resolve([
                                    {
                                        "id": {
                                            "$oid": "project1-id"
                                        },
                                        "name": "project1"
                                    },
                                    {
                                        "id": {
                                            "$oid": "project2-id"
                                        },
                                        "name": "project2"
                                    }
                                ]);
                            },
                            show: function(projectId) {
                                return Promise.resolve({
                                    "id": projectId,
                                    "out_number_sum": 0,
                                    "licenses_red_sum": 0,
                                    "licenses_unknown_sum": 0,
                                    "sv_count_sum": 0
                                });
                            }
                        }
                    }
                },
                'slack-incoming-webhook': mockSlack
            });
            sut = new VersionEyeSlack(versioneyeApiKey, slackWebhookUrl);
        });

        it('Post a summary for the specific project', function() {
            return sut.postProjectSummary('project1').then(response => {
                assert(actualMessage === 'Project summary for <https://www.versioneye.com/user/projects/project1-id|project1>');
                assert.deepEqual(actualOpts, {
                    'attachments': [
                        {
                            color: 'good',
                            text: 'Outdated: 0'
                        },
                        {
                            color: 'good',
                            text: 'Licenses: 0 : 0'
                        },
                        {
                            color: 'good',
                            text: 'Security: 0'
                        }
                    ]
                });
                assert(response === 'mocked');
            });
        });
    });
});
<|endoftext|>


<commit_before>var fs = require('fs'),
    fis = require('../../fis-kernel.js');

var project = fis.project;
var expect = require('chai').expect;

function getPath(root, args){
    if(args && args.length > 0){
        args = root + '/' + Array.prototype.join.call(args, '/');
        return fis.util(args);
    } else {
        return root;
    }
}

describe('project',function(){
    it('getTempPath', function(){
        var list = ['LOCALAPPDATA', 'APPDATA', 'HOME'];
        var tmp;
        for(var i = 0, len = list.length; i < len; i++){
            if(tmp = process.env[list[i]]){
                break;
            }
        }
        tmp = tmp || __dirname + '/../';
        tmp = tmp.replace(/\\/g, '/');
        tmp = getPath(tmp, arguments);
        expect(project.getTempPath()).to.be.equal(tmp+'/.fis-tmp');

    });
});<commit_msg>[case]移除project<commit_after><|endoftext|>