<commit_before>define('template', function(template) {
  var template = {
    load: function (resourceName, parentRequire, callback, config) {
      var extension = '.handlebars';

      return parentRequire(
        [("text!" + resourceName + extension)],
        function (templateContent) {
          var templateName = resourceName;
          Ember.TEMPLATES[templateName] = Ember.Handlebars.compile(templateContent);
          callback(templateName);
        }
      );
    }
  }

  return template;
});
<commit_msg>Template files' extension is now configurable.<commit_after>define(['module'], function(module) {

  var masterConfig = module.config();

  var hbs = {
    load: function(name, req, load, config) {
      config = config || {};
      var extension = masterConfig.extension;
      if (config.extension) {
        extension = config.extension;
      }
      extension = extension || 'handlebars';
      var textName = 'text!' + name + '.' + extension;

      return req([textName], function (template) {
          var templateName = name;
          Ember.TEMPLATES[templateName] = Ember.Handlebars.compile(template);
          load(templateName);
        }
      );
    }
  }

  return hbs;
});
<|endoftext|>


<commit_before>'use strict'
module.exports = function (protocol, key) {
  describe('reconnect', function () {
    var a, b, receiver
    var Hub = require('../../lib')
    var mock = key === 'mock'

    it('can create multiple hubs', function () {
      a = new Hub({
        key: 'server_reconnect_a',
        adapter: {
          id: 'server_reconnect_a',
          inject: protocol
        }
      })
      b = new Hub({
        key: 'server_reconnect_b',
        adapter: {
          id: 'server_reconnect_b',
          inject: protocol
        }
      })
      receiver = new Hub({
        key: 'receiver_reconnect',
        adapter: {
          id: 'receiver_reconnect',
          inject: protocol,
          [key]: {}
        }
      })
      a.adapter.set({ [key]: { server: mock ? 'server_reconnect_a' : 6002 } })
      b.adapter.set({ [key]: { server: mock ? 'server_reconnect_b' : 6003 } })
    })

    it('can connect to server_a', function (done) {
      // ok so wait with sendeing connect
      receiver.adapter[key].once('connect', function () {
        a.get('clients', {}).once(function () {
          expect(a.clients).to.have.property('receiver_reconnect')
          done()
        })
      })
      receiver.adapter[key].val = mock ? 'server_reconnect_a' : 'ws://localhost:6002'
    })

    it('connected should be true', function () {
      expect(receiver.adapter[key].connected.val).to.equal(true)
    })

    it('can connect to another server server_b', function (done) {
      receiver.adapter[key].once('connect', function () {
        // expect(b.clients).to.have.property('receiver_reconnect').which.is.ok
        // expect(a.clients['receiver_reconnect']).to.not.be.ok
        done()
      })
      receiver.adapter[key].val = mock ? 'server_reconnect_b' : 'ws://localhost:6003'
    })

    it('can connect to another server server_a', function (done) {
      receiver.adapter[key].once('connect', function () {
        // expect(a.clients).to.have.property('receiver_reconnect').which.is.ok
        // expect(b.clients['return  ;eceiver_reconnect']).to.not.be.ok
        done()
      })
      receiver.adapter[key].val = mock ? 'server_reconnect_a' : 'ws://localhost:6002'
    })

    it('server connections gets removed, client reconnects after 1 attempt', function (done) {
      // nested callbacks to test order
      receiver.adapter[key].once('close', function () {
        // close connection if no other clients? no wrong!
        expect(receiver.adapter[key].connected.val).to.equal(false)
        this.once('reconnect', function () {
          this.once('connect', done)
        })
      })
      // does not result in a close fire
      // make a protocol .close method or something or disconnect
      // client.disconnect // protocol.disconnect
      a.clients['receiver_reconnect'].connection.origin.remove()
    })
  })
}
<commit_msg>added checks that make the tests fail in websocket (client checkups)<commit_after>'use strict'
module.exports = function (protocol, key) {
  describe('reconnect', function () {
    var a, b, receiver
    var Hub = require('../../lib')
    var mock = key === 'mock'

    it('can create multiple hubs', function () {
      a = new Hub({
        key: 'server_reconnect_a',
        adapter: {
          id: 'server_reconnect_a',
          inject: protocol
        }
      })
      b = new Hub({
        key: 'server_reconnect_b',
        adapter: {
          id: 'server_reconnect_b',
          inject: protocol
        }
      })
      receiver = new Hub({
        key: 'receiver_reconnect',
        adapter: {
          id: 'receiver_reconnect',
          inject: protocol,
          [key]: {}
        }
      })
      a.adapter.set({ [key]: { server: mock ? 'server_reconnect_a' : 6002 } })
      b.adapter.set({ [key]: { server: mock ? 'server_reconnect_b' : 6003 } })
    })

    it('can connect to server_a', function (done) {
      receiver.adapter[key].once('connect', function () {
        a.get('clients', {}).once(function () {
          expect(a.clients).to.have.property('receiver_reconnect')
          done()
        })
      })
      receiver.adapter[key].val = mock ? 'server_reconnect_a' : 'ws://localhost:6002'
    })

    it('connected should be true', function () {
      expect(receiver.adapter[key].connected.val).to.equal(true)
    })

    it('can connect to another server server_b', function (done) {
      receiver.adapter[key].once('connect', function () {
        // console.log('ok ok ok ok ok')
        // expect(b.clients).to.have.property('receiver_reconnect').which.is.ok
      })

      b.get('clients', {}).once(function () {
        // console.log('ok ok ok ok ok')
        expect(a.clients['receiver_reconnect']).to.not.be.ok
        done()
      })
      receiver.adapter[key].val = mock ? 'server_reconnect_b' : 'ws://localhost:6003'
    })

    it('can connect to another server server_a', function (done) {
      receiver.adapter[key].once('connect', function () {
        // expect(a.clients).to.have.property('receiver_reconnect').which.is.ok
        // expect(b.clients['return  ;eceiver_reconnect']).to.not.be.ok
        done()
      })
      receiver.adapter[key].val = mock ? 'server_reconnect_a' : 'ws://localhost:6002'
    })

    it('server connections gets removed, client reconnects after 1 attempt', function (done) {
      receiver.adapter[key].once('close', function () {
        expect(receiver.adapter[key].connected.val).to.equal(false)
        this.once('reconnect', function () {
          this.once('connect', done)
        })
      })
      // does not result in a close fire
      // make a protocol .close method or something or disconnect
      // client.disconnect // protocol.disconnect
      a.clients['receiver_reconnect'].connection.origin.remove()
    })
  })
}
<|endoftext|>


<commit_before>module.exports = {

    //---------------------------------------------------------------------
    // Action Name
    //
    // This is the name of the action displayed in the editor.
    //---------------------------------------------------------------------

    name: "File Control",

    //---------------------------------------------------------------------
    // Action Section
    //
    // This is the section the action will fall into.
    //---------------------------------------------------------------------

    section: "File Stuff",

    //---------------------------------------------------------------------
        // DBM Mods Manager Variables (Optional but nice to have!)
        //
        // These are variables that DBM Mods Manager uses to show information
        // about the mods for people to see in the list.
    //---------------------------------------------------------------------

        // Who made the mod (If not set, defaults to "DBM Mods")
        author: "Danno3187", //Original Idea by EliteArtz

        // The version of the mod (Defaults to 1.0.0)
        version: "1.8.7", //Added in 1.8.7

        // A short description to show on the mod line for this mod (Must be on a single line)
        short_description: "Allows a user to interact with 'Files'",

    //---------------------------------------------------------------------
        // If it depends on any other mods by name, ex: WrexMODS if the mod uses something from WrexMods

    //---------------------------------------------------------------------

    //---------------------------------------------------------------------
    // Action Subtitle
    //
    // This function generates the subtitle displayed next to the name.
    //---------------------------------------------------------------------

    subtitle: function(data) {
        const filetasks = ['Create', 'Write', 'Append', 'Delete'];
        return `${filetasks[parseInt(data.filetask)]} ${data.filename}${data.format}`;
    },

    //---------------------------------------------------------------------
    // Action Fields
    //
    // These are the fields for the action. These fields are customized
    // by creating elements with corresponding IDs in the HTML. These
    // are also the names of the fields stored in the action's JSON data.
    //---------------------------------------------------------------------

    fields: ["input", "format", "filename", "filepath", "filetask"],

    //---------------------------------------------------------------------
    // Command HTML
    //
    // This function returns a string containing the HTML used for
    // editting actions.
    //
    // The "isEvent" parameter will be true if this action is being used
    // for an event. Due to their nature, events lack certain information,
    // so edit the HTML to reflect this.
    //
    // The "data" parameter stores constants for select elements to use.
    // Each is an array: index 0 for commands, index 1 for events.
    // The names are: sendTargets, members, roles, channels,
    //                messages, servers, variables
    //---------------------------------------------------------------------

    html: function(isEvent, data) {
        return `

        Mod Info

        Made by Danno3817, EliteArtz & EGGSY

                File Format:

                <select id="format" class="round">
                <option value=".json">JSON</option>
                <option value=".txt">TXT</option>
                <option value=".js">JS</option>
                <option value=".log" selected>LOG</option>
                </select>

                File Task:

                <select id="filetask" class="round">
                <option value="0" selected>Create</option>
                <option value="1">Write</option>
                <option value="2">Append</option>
                <option value="3">Delete</option>
                </select>

                File Name:

                <textarea id="filename" placeholder="Insert File Name Here..." class="round" style="width 50%; resize: none; padding: 4px 0px;" type="textarea" rows="1" cols="25";></textarea>

                File Path:

                <textarea id="filepath" placeholder="Insert Path Here... Example Below" class="round" style="width99%; resize: none;" type="textarea" rows="1" cols="60"></textarea>

            Input Text:

            <textarea id="input" placeholder="Leave Blank For None." class="round" style="width: 99%; resize: 1;" type="textarea" rows="8" cols="35"></textarea>

Important info:

            You'll need a '/' at the end of the Path '\\\' for windows users.

            If you want to delete something in current directory, you can add '.' (dot) before '/':

            e.g:

            My bot directory is: "/root/myBot/"

            I want to delete: "/root/myBot/delete.txt"

            Then I need to write "./delete.txt" in the field.

            Please be careful while using this mod. Don't forget there is no turning back after deleting the file.

`
    },

    //---------------------------------------------------------------------
    // Action Editor Init Code
    //
    // When the HTML is first applied to the action editor, this code
    // is also run. This helps add modifications or setup reactionary
    // functions for the DOM elements.
    //---------------------------------------------------------------------

    init: function() {},

    //---------------------------------------------------------------------
    // Action Bot Function
    //
    // This is the function for the action within the Bot's Action class.
    // Keep in mind event calls won't have access to the "msg" parameter,
    // so be sure to provide checks for variable existance.
    //---------------------------------------------------------------------

    action: function (cache) {
        const data = cache.actions[cache.index];

        const fileNAME = this.evalMessage(data.filename, cache);
        const filePATH = this.evalMessage(data.filepath, cache);
        const FullFile = filePATH + fileNAME + `${data.format}`;
        const fs = require('fs');

        const task = parseInt(data.filetask);

        const inputtext = this.evalMessage(data.input, cache);

        switch(task){
            case 0: //Create
            console.log("Create File Activated");
            try {
                if (filePATH){
                    if (fileNAME) {
                        fs.writeFileSync(FullFile,"");
                    }else {
                        console.log("File name is missing.");
                    }
                }else{
                console.log("File path is missing.");
                }
            }catch (err){
                console.log("ERROR!" + err.stack ? err.stack : err);
            }this.callNextAction(cache);
            break;

            case 1: //Write
            try{
                if (filePATH){
                    if (fileNAME) {
                        fs.writeFileSync(FullFile, inputtext);
                    }else {
                        console.log("File name is missing.");
                    }
                }else{
                console.log("File path is missing.");
                }
            } catch (err) {
                console.log("ERROR!" + err.stack ? err.stack : err);
            }this.callNextAction(cache);
            break;

            case 2: //Append
            try {
                if (filePATH && fileNAME){
                    fs.appendFileSync(FullFile, inputtext + '\r\n' );
                }else{
                console.log("File name or File path is missing.");
                }
            }catch (err){
                console.log("ERROR!" + err.stack ? err.stack : err);
            }this.callNextAction(cache);
            break;

            case 3: //Delete
            try {
                if (filePATH) {
                    fs.exists(`${FullFile}`, function(exists) {
                        if(exists) {
                            fs.unlink(FullFile, (err) => {
                                if (err) return console.log(`Something went wrong while deleting: [${err}]`);
                              });
                        } else {
                            console.log('File not found, nothing to delete.');
                        }
                      });
                } else {
                console.log(`File path is missing.`);
                }
            } catch (err) {
                console.log("ERROR!" + err.stack ? err.stack : err);
            }
            this.callNextAction(cache);
            break;

        }
        this.callNextAction(cache);
    },

    //---------------------------------------------------------------------
    // Action Bot Mod
    //
    // Upon initialization of the bot, this code is run. Using the bot's
    // DBM namespace, one can add/modify existing functions if necessary.
    // In order to reduce conflictions between mods, be sure to alias
    // functions you wish to overwrite.
    //---------------------------------------------------------------------

    mod: function(DBM) {
    }

    }; // End of module
<commit_msg>UI update<commit_after>module.exports = {

    //---------------------------------------------------------------------
    // Action Name
    //
    // This is the name of the action displayed in the editor.
    //---------------------------------------------------------------------

    name: "File Control",

    //---------------------------------------------------------------------
    // Action Section
    //
    // This is the section the action will fall into.
    //---------------------------------------------------------------------

    section: "File Stuff",

    //---------------------------------------------------------------------
        // DBM Mods Manager Variables (Optional but nice to have!)
        //
        // These are variables that DBM Mods Manager uses to show information
        // about the mods for people to see in the list.
    //---------------------------------------------------------------------

        // Who made the mod (If not set, defaults to "DBM Mods")
        author: "Danno3187", //Original Idea by EliteArtz

        // The version of the mod (Defaults to 1.0.0)
        version: "1.8.7", //Added in 1.8.7

        // A short description to show on the mod line for this mod (Must be on a single line)
        short_description: "Allows a user to interact with 'Files'",

    //---------------------------------------------------------------------
        // If it depends on any other mods by name, ex: WrexMODS if the mod uses something from WrexMods

    //---------------------------------------------------------------------

    //---------------------------------------------------------------------
    // Action Subtitle
    //
    // This function generates the subtitle displayed next to the name.
    //---------------------------------------------------------------------

    subtitle: function(data) {
        const filetasks = ['Create', 'Write', 'Append', 'Delete'];
        return `${filetasks[parseInt(data.filetask)]} ${data.filename}${data.format}`;
    },

    //---------------------------------------------------------------------
    // Action Fields
    //
    // These are the fields for the action. These fields are customized
    // by creating elements with corresponding IDs in the HTML. These
    // are also the names of the fields stored in the action's JSON data.
    //---------------------------------------------------------------------

    fields: ["input", "format", "filename", "filepath", "filetask"],

    //---------------------------------------------------------------------
    // Command HTML
    //
    // This function returns a string containing the HTML used for
    // editting actions.
    //
    // The "isEvent" parameter will be true if this action is being used
    // for an event. Due to their nature, events lack certain information,
    // so edit the HTML to reflect this.
    //
    // The "data" parameter stores constants for select elements to use.
    // Each is an array: index 0 for commands, index 1 for events.
    // The names are: sendTargets, members, roles, channels,
    //                messages, servers, variables
    //---------------------------------------------------------------------

    html: function(isEvent, data) {
        return `

Mod Info:

              Made By: Danno3817, EliteArtz & Eggsy

Important Info:

              You'll need a '/' at the end of the Path.

              If you want to delete something in current directory, you can add '.' (dot) before '/':

              e.g:

              My bot directory is: "/root/myBot/"

              I want to delete: "/root/myBot/delete.txt"

              Then I need to write "./" in the file path field.

              Please be careful while using the delete function, there is no turning back after deleting the file.

            Format:

            <select id="format" class="round">
              <option value=".json">JSON</option>
              <option value=".txt">txt</option>
              <option value=".js">Java Script</option>
              <option value=".log" selected>Log</option>
            </select>

            Task:

            <select id="filetask" class="round">
              <option value="0" selected>Create</option>
              <option value="1">Write</option>
              <option value="2">Append</option>
              <option value="3">Delete</option>
            </select>

            File Name:

            <textarea id="filename" placeholder=" Insert File Name Here..." class="round" style="width: 100%; resize: none; padding: 4px 0px;" type="textarea" rows="1";></textarea>

            File Path:

            <textarea id="filepath" placeholder=" Example Path = ./logs/date/example-date/" class="round" style="width: 99%; resize: none; padding: 4px 0px;" type="textarea" rows="1" cols="60"></textarea>

            Input Text:

            <textarea id="input" placeholder=" Leave Blank For None." class="round" style="width: 99%; resize: 1; padding: 4px 0px;" type="textarea" rows="8" cols="35"></textarea>

`
    },

    //---------------------------------------------------------------------
    // Action Editor Init Code
    //
    // When the HTML is first applied to the action editor, this code
    // is also run. This helps add modifications or setup reactionary
    // functions for the DOM elements.
    //---------------------------------------------------------------------

    init: function() {},

    //---------------------------------------------------------------------
    // Action Bot Function
    //
    // This is the function for the action within the Bot's Action class.
    // Keep in mind event calls won't have access to the "msg" parameter,
    // so be sure to provide checks for variable existance.
    //---------------------------------------------------------------------

    action: function (cache) {
        const data = cache.actions[cache.index];

        const fileNAME = this.evalMessage(data.filename, cache);
        const filePATH = this.evalMessage(data.filepath, cache);
        const FullFile = filePATH + fileNAME + `${data.format}`;
        const fs = require('fs');

        const task = parseInt(data.filetask);

        const inputtext = this.evalMessage(data.input, cache);

        switch(task){
            case 0: //Create
            console.log("Create File Activated");
            try {
                if (filePATH){
                    if (fileNAME) {
                        fs.writeFileSync(FullFile,"");
                    }else {
                        console.log("File name is missing.");
                    }
                }else{
                console.log("File path is missing.");
                }
            }catch (err){
                console.log("ERROR!" + err.stack ? err.stack : err);
            }this.callNextAction(cache);
            break;

            case 1: //Write
            try{
                if (filePATH){
                    if (fileNAME) {
                        fs.writeFileSync(FullFile, inputtext);
                    }else {
                        console.log("File name is missing.");
                    }
                }else{
                console.log("File path is missing.");
                }
            } catch (err) {
                console.log("ERROR!" + err.stack ? err.stack : err);
            }this.callNextAction(cache);
            break;

            case 2: //Append
            try {
                if (filePATH && fileNAME){
                    fs.appendFileSync(FullFile, inputtext + '\r\n' );
                }else{
                console.log("File name or File path is missing.");
                }
            }catch (err){
                console.log("ERROR!" + err.stack ? err.stack : err);
            }this.callNextAction(cache);
            break;

            case 3: //Delete
            try {
                if (filePATH) {
                    fs.exists(`${FullFile}`, function(exists) {
                        if(exists) {
                            fs.unlink(FullFile, (err) => {
                                if (err) return console.log(`Something went wrong while deleting: [${err}]`);
                              });
                        } else {
                            console.log('File not found, nothing to delete.');
                        }
                      });
                } else {
                console.log(`File path is missing.`);
                }
            } catch (err) {
                console.log("ERROR!" + err.stack ? err.stack : err);
            }
            this.callNextAction(cache);
            break;

        }
        this.callNextAction(cache);
    },

    //---------------------------------------------------------------------
    // Action Bot Mod
    //
    // Upon initialization of the bot, this code is run. Using the bot's
    // DBM namespace, one can add/modify existing functions if necessary.
    // In order to reduce conflictions between mods, be sure to alias
    // functions you wish to overwrite.
    //---------------------------------------------------------------------

    mod: function(DBM) {
    }

    }; // End of module
<|endoftext|>


<commit_before>module.exports = {

//---------------------------------------------------------------------
// Action Name
//
// This is the name of the action displayed in the editor.
//---------------------------------------------------------------------

name: "Find Message",

//---------------------------------------------------------------------
// Action Section
//
// This is the section the action will fall into.
//---------------------------------------------------------------------

section: "Messaging",

//---------------------------------------------------------------------
// Action Subtitle
//
// This function generates the subtitle displayed next to the name.
//---------------------------------------------------------------------

subtitle: function(data) {
	const channels = ['Same Channel', 'Mentioned Channel', '1st Server Channel', 'Temp Variable', 'Server Variable', 'Global Variable'];
	const info = ['Find by Content', 'Find by ID'];
	return `${channels[parseInt(data.channel)]} - ${info[parseInt(data.info)]}`;
},

	//---------------------------------------------------------------------
	 // DBM Mods Manager Variables (Optional but nice to have!)
	 //
	 // These are variables that DBM Mods Manager uses to show information
	 // about the mods for people to see in the list.
	 //---------------------------------------------------------------------

	 // Who made the mod (If not set, defaults to "DBM Mods")
	 author: "Lasse",

	 // The version of the mod (Defaults to 1.0.0)
	 version: "1.8.7", //Added in 1.8.5

	 // A short description to show on the mod line for this mod (Must be on a single line)
	 short_description: "Finds a message by content or ID.",

	 // If it depends on any other mods by name, ex: WrexMODS if the mod uses something from WrexMods

	 //---------------------------------------------------------------------

//---------------------------------------------------------------------
// Action Storage Function
//
// Stores the relevant variable info for the editor.
//---------------------------------------------------------------------

variableStorage: function(data, varType) {
	const type = parseInt(data.storage);
	if(type !== varType) return;
	const info = parseInt(data.info);
	let dataType = 'Message';
	return ([data.varName2, dataType]);
},

//---------------------------------------------------------------------
// Action Fields
//
// These are the fields for the action. These fields are customized
// by creating elements with corresponding IDs in the HTML. These
// are also the names of the fields stored in the action's JSON data.
//---------------------------------------------------------------------

fields: ["channel", "varName", "info", "search", "storage", "varName2"],

//---------------------------------------------------------------------
// Command HTML
//
// This function returns a string containing the HTML used for
// editting actions.
//
// The "isEvent" parameter will be true if this action is being used
// for an event. Due to their nature, events lack certain information,
// so edit the HTML to reflect this.
//
// The "data" parameter stores constants for select elements to use.
// Each is an array: index 0 for commands, index 1 for events.
// The names are: sendTargets, members, roles, channels,
//                messages, servers, variables
//---------------------------------------------------------------------

html: function(isEvent, data) {
	return `

		Mod Info:

		Created by Lasse!

		Source Channel:

		<select id="channel" class="round" onchange="glob.channelChange(this, 'varNameContainer')">
			${data.channels[isEvent ? 1 : 0]}
		</select>

		Variable Name:

		<input id="varName" class="round" type="text" list="variableList">

		Find by:

		<select id="info" class="round">
			<option value="0" selected>Find by Content</option>
			<option value="1">Find by ID</option>
		</select>

		Search for:

		<input id="search" class="round" type="text">

		Store In:

		<select id="storage" class="round">
			${data.variables[1]}
		</select>

		Variable Name:

		<input id="varName2" class="round" type="text">

	Note:

	This mod can only find messages which have been sent after the bot started.

	If there are multiple messages with the same content, the bot is always using the oldest message (after start).

`
},

//---------------------------------------------------------------------
// Action Editor Init Code
//
// When the HTML is first applied to the action editor, this code
// is also run. This helps add modifications or setup reactionary
// functions for the DOM elements.
//---------------------------------------------------------------------

init: function() {
	const {glob, document} = this;

	glob.channelChange(document.getElementById('channel'), 'varNameContainer');
},

//---------------------------------------------------------------------
// Action Bot Function
//
// This is the function for the action within the Bot's Action class.
// Keep in mind event calls won't have access to the "msg" parameter,
// so be sure to provide checks for variable existance.
//---------------------------------------------------------------------

action: function(cache) {
	const data = cache.actions[cache.index];
	const channel = parseInt(data.channel);
	const varName = this.evalMessage(data.varName, cache);
	const info = parseInt(data.info);
	const search = this.evalMessage(data.search, cache);
	const targetChannel = this.getChannel(channel, varName, cache);
	if(!targetChannel) {
		this.callNextAction(cache);
		return;
	}
	let result;
	switch(info) {
		case 0:
			result = targetChannel.messages.find("content", search);
			break;
		case 1:
			result = targetChannel.messages.find("id", search);
			break;
		default:
			break;
	}
	if(result !== undefined) {
		const storage = parseInt(data.storage);
		const varName2 = this.evalMessage(data.varName2, cache);
		this.storeValue(result, storage, varName2, cache);
	}
	this.callNextAction(cache);
},

//---------------------------------------------------------------------
// Action Bot Mod
//
// Upon initialization of the bot, this code is run. Using the bot's
// DBM namespace, one can add/modify existing functions if necessary.
// In order to reduce conflictions between mods, be sure to alias
// functions you wish to overwrite.
//---------------------------------------------------------------------

mod: function(DBM) {
}

}; // End of module
<commit_msg>[Find Message] Was updated to use fetch. (No more only new messages)<commit_after>module.exports = {

//---------------------------------------------------------------------
// Action Name
//
// This is the name of the action displayed in the editor.
//---------------------------------------------------------------------

name: "Find Message",

//---------------------------------------------------------------------
// Action Section
//
// This is the section the action will fall into.
//---------------------------------------------------------------------

section: "Messaging",

//---------------------------------------------------------------------
// Action Subtitle
//
// This function generates the subtitle displayed next to the name.
//---------------------------------------------------------------------

subtitle: function(data) {
	const channels = ['Same Channel', 'Mentioned Channel', '1st Server Channel', 'Temp Variable', 'Server Variable', 'Global Variable'];
	const info = ['Find by Content', 'Find by ID'];
	return `${channels[parseInt(data.channel)]} - ${info[parseInt(data.info)]}`;
},

	//---------------------------------------------------------------------
	 // DBM Mods Manager Variables (Optional but nice to have!)
	 //
	 // These are variables that DBM Mods Manager uses to show information
	 // about the mods for people to see in the list.
	 //---------------------------------------------------------------------

	 // Who made the mod (If not set, defaults to "DBM Mods")
	 author: "Lasse",

	 // The version of the mod (Defaults to 1.0.0)
	 version: "1.8.7", //Added in 1.8.5

	 // A short description to show on the mod line for this mod (Must be on a single line)
	 short_description: "Finds a message by content or ID.",

	 // If it depends on any other mods by name, ex: WrexMODS if the mod uses something from WrexMods

	 //---------------------------------------------------------------------

//---------------------------------------------------------------------
// Action Storage Function
//
// Stores the relevant variable info for the editor.
//---------------------------------------------------------------------

variableStorage: function(data, varType) {
	const type = parseInt(data.storage);
	if(type !== varType) return;
	const info = parseInt(data.info);
	let dataType = 'Message';
	return ([data.varName2, dataType]);
},

//---------------------------------------------------------------------
// Action Fields
//
// These are the fields for the action. These fields are customized
// by creating elements with corresponding IDs in the HTML. These
// are also the names of the fields stored in the action's JSON data.
//---------------------------------------------------------------------

fields: ["channel", "varName", "info", "search", "storage", "varName2"],

//---------------------------------------------------------------------
// Command HTML
//
// This function returns a string containing the HTML used for
// editting actions.
//
// The "isEvent" parameter will be true if this action is being used
// for an event. Due to their nature, events lack certain information,
// so edit the HTML to reflect this.
//
// The "data" parameter stores constants for select elements to use.
// Each is an array: index 0 for commands, index 1 for events.
// The names are: sendTargets, members, roles, channels,
//                messages, servers, variables
//---------------------------------------------------------------------

html: function(isEvent, data) {
	return `

		Mod Info:

		Created by Lasse!
		Modified by General Wrex!

		Source Channel:

		<select id="channel" class="round" onchange="glob.channelChange(this, 'varNameContainer')">
			${data.channels[isEvent ? 1 : 0]}
		</select>

		Variable Name:

		<input id="varName" class="round" type="text" list="variableList">

		Find by:

		<select id="info" class="round">
			<option value="0" selected>Find by Content</option>
			<option value="1">Find by ID</option>
		</select>

		Search for:

		<input id="search" class="round" type="text">

		Store In:

		<select id="storage" class="round">
			${data.variables[1]}
		</select>

		Variable Name:

		<input id="varName2" class="round" type="text">

	Note:

	This mod can only find messages by content within the last 100 messages.

	If there are multiple messages with the same content, the bot is always using the oldest message (after start).

`;
},

//---------------------------------------------------------------------
// Action Editor Init Code
//
// When the HTML is first applied to the action editor, this code
// is also run. This helps add modifications or setup reactionary
// functions for the DOM elements.
//---------------------------------------------------------------------

init: function() {
	const {glob, document} = this;

	glob.channelChange(document.getElementById('channel'), 'varNameContainer');
},

//---------------------------------------------------------------------
// Action Bot Function
//
// This is the function for the action within the Bot's Action class.
// Keep in mind event calls won't have access to the "msg" parameter,
// so be sure to provide checks for variable existance.
//---------------------------------------------------------------------

action: function(cache) {
	const data = cache.actions[cache.index];
	const channel = parseInt(data.channel);
	const varName = this.evalMessage(data.varName, cache);
	const info = parseInt(data.info);
	const search = this.evalMessage(data.search, cache);
	const targetChannel = this.getChannel(channel, varName, cache);
	if(!targetChannel) {
		this.callNextAction(cache);
		return;
	}

	const storage = parseInt(data.storage);
	const varName2 = this.evalMessage(data.varName2, cache);

	let result;
	switch(info) {
		case 0:
			targetChannel.fetchMessages({ limit: 100 }).then(messages =>{
				const message = messages.find(el => el.content.includes(search));
				if(message !== undefined){
					this.storeValue(message, storage, varName2, cache);
				}
				this.callNextAction(cache);
			}).catch(err=>{
				console.error(err);
				this.callNextAction(cache);
			});
			break;
		case 1:
			targetChannel.fetchMessage(search).then(message =>{
				if(message !== undefined){
					this.storeValue(message, storage, varName2, cache);
				}
				this.callNextAction(cache);
			}).catch(err=>{
				console.error(err);
				this.callNextAction(cache);
			});
			break;
		default:
			break;
	}
},

//---------------------------------------------------------------------
// Action Bot Mod
//
// Upon initialization of the bot, this code is run. Using the bot's
// DBM namespace, one can add/modify existing functions if necessary.
// In order to reduce conflictions between mods, be sure to alias
// functions you wish to overwrite.
//---------------------------------------------------------------------

mod: function(DBM) {
}

}; // End of module
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');

var inFile = process.argv[2];
var outFile = process.argv[3];
var fullInFile = path.resolve(process.cwd(), inFile || '');
var fullOutFile = path.resolve(process.cwd(), outFile || '');
var fileContent = null;
var characters = [];
var charWidths = [];
var output = null;

var font = {
	meta: {
		monospaced: true,
		charWidth: -1,
		lineHeight: -1
	},
	chars: {}
};

if (!inFile) {
	return console.log('Please specify a filename as input.');
}

if (!fs.existsSync(fullInFile)) {
	return console.log('File:', fullInFile, 'does not exist.');
}

fileContent = fs.readFileSync(fullInFile).toString('utf-8');
characters = fileContent.split(/\n\n/).map(function (character) {
	return character.split(/\n/);
});

font.meta.charWidth = characters.reduce(charWidth, 0);
font.meta.lineHeight = characters.reduce(charHeight, 0);

for (var i = 0; i < characters.length; i += 1) {
	var charData = characters[i];
	var identifier = charData.shift().replace('# ', '');
	var charBuffer = generateCharData(charData);

	var xBuffer = charBuffer.map(function (blob) {
		return blob[0];
	});

	var width = Math.max.apply(Math, xBuffer) + 1;
	charWidths.push(width);

	font.chars[identifier] = {
		data: charBuffer,
		width: width
	};
}

if (Math.max.apply(Math, charWidths) !== Math.min.apply(Math, charWidths)) {
	font.meta.monospaced = false;
}

output = JSON.stringify(font, null, 2);
if (!outFile) {
	console.log(output);
} else {
	fs.writeFileSync(fullOutFile, output);
}

function charWidth(initial, character) {
	var lineLengths = character.map(function (line) { return line.length; });
	var maxLength = Math.max.apply(Math, lineLengths);
	return maxLength > initial ? maxLength : initial;
}

function charHeight(initial, character) {
	var len = character.length - 2;
	return len > initial ? len : initial;
}

function generateCharData(character) {
	var coords = [];
	for (var y = 0; y < character.length; y += 1) {
		var line = character[y];

		for (var x = 0; x < line.length; x += 1) {
			if ([' ', '#', '.'].indexOf(line.charAt(x)) === -1) {
				coords.push([x, y]);
			}
		}
	}
	return coords;
}
<commit_msg>cleanup (charbuffer, xbuffer, width)<commit_after>var fs = require('fs');
var path = require('path');

var inFile = process.argv[2];
var outFile = process.argv[3];
var fullInFile = path.resolve(process.cwd(), inFile || '');
var fullOutFile = path.resolve(process.cwd(), outFile || '');
var fileContent = null;
var characters = [];
var charWidths = [];
var output = null;

var font = {
	meta: {
		monospaced: true,
		charWidth: -1,
		lineHeight: -1
	},
	chars: {}
};

if (!inFile) {
	return console.log('Please specify a filename as input.');
}

if (!fs.existsSync(fullInFile)) {
	return console.log('File:', fullInFile, 'does not exist.');
}

fileContent = fs.readFileSync(fullInFile).toString('utf-8');
characters = fileContent.split(/\n\n/).map(function (character) {
	return character.split(/\n/);
});

font.meta.charWidth = characters.reduce(charWidth, 0);
font.meta.lineHeight = characters.reduce(charHeight, 0);

for (var i = 0; i < characters.length; i += 1) {
	var charData = characters[i];
	var identifier = charData.shift().replace('# ', '');

	font.chars[identifier] = {
		data: generateCharData(charData),
		width: charWidth(0, charData)
	};
}

if (Math.max.apply(Math, charWidths) !== Math.min.apply(Math, charWidths)) {
	font.meta.monospaced = false;
}

output = JSON.stringify(font, null, 2);
if (!outFile) {
	console.log(output);
} else {
	fs.writeFileSync(fullOutFile, output);
}

function charWidth(initial, character) {
	var lineLengths = character.map(function (line) { return line.length; });
	var maxLength = Math.max.apply(Math, lineLengths);
	return maxLength > initial ? maxLength : initial;
}

function charHeight(initial, character) {
	var len = character.length - 2;
	return len > initial ? len : initial;
}

function generateCharData(character) {
	var coords = [];
	for (var y = 0; y < character.length; y += 1) {
		var line = character[y];

		for (var x = 0; x < line.length; x += 1) {
			if ([' ', '#', '.'].indexOf(line.charAt(x)) === -1) {
				coords.push([x, y]);
			}
		}
	}
	return coords;
}
<|endoftext|>


<commit_before>const digits = new Set('0123456789')
const isDigit = x => digits.has(x)

/**
 * @param {string} word
 * @param {string} abbr
 * @return {boolean}
 */
const validWordAbbreviation = (word, abbrRaw) => {
  // convert abbr into an array of either strings or numbers.
  let abbrList = []
  for (let i = 0; i < abbrRaw.length; /* NOOP */) {
    const ch = abbrRaw[i]
    if (isDigit(ch)) {
      let j = i
      while (j+1 < abbrRaw.length && isDigit(abbrRaw[j+1]))
             ++j
      // a "takeWhile"
      const d = abbrRaw.slice(i,j+1)
      // invalid abbr because the digit starts with 0
      if (d[0] === '0')
        return false
      abbrList.push(Number(d))
      i = j+1
    } else {
      let j = i
      while (j+1 < abbrRaw.length && !isDigit(abbrRaw[j+1]))
             ++j
      const w = abbrRaw.slice(i,j+1)
      abbrList.push(w)
      i = j+1
    }
  }

  // match string
  let startInd = 0
  for (let i = 0; i < abbrList.length; ++i) {
    const abbr = abbrList[i]
    if (typeof abbr === 'number') {
      if (startInd + abbr - 1 >= word.length)
        return false
      startInd += abbr
    } else {
      if (word.substr(startInd, abbr.length) !== abbr)
        return false
      startInd += abbr.length
    }
  }
  return startInd === word.length
}

console.assert(validWordAbbreviation("word", "word"))
console.assert(validWordAbbreviation("internationalization","i12iz4n"))
console.assert(!validWordAbbreviation("inernationalization","i12iz4n"))
console.assert(!validWordAbbreviation("internationalizatiot","i12iz4n"))
<commit_msg>optimize<commit_after>const digitsTmp = new Array(256)
'0123456789'.split('').map(ch => { digitsTmp[ch.codePointAt(0)] = true })
const isDigit = x => Boolean(digitsTmp[x.codePointAt(0)])

/**
 * @param {string} word
 * @param {string} abbr
 * @return {boolean}
 */
const validWordAbbreviation = (word, abbrRaw) => {
  // match string
  let startInd = 0
  const tryMatch = abbr => {
    if (typeof abbr === 'number') {
      if (startInd + abbr - 1 >= word.length)
        return false
      startInd += abbr
    } else {
      if (word.substr(startInd, abbr.length) !== abbr)
        return false
      startInd += abbr.length
    }
    return true
  }

  // convert abbr into an array of either strings or numbers.
  for (let i = 0; i < abbrRaw.length; /* NOOP */) {
    const ch = abbrRaw[i]
    if (isDigit(ch)) {
      let j = i
      while (j+1 < abbrRaw.length && isDigit(abbrRaw[j+1]))
             ++j
      // a "takeWhile"
      const d = abbrRaw.slice(i,j+1)
      // invalid abbr because the digit starts with 0
      if (d[0] === '0')
        return false
      if (!tryMatch(Number(d)))
        return false
      i = j+1
    } else {
      let j = i
      while (j+1 < abbrRaw.length && !isDigit(abbrRaw[j+1]))
             ++j
      const w = abbrRaw.slice(i,j+1)
      if (!tryMatch(w))
        return false
      i = j+1
    }
  }
  return startInd === word.length
}

console.assert(validWordAbbreviation("word", "word"))
console.assert(validWordAbbreviation("internationalization","i12iz4n"))
console.assert(!validWordAbbreviation("inernationalization","i12iz4n"))
console.assert(!validWordAbbreviation("internationalizatiot","i12iz4n"))
<|endoftext|>


<commit_before>
var sl = require('..');

var list = [
    { id: 1, name: 'Adam', age: 800, gender: 'man' },
    { id: 2, name: 'Eve', age: 600, gender: 'woman' },
    { id: 3, name: 'Abel', age: 500, gender: 'man' },
    { id: 4, name: 'Caine', age: 400, gender: 'man' }
];

exports['all with age'] = function (test) {
    test.ok(sl.all(list, "age"));
}

exports['all with age and name'] = function (test) {
    test.ok(sl.all(list, [ "age", "name" ]));
}

exports['all with age, name and parents'] = function (test) {
    test.ok(!sl.all(list, [ "age", "name", "parents" ]));
}

exports['all with positive age'] = function (test) {
    test.ok(sl.all(list, function (obj) { return obj.age > 0; }));
}

exports['all with age, name and parents on empty objects list'] = function (test) {
    test.ok(!sl.all([ {}, {} ], [ "age", "name", "parents" ]));
}
<commit_msg>Refactor all tests<commit_after>
const sl = require('..');

const list = [
    { id: 1, name: 'Adam', age: 800, gender: 'man' },
    { id: 2, name: 'Eve', age: 600, gender: 'woman' },
    { id: 3, name: 'Abel', age: 500, gender: 'man' },
    { id: 4, name: 'Caine', age: 400, gender: 'man' }
];

exports['all with age'] = function (test) {
    test.ok(sl.all(list, "age"));
}

exports['all with age and name'] = function (test) {
    test.ok(sl.all(list, [ "age", "name" ]));
}

exports['all with age, name and parents'] = function (test) {
    test.ok(!sl.all(list, [ "age", "name", "parents" ]));
}

exports['all with positive age'] = function (test) {
    test.ok(sl.all(list, function (obj) { return obj.age > 0; }));
}

exports['all with age, name and parents on empty objects list'] = function (test) {
    test.ok(!sl.all([ {}, {} ], [ "age", "name", "parents" ]));
}
<|endoftext|>


<commit_before>/* eslint-env mocha */
'use strict';

const os = require('os');
const path = require('path');
const fs = require('mz/fs');
const madge = require('../lib/api');

require('should');

describe('API', () => {
	it('throws error on missing path argument', () => {
		(() => {
			madge();
		}).should.throw('path argument not provided');
	});

	it('returns a Promise', () => {
		madge(__dirname + '/cjs/a.js').should.be.Promise(); // eslint-disable-line new-cap
	});

	it('throws error if file or directory does not exists', (done) => {
		madge(__dirname + '/missing.js').catch((err) => {
			err.message.should.match(/no such file or directory/);
			done();
		}).catch(done);
	});

	it('takes single file as path', (done) => {
		madge(__dirname + '/cjs/a.js').then((res) => {
			res.obj().should.eql({
				'a.js': ['b.js', 'c.js'],
				'b.js': ['c.js'],
				'c.js': []
			});
			done();
		}).catch(done);
	});

	it('takes an array of files as path and combines the result', (done) => {
		madge([__dirname + '/cjs/a.js', __dirname + '/cjs/normal/d.js']).then((res) => {
			res.obj().should.eql({
				'a.js': ['b.js', 'c.js'],
				'b.js': ['c.js'],
				'c.js': [],
				'normal/d.js': []
			});
			done();
		}).catch(done);
	});

	it('take a single directory as path and find files in it', (done) => {
		madge(__dirname + '/cjs/normal').then((res) => {
			res.obj().should.eql({
				'a.js': ['sub/b.js'],
				'd.js': [],
				'sub/b.js': ['sub/c.js'],
				'sub/c.js': ['d.js']
			});
			done();
		}).catch(done);
	});

	it('takes an array of directories as path and compute the basedir correctly', (done) => {
		madge([__dirname + '/cjs/multibase/1', __dirname + '/cjs/multibase/2']).then((res) => {
			res.obj().should.eql({
				'1/a.js': [],
				'2/b.js': []
			});
			done();
		}).catch(done);
	});

	it('takes a predefined tree', (done) => {
		madge({
			a: ['b', 'c', 'd'],
			b: ['c'],
			c: [],
			d: ['a']
		}).then((res) => {
			res.obj().should.eql({
				a: ['b', 'c', 'd'],
				b: ['c'],
				c: [],
				d: ['a']
			});
			done();
		}).catch(done);
	});

	it('can exclude modules using RegExp', (done) => {
		madge(__dirname + '/cjs/a.js', {
			excludeRegExp: ['^b.js$']
		}).then((res) => {
			res.obj().should.eql({
				'a.js': ['c.js'],
				'c.js': []
			});
			done();
		}).catch(done);
	});

	describe('dependencyFilter', () => {
		it('will stop traversing when returning false', (done) => {
			madge(__dirname + '/cjs/a.js', {
				dependencyFilter: () => {
					return false;
				}
			}).then((res) => {
				res.obj().should.eql({
					'a.js': []
				});
				done();
			}).catch(done);
		});

		it('will not stop traversing when not returning anything', (done) => {
			madge(__dirname + '/cjs/a.js', {
				dependencyFilter: () => {}
			}).then((res) => {
				res.obj().should.eql({
					'a.js': ['b.js', 'c.js'],
					'b.js': ['c.js'],
					'c.js': []
				});
				done();
			}).catch(done);
		});

		it('will pass arguments to the function', (done) => {
			let counter = 0;

			madge(__dirname + '/cjs/a.js', {
				dependencyFilter: (dependencyFilePath, traversedFilePath, baseDir) => {
					if (counter === 0) {
						dependencyFilePath.should.match(/test\/cjs\/b\.js$/);
						traversedFilePath.should.match(/test\/cjs\/a\.js$/);
						baseDir.should.match(/test\/cjs$/);
					}

					if (counter === 1) {
						dependencyFilePath.should.match(/test\/cjs\/c\.js$/);
						traversedFilePath.should.match(/test\/cjs\/a\.js$/);
						baseDir.should.match(/test\/cjs$/);
					}

					if (counter === 2) {
						dependencyFilePath.should.match(/test\/cjs\/c\.js$/);
						traversedFilePath.should.match(/test\/cjs\/b\.js$/);
						baseDir.should.match(/test\/cjs$/);
					}

					counter++;
				}
			}).then(() => {
				done();
			}).catch(done);
		});
	});

	describe('obj()', () => {
		it('returns dependency object', (done) => {
			madge(__dirname + '/cjs/a.js').then((res) => {
				res.obj().should.eql({
					'a.js': ['b.js', 'c.js'],
					'b.js': ['c.js'],
					'c.js': []
				});
				done();
			}).catch(done);
		});
	});

	describe('warnings()', () => {
		it('returns an array of skipped files', (done) => {
			madge(__dirname + '/cjs/missing.js').then((res) => {
				res.obj().should.eql({
					'missing.js': ['c.js'],
					'c.js': []
				});
				res.warnings().should.eql({
					skipped: ['./path/non/existing/file']
				});
				done();
			}).catch(done);
		});
	});

	describe('dot()', () => {
		it('returns a promise resolved with graphviz DOT output', (done) => {
			madge(__dirname + '/cjs/b.js')
				.then((res) => res.dot())
				.then((output) => {
					output.should.eql('digraph G {\n  "b.js";\n  "c.js";\n  "b.js" -> "c.js";\n}\n');
					done();
				})
				.catch(done);
		});
	});

	describe('depends()', () => {
		it('returns modules that depends on another', (done) => {
			madge(__dirname + '/cjs/a.js').then((res) => {
				res.depends('c.js').should.eql(['a.js', 'b.js']);
				done();
			}).catch(done);
		});
	});

	describe('orphans()', () => {
		it('returns modules that no one is depending on', (done) => {
			madge(__dirname + '/cjs/normal').then((res) => {
				res.orphans().should.eql(['a.js']);
				done();
			}).catch(done);
		});
	});

	describe('svg()', () => {
		it('returns a promise resolved with XML SVG output in a Buffer', (done) => {
			madge(__dirname + '/cjs/b.js')
				.then((res) => res.svg())
				.then((output) => {
					output.should.instanceof(Buffer);
					done();
				})
				.catch(done);
		});
	});

	describe('image()', () => {
		let imagePath;

		beforeEach(() => {
			imagePath = path.join(os.tmpdir(), 'madge_' + Date.now() + '_image.png');
		});

		afterEach(() => {
			return fs.unlink(imagePath).catch(() => {});
		});

		it('rejects if a filename is not supplied', (done) => {
			madge(__dirname + '/cjs/a.js')
				.then((res) => res.image())
				.catch((err) => {
					err.message.should.eql('imagePath not provided');
					done();
				});
		});

		it('rejects on unsupported image format', (done) => {
			madge(__dirname + '/cjs/a.js')
				.then((res) => res.image('image.zyx'))
				.catch((err) => {
					err.message.should.match(/Format: "zyx" not recognized/);
					done();
				});
		});

		it('rejects if graphviz is not installed', (done) => {
			madge(__dirname + '/cjs/a.js', {graphVizPath: '/invalid/path'})
				.then((res) => res.image('image.png'))
				.catch((err) => {
					err.message.should.match(/Could not execute .*gvpr \-V/);
					done();
				});
		});

		it('writes image to file', (done) => {
			madge(__dirname + '/cjs/a.js')
				.then((res) => res.image(imagePath))
				.then((writtenImagePath) => {
					writtenImagePath.should.eql(imagePath);

					return fs
						.exists(imagePath)
						.then((exists) => {
							if (!exists) {
								throw new Error(imagePath + ' not created');
							}
							done();
						});
				})
				.catch(done);
		});
	});
});
<commit_msg>.svg(): Add simple content test<commit_after>/* eslint-env mocha */
'use strict';

const os = require('os');
const path = require('path');
const fs = require('mz/fs');
const madge = require('../lib/api');

require('should');

describe('API', () => {
	it('throws error on missing path argument', () => {
		(() => {
			madge();
		}).should.throw('path argument not provided');
	});

	it('returns a Promise', () => {
		madge(__dirname + '/cjs/a.js').should.be.Promise(); // eslint-disable-line new-cap
	});

	it('throws error if file or directory does not exists', (done) => {
		madge(__dirname + '/missing.js').catch((err) => {
			err.message.should.match(/no such file or directory/);
			done();
		}).catch(done);
	});

	it('takes single file as path', (done) => {
		madge(__dirname + '/cjs/a.js').then((res) => {
			res.obj().should.eql({
				'a.js': ['b.js', 'c.js'],
				'b.js': ['c.js'],
				'c.js': []
			});
			done();
		}).catch(done);
	});

	it('takes an array of files as path and combines the result', (done) => {
		madge([__dirname + '/cjs/a.js', __dirname + '/cjs/normal/d.js']).then((res) => {
			res.obj().should.eql({
				'a.js': ['b.js', 'c.js'],
				'b.js': ['c.js'],
				'c.js': [],
				'normal/d.js': []
			});
			done();
		}).catch(done);
	});

	it('take a single directory as path and find files in it', (done) => {
		madge(__dirname + '/cjs/normal').then((res) => {
			res.obj().should.eql({
				'a.js': ['sub/b.js'],
				'd.js': [],
				'sub/b.js': ['sub/c.js'],
				'sub/c.js': ['d.js']
			});
			done();
		}).catch(done);
	});

	it('takes an array of directories as path and compute the basedir correctly', (done) => {
		madge([__dirname + '/cjs/multibase/1', __dirname + '/cjs/multibase/2']).then((res) => {
			res.obj().should.eql({
				'1/a.js': [],
				'2/b.js': []
			});
			done();
		}).catch(done);
	});

	it('takes a predefined tree', (done) => {
		madge({
			a: ['b', 'c', 'd'],
			b: ['c'],
			c: [],
			d: ['a']
		}).then((res) => {
			res.obj().should.eql({
				a: ['b', 'c', 'd'],
				b: ['c'],
				c: [],
				d: ['a']
			});
			done();
		}).catch(done);
	});

	it('can exclude modules using RegExp', (done) => {
		madge(__dirname + '/cjs/a.js', {
			excludeRegExp: ['^b.js$']
		}).then((res) => {
			res.obj().should.eql({
				'a.js': ['c.js'],
				'c.js': []
			});
			done();
		}).catch(done);
	});

	describe('dependencyFilter', () => {
		it('will stop traversing when returning false', (done) => {
			madge(__dirname + '/cjs/a.js', {
				dependencyFilter: () => {
					return false;
				}
			}).then((res) => {
				res.obj().should.eql({
					'a.js': []
				});
				done();
			}).catch(done);
		});

		it('will not stop traversing when not returning anything', (done) => {
			madge(__dirname + '/cjs/a.js', {
				dependencyFilter: () => {}
			}).then((res) => {
				res.obj().should.eql({
					'a.js': ['b.js', 'c.js'],
					'b.js': ['c.js'],
					'c.js': []
				});
				done();
			}).catch(done);
		});

		it('will pass arguments to the function', (done) => {
			let counter = 0;

			madge(__dirname + '/cjs/a.js', {
				dependencyFilter: (dependencyFilePath, traversedFilePath, baseDir) => {
					if (counter === 0) {
						dependencyFilePath.should.match(/test\/cjs\/b\.js$/);
						traversedFilePath.should.match(/test\/cjs\/a\.js$/);
						baseDir.should.match(/test\/cjs$/);
					}

					if (counter === 1) {
						dependencyFilePath.should.match(/test\/cjs\/c\.js$/);
						traversedFilePath.should.match(/test\/cjs\/a\.js$/);
						baseDir.should.match(/test\/cjs$/);
					}

					if (counter === 2) {
						dependencyFilePath.should.match(/test\/cjs\/c\.js$/);
						traversedFilePath.should.match(/test\/cjs\/b\.js$/);
						baseDir.should.match(/test\/cjs$/);
					}

					counter++;
				}
			}).then(() => {
				done();
			}).catch(done);
		});
	});

	describe('obj()', () => {
		it('returns dependency object', (done) => {
			madge(__dirname + '/cjs/a.js').then((res) => {
				res.obj().should.eql({
					'a.js': ['b.js', 'c.js'],
					'b.js': ['c.js'],
					'c.js': []
				});
				done();
			}).catch(done);
		});
	});

	describe('warnings()', () => {
		it('returns an array of skipped files', (done) => {
			madge(__dirname + '/cjs/missing.js').then((res) => {
				res.obj().should.eql({
					'missing.js': ['c.js'],
					'c.js': []
				});
				res.warnings().should.eql({
					skipped: ['./path/non/existing/file']
				});
				done();
			}).catch(done);
		});
	});

	describe('dot()', () => {
		it('returns a promise resolved with graphviz DOT output', (done) => {
			madge(__dirname + '/cjs/b.js')
				.then((res) => res.dot())
				.then((output) => {
					output.should.eql('digraph G {\n  "b.js";\n  "c.js";\n  "b.js" -> "c.js";\n}\n');
					done();
				})
				.catch(done);
		});
	});

	describe('depends()', () => {
		it('returns modules that depends on another', (done) => {
			madge(__dirname + '/cjs/a.js').then((res) => {
				res.depends('c.js').should.eql(['a.js', 'b.js']);
				done();
			}).catch(done);
		});
	});

	describe('orphans()', () => {
		it('returns modules that no one is depending on', (done) => {
			madge(__dirname + '/cjs/normal').then((res) => {
				res.orphans().should.eql(['a.js']);
				done();
			}).catch(done);
		});
	});

	describe('svg()', () => {
		it('returns a promise resolved with XML SVG output in a Buffer', (done) => {
			madge(__dirname + '/cjs/b.js')
				.then((res) => res.svg())
				.then((output) => {
					output.should.instanceof(Buffer);
					output.toString().should.match(/<svg.*/);
					done();
				})
				.catch(done);
		});
	});

	describe('image()', () => {
		let imagePath;

		beforeEach(() => {
			imagePath = path.join(os.tmpdir(), 'madge_' + Date.now() + '_image.png');
		});

		afterEach(() => {
			return fs.unlink(imagePath).catch(() => {});
		});

		it('rejects if a filename is not supplied', (done) => {
			madge(__dirname + '/cjs/a.js')
				.then((res) => res.image())
				.catch((err) => {
					err.message.should.eql('imagePath not provided');
					done();
				});
		});

		it('rejects on unsupported image format', (done) => {
			madge(__dirname + '/cjs/a.js')
				.then((res) => res.image('image.zyx'))
				.catch((err) => {
					err.message.should.match(/Format: "zyx" not recognized/);
					done();
				});
		});

		it('rejects if graphviz is not installed', (done) => {
			madge(__dirname + '/cjs/a.js', {graphVizPath: '/invalid/path'})
				.then((res) => res.image('image.png'))
				.catch((err) => {
					err.message.should.match(/Could not execute .*gvpr \-V/);
					done();
				});
		});

		it('writes image to file', (done) => {
			madge(__dirname + '/cjs/a.js')
				.then((res) => res.image(imagePath))
				.then((writtenImagePath) => {
					writtenImagePath.should.eql(imagePath);

					return fs
						.exists(imagePath)
						.then((exists) => {
							if (!exists) {
								throw new Error(imagePath + ' not created');
							}
							done();
						});
				})
				.catch(done);
		});
	});
});
<|endoftext|>


<commit_before>const tape = require('tape')
const utils = require('ethereumjs-util')
const rlp = utils.rlp
const Transaction = require('../index.js')
const txFixtures = require('./txs.json')
const txFixturesEip155 = require('./ttTransactionTestEip155VitaliksTests.json')
tape('[Transaction]: Basic functions', function (t) {
  var transactions = []

  t.test('should decode transactions', function (st) {
    txFixtures.slice(0, 4).forEach(function (tx) {
      var pt = new Transaction(tx.raw)
      st.equal('0x' + pt.nonce.toString('hex'), tx.raw[0])
      st.equal('0x' + pt.gasPrice.toString('hex'), tx.raw[1])
      st.equal('0x' + pt.gasLimit.toString('hex'), tx.raw[2])
      st.equal('0x' + pt.to.toString('hex'), tx.raw[3])
      st.equal('0x' + pt.value.toString('hex'), tx.raw[4])
      st.equal('0x' + pt.v.toString('hex'), tx.raw[6])
      st.equal('0x' + pt.r.toString('hex'), tx.raw[7])
      st.equal('0x' + pt.s.toString('hex'), tx.raw[8])
      st.equal('0x' + pt.data.toString('hex'), tx.raw[5])
      transactions.push(pt)
    })
    st.end()
  })

  t.test('should serialize', function (st) {
    transactions.forEach(function (tx) {
      st.deepEqual(tx.serialize(), rlp.encode(tx.raw))
    })
    st.end()
  })

  t.test('should hash', function (st) {
    var tx = new Transaction(txFixtures[3].raw)
    st.deepEqual(tx.hash(), new Buffer('375a8983c9fc56d7cfd118254a80a8d7403d590a6c9e105532b67aca1efb97aa', 'hex'))
    st.deepEqual(tx.hash(false), new Buffer('61e1ec33764304dddb55348e7883d4437426f44ab3ef65e6da1e025734c03ff0', 'hex'))
    st.deepEqual(tx.hash(true), new Buffer('375a8983c9fc56d7cfd118254a80a8d7403d590a6c9e105532b67aca1efb97aa', 'hex'))
    st.end()
  })

  t.test('should hash with defined chainId', function (st) {
    var tx = new Transaction(txFixtures[4].raw)
    st.equal(tx.hash().toString('hex'), '0f09dc98ea85b7872f4409131a790b91e7540953992886fc268b7ba5c96820e4')
    st.equal(tx.hash(true).toString('hex'), '0f09dc98ea85b7872f4409131a790b91e7540953992886fc268b7ba5c96820e4')
    st.equal(tx.hash(false).toString('hex'), 'f97c73fdca079da7652dbc61a46cd5aeef804008e057be3e712c43eac389aaf0')
    st.end()
  })

  t.test('should verify Signatures', function (st) {
    transactions.forEach(function (tx) {
      st.equals(tx.verifySignature(), true)
    })
    st.end()
  })

  t.test('should not verify Signatures', function (st) {
    transactions.forEach(function (tx) {
      tx.s = utils.zeros(32)
      st.equals(tx.verifySignature(), false)
    })
    st.end()
  })

  t.test('should give a string about not verifing Signatures', function (st) {
    transactions.forEach(function (tx) {
      st.equals(tx.validate(true).slice(0, 54), 'Invalid Signature gas limit is too low. Need at least ')
    })
    st.end()
  })

  t.test('should validate', function (st) {
    transactions.forEach(function (tx) {
      st.equals(tx.validate(), false)
    })
    st.end()
  })

  t.test('should sign tx', function (st) {
    transactions.forEach(function (tx, i) {
      if (txFixtures[i].privateKey) {
        var privKey = new Buffer(txFixtures[i].privateKey, 'hex')
        tx.sign(privKey)
      }
    })
    st.end()
  })

  t.test("should get sender's address after signing it", function (st) {
    transactions.forEach(function (tx, i) {
      if (txFixtures[i].privateKey) {
        st.equals(tx.getSenderAddress().toString('hex'), txFixtures[i].sendersAddress)
      }
    })
    st.end()
  })

  t.test("should get sender's public key after signing it", function (st) {
    transactions.forEach(function (tx, i) {
      if (txFixtures[i].privateKey) {
        st.equals(tx.getSenderPublicKey().toString('hex'),
          utils.privateToPublic(new Buffer(txFixtures[i].privateKey, 'hex')).toString('hex'))
      }
    })
    st.end()
  })

  t.test("should get sender's address after signing it (second call should be cached)", function (st) {
    transactions.forEach(function (tx, i) {
      if (txFixtures[i].privateKey) {
        st.equals(tx.getSenderAddress().toString('hex'), txFixtures[i].sendersAddress)
        st.equals(tx.getSenderAddress().toString('hex'), txFixtures[i].sendersAddress)
      }
    })
    st.end()
  })

  t.test('should verify signing it', function (st) {
    transactions.forEach(function (tx, i) {
      if (txFixtures[i].privateKey) {
        st.equals(tx.verifySignature(), true)
      }
    })
    st.end()
  })

  t.test('should validate with string option', function (st) {
    transactions.forEach(function (tx) {
      tx.gasLimit = 30000
      st.equals(tx.validate(true), '')
    })
    st.end()
  })

  t.test('should round trip decode a tx', function (st) {
    var tx = new Transaction()
    tx.value = 5000
    var s1 = tx.serialize().toString('hex')
    var tx2 = new Transaction(s1)
    var s2 = tx2.serialize().toString('hex')
    st.equals(s1, s2)
    st.end()
  })

  t.test('should accept lesser r values', function (st) {
    var tx = new Transaction()
    tx.r = '0x0005'
    st.equals(tx.r.toString('hex'), '05')
    st.end()
  })

  t.test('should return data fee', function (st) {
    var tx = new Transaction()
    st.equals(tx.getDataFee().toNumber(), 0)

    tx = new Transaction(txFixtures[3].raw)
    st.equals(tx.getDataFee().toNumber(), 2496)

    st.end()
  })

  t.test('should return base fee', function (st) {
    var tx = new Transaction()
    st.equals(tx.getBaseFee().toNumber(), 53000)
    st.end()
  })

  t.test('should return upfront cost', function (st) {
    var tx = new Transaction({
      gasPrice: 1000,
      gasLimit: 10000000,
      value: 42
    })
    st.equals(tx.getUpfrontCost().toNumber(), 10000000042)
    st.end()
  })

  t.test('Verify EIP155 Signature based on Vitalik\'s tests', function (st) {
    txFixturesEip155.forEach(function (tx) {
      var pt = new Transaction(tx.rlp)
      st.equal(pt.hash(false).toString('hex'), tx.hash)
      st.equal('0x' + pt.serialize().toString('hex'), tx.rlp)
      st.equal(pt.getSenderAddress().toString('hex'), tx.sender)
    })
    st.end()
  })

  t.test('Verify EIP155 Signature before and after signing with private key', function (st) {
    // Inputs and expected results for this test are taken directly from the example in https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
    var txRaw = [
      '0x09',
      '0x4a817c800',
      '0x5208',
      '0x3535353535353535353535353535353535353535',
      '0x0de0b6b3a7640000',
      '0x'
    ]
    var privateKey = Buffer.from('4646464646464646464646464646464646464646464646464646464646464646', 'hex')
    var pt = new Transaction(txRaw, { chain: 1 })
    st.equal(pt.serialize().toString('hex'), 'ec098504a817c800825208943535353535353535353535353535353535353535880de0b6b3a764000080018080')
    pt.sign(privateKey)
    st.equal(pt.hash(false).toString('hex'), 'daf5a779ae972f972197303d7b574746c7ef83eadac0f2791ad23db92e4c8e53')
    st.equal(pt.serialize().toString('hex'), 'f86c098504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a028ef61340bd939bc2195fe537567866003e1a15d3c71ff63e1590620aa636276a067cbe9d8997f761aecb703304b3800ccf555c9f3dc64214b297fb1966a3b6d83')
    st.end()
  })

  t.test('Serialize correctly after being signed with EIP155 Signature for tx created on ropsten', function (st) {
    var txRaw = [
      '0x1',
      '0x02540be400',
      '0x5208',
      '0xd7250824390ec5c8b71d856b5de895e271170d9d',
      '0x0de0b6b3a7640000',
      '0x'
    ]

    var privateKey = Buffer.from('DE3128752F183E8930D7F00A2AAA302DCB5E700B2CBA2D8CA5795660F07DEFD5', 'hex')
    var pt = new Transaction(txRaw, { chain: 3 })
    pt.sign(privateKey)
    st.equal(pt.serialize().toString('hex'), 'f86c018502540be40082520894d7250824390ec5c8b71d856b5de895e271170d9d880de0b6b3a76400008029a0d3512c68099d184ccf54f44d9d6905bff303128574b663dcf10b4c726ddd8133a0628acc8f481dea593f13309dfc5f0340f83fdd40cf9fbe47f782668f6f3aec74')
    st.end()
  })

  t.test('sign tx with chainId specified in params', function (st) {
    var tx = new Transaction({ chainId: 42 })
    st.equal(tx.getChainId(), 42)
    var privKey = new Buffer(txFixtures[0].privateKey, 'hex')
    tx.sign(privKey)
    var serialized = tx.serialize()
    var reTx = new Transaction(serialized)
    st.equal(reTx.verifySignature(), true)
    st.equal(reTx.getChainId(), 42)
    st.end()
  })

  t.test('allow chainId more than 1 byte', function (st) {
    var tx = new Transaction({ chainId: 0x16b2 })
    st.equal(tx.getChainId(), 0x16b2)
    st.end()
  })
})
<commit_msg>Add additional signing + hashing api tests.<commit_after>const tape = require('tape')
const utils = require('ethereumjs-util')
const rlp = utils.rlp
const Transaction = require('../index.js')
const txFixtures = require('./txs.json')
const txFixturesEip155 = require('./ttTransactionTestEip155VitaliksTests.json')
tape('[Transaction]: Basic functions', function (t) {
  var transactions = []

  t.test('should decode transactions', function (st) {
    txFixtures.slice(0, 4).forEach(function (tx) {
      var pt = new Transaction(tx.raw)
      st.equal('0x' + pt.nonce.toString('hex'), tx.raw[0])
      st.equal('0x' + pt.gasPrice.toString('hex'), tx.raw[1])
      st.equal('0x' + pt.gasLimit.toString('hex'), tx.raw[2])
      st.equal('0x' + pt.to.toString('hex'), tx.raw[3])
      st.equal('0x' + pt.value.toString('hex'), tx.raw[4])
      st.equal('0x' + pt.v.toString('hex'), tx.raw[6])
      st.equal('0x' + pt.r.toString('hex'), tx.raw[7])
      st.equal('0x' + pt.s.toString('hex'), tx.raw[8])
      st.equal('0x' + pt.data.toString('hex'), tx.raw[5])
      transactions.push(pt)
    })
    st.end()
  })

  t.test('should serialize', function (st) {
    transactions.forEach(function (tx) {
      st.deepEqual(tx.serialize(), rlp.encode(tx.raw))
    })
    st.end()
  })

  t.test('should hash', function (st) {
    var tx = new Transaction(txFixtures[3].raw)
    st.deepEqual(tx.hash(), new Buffer('375a8983c9fc56d7cfd118254a80a8d7403d590a6c9e105532b67aca1efb97aa', 'hex'))
    st.deepEqual(tx.hash(false), new Buffer('61e1ec33764304dddb55348e7883d4437426f44ab3ef65e6da1e025734c03ff0', 'hex'))
    st.deepEqual(tx.hash(true), new Buffer('375a8983c9fc56d7cfd118254a80a8d7403d590a6c9e105532b67aca1efb97aa', 'hex'))
    st.end()
  })

  t.test('should hash with defined chainId', function (st) {
    var tx = new Transaction(txFixtures[4].raw)
    st.equal(tx.hash().toString('hex'), '0f09dc98ea85b7872f4409131a790b91e7540953992886fc268b7ba5c96820e4')
    st.equal(tx.hash(true).toString('hex'), '0f09dc98ea85b7872f4409131a790b91e7540953992886fc268b7ba5c96820e4')
    st.equal(tx.hash(false).toString('hex'), 'f97c73fdca079da7652dbc61a46cd5aeef804008e057be3e712c43eac389aaf0')
    st.end()
  })

  t.test('should verify Signatures', function (st) {
    transactions.forEach(function (tx) {
      st.equals(tx.verifySignature(), true)
    })
    st.end()
  })

  t.test('should not verify Signatures', function (st) {
    transactions.forEach(function (tx) {
      tx.s = utils.zeros(32)
      st.equals(tx.verifySignature(), false)
    })
    st.end()
  })

  t.test('should give a string about not verifing Signatures', function (st) {
    transactions.forEach(function (tx) {
      st.equals(tx.validate(true).slice(0, 54), 'Invalid Signature gas limit is too low. Need at least ')
    })
    st.end()
  })

  t.test('should validate', function (st) {
    transactions.forEach(function (tx) {
      st.equals(tx.validate(), false)
    })
    st.end()
  })

  t.test('should sign tx', function (st) {
    transactions.forEach(function (tx, i) {
      if (txFixtures[i].privateKey) {
        var privKey = new Buffer(txFixtures[i].privateKey, 'hex')
        tx.sign(privKey)
      }
    })
    st.end()
  })

  t.test("should get sender's address after signing it", function (st) {
    transactions.forEach(function (tx, i) {
      if (txFixtures[i].privateKey) {
        st.equals(tx.getSenderAddress().toString('hex'), txFixtures[i].sendersAddress)
      }
    })
    st.end()
  })

  t.test("should get sender's public key after signing it", function (st) {
    transactions.forEach(function (tx, i) {
      if (txFixtures[i].privateKey) {
        st.equals(tx.getSenderPublicKey().toString('hex'),
          utils.privateToPublic(new Buffer(txFixtures[i].privateKey, 'hex')).toString('hex'))
      }
    })
    st.end()
  })

  t.test("should get sender's address after signing it (second call should be cached)", function (st) {
    transactions.forEach(function (tx, i) {
      if (txFixtures[i].privateKey) {
        st.equals(tx.getSenderAddress().toString('hex'), txFixtures[i].sendersAddress)
        st.equals(tx.getSenderAddress().toString('hex'), txFixtures[i].sendersAddress)
      }
    })
    st.end()
  })

  t.test('should verify signing it', function (st) {
    transactions.forEach(function (tx, i) {
      if (txFixtures[i].privateKey) {
        st.equals(tx.verifySignature(), true)
      }
    })
    st.end()
  })

  t.test('should validate with string option', function (st) {
    transactions.forEach(function (tx) {
      tx.gasLimit = 30000
      st.equals(tx.validate(true), '')
    })
    st.end()
  })

  t.test('should round trip decode a tx', function (st) {
    var tx = new Transaction()
    tx.value = 5000
    var s1 = tx.serialize().toString('hex')
    var tx2 = new Transaction(s1)
    var s2 = tx2.serialize().toString('hex')
    st.equals(s1, s2)
    st.end()
  })

  t.test('should accept lesser r values', function (st) {
    var tx = new Transaction()
    tx.r = '0x0005'
    st.equals(tx.r.toString('hex'), '05')
    st.end()
  })

  t.test('should return data fee', function (st) {
    var tx = new Transaction()
    st.equals(tx.getDataFee().toNumber(), 0)

    tx = new Transaction(txFixtures[3].raw)
    st.equals(tx.getDataFee().toNumber(), 2496)

    st.end()
  })

  t.test('should return base fee', function (st) {
    var tx = new Transaction()
    st.equals(tx.getBaseFee().toNumber(), 53000)
    st.end()
  })

  t.test('should return upfront cost', function (st) {
    var tx = new Transaction({
      gasPrice: 1000,
      gasLimit: 10000000,
      value: 42
    })
    st.equals(tx.getUpfrontCost().toNumber(), 10000000042)
    st.end()
  })

  t.test('Verify EIP155 Signature based on Vitalik\'s tests', function (st) {
    txFixturesEip155.forEach(function (tx) {
      var pt = new Transaction(tx.rlp)
      st.equal(pt.hash(false).toString('hex'), tx.hash)
      st.equal('0x' + pt.serialize().toString('hex'), tx.rlp)
      st.equal(pt.getSenderAddress().toString('hex'), tx.sender)
    })
    st.end()
  })

  t.test('Verify EIP155 Signature before and after signing with private key', function (st) {
    // Inputs and expected results for this test are taken directly from the example in https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
    var txRaw = [
      '0x09',
      '0x4a817c800',
      '0x5208',
      '0x3535353535353535353535353535353535353535',
      '0x0de0b6b3a7640000',
      '0x'
    ]
    var privateKey = Buffer.from('4646464646464646464646464646464646464646464646464646464646464646', 'hex')
    var pt = new Transaction(txRaw, { chain: 1 })
    st.equal(pt.serialize().toString('hex'), 'ec098504a817c800825208943535353535353535353535353535353535353535880de0b6b3a764000080018080')
    pt.sign(privateKey)
    st.equal(pt.hash(false).toString('hex'), 'daf5a779ae972f972197303d7b574746c7ef83eadac0f2791ad23db92e4c8e53')
    st.equal(pt.serialize().toString('hex'), 'f86c098504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a028ef61340bd939bc2195fe537567866003e1a15d3c71ff63e1590620aa636276a067cbe9d8997f761aecb703304b3800ccf555c9f3dc64214b297fb1966a3b6d83')
    st.end()
  })

  t.test('Serialize correctly after being signed with EIP155 Signature for tx created on ropsten', function (st) {
    var txRaw = [
      '0x1',
      '0x02540be400',
      '0x5208',
      '0xd7250824390ec5c8b71d856b5de895e271170d9d',
      '0x0de0b6b3a7640000',
      '0x'
    ]

    var privateKey = Buffer.from('DE3128752F183E8930D7F00A2AAA302DCB5E700B2CBA2D8CA5795660F07DEFD5', 'hex')
    var pt = new Transaction(txRaw, { chain: 3 })
    pt.sign(privateKey)
    st.equal(pt.serialize().toString('hex'), 'f86c018502540be40082520894d7250824390ec5c8b71d856b5de895e271170d9d880de0b6b3a76400008029a0d3512c68099d184ccf54f44d9d6905bff303128574b663dcf10b4c726ddd8133a0628acc8f481dea593f13309dfc5f0340f83fdd40cf9fbe47f782668f6f3aec74')
    st.end()
  })

  t.test('sign tx with chainId specified in params', function (st) {
    var tx = new Transaction({ chainId: 42 })
    st.equal(tx.getChainId(), 42)
    var privKey = new Buffer(txFixtures[0].privateKey, 'hex')
    tx.sign(privKey)
    var serialized = tx.serialize()
    var reTx = new Transaction(serialized)
    st.equal(reTx.verifySignature(), true)
    st.equal(reTx.getChainId(), 42)
    st.end()
  })

  t.test('allow chainId more than 1 byte', function (st) {
    var tx = new Transaction({ chainId: 0x16b2 })
    st.equal(tx.getChainId(), 0x16b2)
    st.end()
  })

  t.test('EIP155 hashing when singing', function (st) {
    txFixtures.slice(0, 3).forEach(function (txData) {
      const tx = new Transaction(txData.raw.slice(0, 6), {chain: 1})

      var privKey = new Buffer(txData.privateKey, 'hex')
      tx.sign(privKey)

      st.equal(
        tx.getSenderAddress().toString('hex'),
        txData.sendersAddress,
        'computed sender address should equal the fixture\'s one'
      )
    })

    st.end()
  })
})
<|endoftext|>


<commit_before>'use strict';

describe('bad', function(){
  var kid = require('kid_process');
  var path = require('path');
  var bad = path.resolve(__dirname, '..', 'bin', 'bad.js');
  var fixtures = path.resolve(__dirname, '..', 'test-fixtures');
  var printArgvWithEnv = path.resolve(fixtures, 'print-argv-with-env.bash');
  var printArgvWithoutEnv = path.resolve(fixtures, 'print-argv-without-env.bash');
  var printSubject = path.resolve(fixtures, 'print-subject.bash');
  var printEnv = path.resolve(fixtures, 'print-env-FOO.bash');
  var writeToStdErr = path.resolve(fixtures, 'write-to-stderr.bash');
  var abnormalExit = path.resolve(fixtures, 'abnormal-exit.bash');

  it('exits normally on normal exit codes', function(done){
    kid.play(bad, ['--exec', printSubject, '--for', '2 3 4 5'])
    .on('terminated', function(code){
      code.should.equal(0);
      done();
    });
  });

  it('exits abnormally on bad exit codes', function(done){
    kid.play(bad, ['--exec', abnormalExit, '--for', '2 3 4 5'])
    .on('terminated', function(code){
      code.should.equal(3);
      done();
    });
  });

  it('exits normally if stderr output exists', function(done){
    kid.play(bad, ['--exec', writeToStdErr, '--for', '2 3 4 5'])
    .on('terminated', function(code){
      code.should.equal(0);
      done();
    });
  });

  it('returns an error if an error if command does not exist', function(done){
    kid.play(bad, ['--exec', 'aaaaaaaaa', '--for', '2 3 4 5'])
    .on('terminated', function(code){
      code.should.be.above(0);
      done();
    });
  });

  it('prints out env vars', function(done){
    var process = kid
    .play(bad, ['--exec', printEnv, '--for', '2 3 4 5', '--to-env', 'FOO'])
    .on('terminated', function(code){
      console.log(Object.prototype.toString.call(process.stdout));
      done();
    });
  });

  describe('--argv', function(){
    describe('with --to-env', function(){
      it('passes subject as env var but not as argv', function(done){
        kid.play(bad, [
          '--exec', printArgvWithEnv,
          '--for', '3',
          '--argv', '1 2',
          '--to-env', 'FOO'
        ])
        .on('terminated', function(code){
          code.should.equal(0);
          done();
        });
      });
    });

    describe('without --to-env', function(){
      it('passes subject as last element in argv', function(done){
        kid.play(bad, [
          '--exec', printArgvWithoutEnv,
          '--for', '3',
          '--argv', '1 2'
        ])
        .on('terminated', function(code){
          code.should.equal(0);
          done();
        });
      });
    });

  });

});
<commit_msg>Testing output as well.<commit_after>'use strict';

describe('bad', function(){
  var assert = require('assert');
  var kid = require('kid_process');
  var exec = require('child_process').exec;
  var path = require('path');
  var bad = path.resolve(__dirname, '..', 'bin', 'bad.js');
  var fixtures = path.resolve(__dirname, '..', 'test-fixtures');
  var printArgvWithEnv = path.resolve(fixtures, 'print-argv-with-env.bash');
  var printArgvWithoutEnv = path.resolve(fixtures, 'print-argv-without-env.bash');
  var printSubject = path.resolve(fixtures, 'print-subject.bash');
  var printEnv = path.resolve(fixtures, 'print-env-FOO.bash');
  var writeToStdErr = path.resolve(fixtures, 'write-to-stderr.bash');
  var abnormalExit = path.resolve(fixtures, 'abnormal-exit.bash');

  it('exits normally on normal exit codes', function(done){
    exec([
      bad,
      '--exec', printSubject,
      '--for', '"2 3 4 5"'
    ].join(' '),
    function(err, out, stderr){
      assert(!err);
      out.should.equal([
        '2','3','4','5', ''
      ].join('\n\n'));
      done();
    });
  });

  it('exits abnormally on bad exit codes', function(done){
    exec(bad+' --exec '+abnormalExit+' --for "2 3 4 5"', function(err, out, stderr){
      out.should.equal([
        'The following subjects exited abnormally:',
        '2',
        '3',
        '4',
        '5',
        ''
      ].join('\n'));
      err.code.should.equal(3);
      done();
    });
  });

  it('exits normally if stderr output exists', function(done){
    exec([bad,'--exec',writeToStdErr,'--for','"2 3 4 5"'].join(' '), function(err, out, stderr){
      out.should.equal([
        'error 2',
        'error 3',
        'error 4',
        'error 5',
        ''
      ].join('\n\n'));
      assert(!stderr);
      assert(!err);
      done();
    });
  });

  it('returns an error if an error if command does not exist', function(done){
    exec([
      bad,
      '--exec', 'aaaaaaaaa',
      '--for', '"2 3 4 5"'
    ].join(' '),
    function(err, out, stderr){
      stderr.should.equal('The --exec arg must refer to a command in your PATH or a file.\n');
      err.code.should.be.above(0);
      done();
    });
  });

  it('prints out env vars', function(done){
    exec([bad, '--exec', printEnv, '--for', '"2 3 4 5"', '--to-env', 'FOO'].join(' '), function(err, out, stderr){
      assert(!err);
      out.should.equal([
        'env var Foo: 2',
        'env var Foo: 3',
        'env var Foo: 4',
        'env var Foo: 5',
        ''
      ].join('\n\n'));
      done();
    });
  });

  describe('--argv', function(){
    describe('with --to-env', function(){
      it('passes subject as env var but not as argv', function(done){
        exec([
          bad,
          '--exec', printArgvWithEnv,
          '--for', '3',
          '--argv', '"1 2"',
          '--to-env', 'FOO'
        ].join(' '),
        function(err, out, stderr){
          assert(!err);
          done();
        });
      });
    });

    describe('without --to-env', function(){
      it('passes subject as last element in argv', function(done){
        exec([
          bad,
          '--exec', printArgvWithoutEnv,
          '--for', '3',
          '--argv', '"1 2"'
        ].join(' '),
        function(err, out, stderr){
          assert(!err);
          done();
        });
      });
    });

  });

});
<|endoftext|>


<commit_before>var exec = require('child_process').exec;
var tap = require('tap');
var test = tap.test;

test('command sync', function(t) {
  exec('node examples/sync', function (error, stdout, stderr) {
    console.log('out', JSON.stringify(stdout), JSON.stringify(stderr), error);
    t.match(stdout, /  ..\n\n  [0-9]+ ms\n  2 tests\n  2 passed\n\n  Pass!/);
    t.end();
  });
});

test('command sync -r=tap', function(t) {
  exec('node examples/sync -r=tap', function (error, stdout, stderr) {
    t.match(stdout, /ok 1 simple sync pass\nok 2 simple sync pass 2\n\n1..2\n# tests 2\n# pass  2\n# time [0-9]+ms\n# passed!\n/);
    t.end();
  });
});

test('command sync -r=spec', function(t) {
  exec('node examples/sync -r=spec', function (error, stdout, stderr) {
    t.match(stdout, /  ✔ simple sync pass \([0-9]+ ms\)\n  ✔ simple sync pass 2 \([0-9]+ ms\)\n\n\n  [0-9]+ ms\n  2 tests\n  2 passed\n\n  Pass!\n/);
    t.end();
  });
});

test('command sync custom reporter', function(t) {
  exec('node examples/sync -r=./examples/custom-reporter', function (error, stdout, stderr) {
    t.match(stdout, /simple sync pass success!\nsimple sync pass 2 success!\n/);
    t.end();
  });
});

test('command sync custom reporter fail', function(t) {
  exec('node examples/sync-error -r=./examples/custom-reporter', function (error, stdout, stderr) {
    t.match(stdout, /simple sync pass failed!\nsimple sync pass 2 failed!\n/);
    t.end();
  });
});

test('command sync -r=nyan does not exist', function(t) {
  exec('node examples/sync -r=nyan', function (error, stdout, stderr) {
    t.ok(error);
    t.end();
  });
});

test('error sync', function(t) {
  exec('node examples/sync-error', function (error, stdout, stderr) {
    t.ok(error);
    t.end();
  });
});

test('error sync tap', function(t) {
  exec('node examples/sync-error -r=tap', function (error, stdout, stderr) {
    t.ok(error);
    t.end();
  });
});

test('error sync spec', function(t) {
  exec('node examples/sync-error -r=spec', function (error, stdout, stderr) {
    t.ok(error);
    t.end();
  });
});

test('command callback', function(t) {
  exec('node examples/callback', function (error, stdout, stderr) {
    t.match(stdout, /  .\n\n  [0-9]+ ms\n  1 tests\n  1 passed\n\n  Pass!/);
    t.end();
  });
});

test('invalid assertion', function(t) {
  exec('node test/fixtures/string-error-test', function (error, stdout, stderr) {
    t.ok(error);
    t.match(stdout, /  x\n\n  [0-9]+ ms\n  1 tests\n  0 passed\n  1 failed\n\n  Failed Tests:\n   x string assertion\n     hello\n      \n/);
    t.end();
  });
});

test('invalid assertion tap', function(t) {
  exec('node test/fixtures/string-error-test -r=tap', function (error, stdout, stderr) {
    t.ok(error);
    t.match(stdout, /not ok 1 string assertion\n  ---\n    error: |-\n      hello\n  ...\n\n1..1\n# tests 1\n# pass  0\n# fail  1\n# time [0-9]+ms\n# failed!\n/);
    t.end();
  });
});

test('invalid assertion spec', function(t) {
  exec('node test/fixtures/string-error-test -r=spec', function (error, stdout, stderr) {
    t.ok(error);
    t.match(stdout, /  ✖ string assertion \([0-9]+ ms\)\n     hello\n      \n\n\n  [0-9]+ ms\n  1 tests\n  0 passed\n  1 failed\n/);
    t.end();
  });
});<commit_msg>Fix tests for new spec reporter output<commit_after>var exec = require('child_process').exec;
var tap = require('tap');
var test = tap.test;

test('command sync', function(t) {
  exec('node examples/sync', function (error, stdout, stderr) {
    console.log('out', JSON.stringify(stdout), JSON.stringify(stderr), error);
    t.match(stdout, /  ..\n\n  [0-9]+ ms\n  2 tests\n  2 passed\n\n  Pass!/);
    t.end();
  });
});

test('command sync -r=tap', function(t) {
  exec('node examples/sync -r=tap', function (error, stdout, stderr) {
    t.match(stdout, /ok 1 simple sync pass\nok 2 simple sync pass 2\n\n1..2\n# tests 2\n# pass  2\n# time [0-9]+ms\n# passed!\n/);
    t.end();
  });
});

test('command sync -r=spec', function(t) {
  exec('node examples/sync -r=spec', function (error, stdout, stderr) {
    t.match(stdout, /  ✔ simple sync pass [0-9]+ms\n  ✔ simple sync pass 2 [0-9]+ms\n\n\n  [0-9]+ms total\n  2 tests\n  2 passed\n\n  Pass!\n/);
    t.end();
  });
});

test('command sync custom reporter', function(t) {
  exec('node examples/sync -r=./examples/custom-reporter', function (error, stdout, stderr) {
    t.match(stdout, /simple sync pass success!\nsimple sync pass 2 success!\n/);
    t.end();
  });
});

test('command sync custom reporter fail', function(t) {
  exec('node examples/sync-error -r=./examples/custom-reporter', function (error, stdout, stderr) {
    t.match(stdout, /simple sync pass failed!\nsimple sync pass 2 failed!\n/);
    t.end();
  });
});

test('command sync -r=nyan does not exist', function(t) {
  exec('node examples/sync -r=nyan', function (error, stdout, stderr) {
    t.ok(error);
    t.end();
  });
});

test('error sync', function(t) {
  exec('node examples/sync-error', function (error, stdout, stderr) {
    t.ok(error);
    t.end();
  });
});

test('error sync tap', function(t) {
  exec('node examples/sync-error -r=tap', function (error, stdout, stderr) {
    t.ok(error);
    t.end();
  });
});

test('error sync spec', function(t) {
  exec('node examples/sync-error -r=spec', function (error, stdout, stderr) {
    t.ok(error);
    t.end();
  });
});

test('command callback', function(t) {
  exec('node examples/callback', function (error, stdout, stderr) {
    t.match(stdout, /  .\n\n  [0-9]+ ms\n  1 tests\n  1 passed\n\n  Pass!/);
    t.end();
  });
});

test('invalid assertion', function(t) {
  exec('node test/fixtures/string-error-test', function (error, stdout, stderr) {
    t.ok(error);
    t.match(stdout, /  x\n\n  [0-9]+ ms\n  1 tests\n  0 passed\n  1 failed\n\n  Failed Tests:\n   x string assertion\n     hello\n      \n/);
    t.end();
  });
});

test('invalid assertion tap', function(t) {
  exec('node test/fixtures/string-error-test -r=tap', function (error, stdout, stderr) {
    t.ok(error);
    t.match(stdout, /not ok 1 string assertion\n  ---\n    error: |-\n      hello\n  ...\n\n1..1\n# tests 1\n# pass  0\n# fail  1\n# time [0-9]+ms\n# failed!\n/);
    t.end();
  });
});

test('invalid assertion spec', function(t) {
  exec('node test/fixtures/string-error-test -r=spec', function (error, stdout, stderr) {
    t.ok(error);
    t.match(stdout, /  ✖ string assertion [0-9]+ms\n     hello\n      \n\n\n  [0-9]+ms total\n  1 tests\n  0 passed\n  1 failed\n/);
    t.end();
  });
});
<|endoftext|>


<commit_before>
var transforms = require('polyfills-db').postcss.transform

describe('Ecstacy.css(code, map)', function () {
  describe('.build()', function () {
    describe('with no transforms', function () {
      var ecstacy

      it('should still build', function () {
        ecstacy = Ecstacy.css({
          name: 'flex',
          code: fixture('flex'),
          transforms: [],
        })

        return ecstacy.build().then(function (data) {
          assert.equal(data.hash, ecstacy.hash)
        })
      })

      it('should build again', function () {
        return ecstacy.build().then(function (data) {
          assert.equal(data.hash, ecstacy.hash)
        })
      })
    })

    describe('calc.css', function () {
      var ecstacy = Ecstacy.css({
        name: 'calc',
        code: fixture('calc'),
        transforms: [transforms.calc],
      })
      var data

      it('.then( data => )', function () {
        return ecstacy.build().then(function (_data) {
          assert(data = _data)
          assert(data.name)
          assert(data.date)
          assert(data.hash)
          assert(data.length)
          assert(data.length['.css'])
        })
      })

      it('.then( data => ) again', function () {
        return ecstacy.build().then(function (_data) {
          assert(data = _data)
          assert(data.name)
          assert(data.date)
          assert(data.hash)
          assert(data.length)
          assert(data.length['.css'])
        })
      })

      it('.read(name, .css)', function () {
        return ecstacy.read(data.name, '.css', 'utf8').then(function (css) {
          assert(!~css.indexOf('calc'))
        })
      })

      it('.read(name, .css) again', function () {
        return ecstacy.read(data.name, '.css')
      })

      it('.read(name, .min.css)', function () {
        return ecstacy.minify(data.name).then(function () {
          return ecstacy.read(data.name, '.min.css', 'utf8')
        }).then(function (js) {
          assert(!~js.indexOf('undefined'))
          assert(!~js.indexOf('sourceMappingURL'))
        })
      })

      it('.read(name, .min.css.gz)', function () {
        return ecstacy.gzip(data.name, '.min.css').then(function () {
          return ecstacy.read(data.name, '.min.css.gz')
        })
      })

      it('.stream(name, .min.css.gz)', function (done) {
        var stream = ecstacy.stream(data.name, '.min.css.gz')
        stream.resume()
        stream.once('end', done)
        stream.once('error', done)
      })
    })
  })
})

function fixture(name) {
  return fs.readFileSync(path.join(__dirname, 'fixtures', name + '.css'), 'utf8')
}
<commit_msg>test autoprefixer<commit_after>
var transforms = require('polyfills-db').postcss.transform

describe('Ecstacy.css(code, map)', function () {
  describe('.build()', function () {
    describe('with no transforms', function () {
      var ecstacy

      it('should still build', function () {
        ecstacy = Ecstacy.css({
          name: 'flex',
          code: fixture('flex'),
          transforms: [],
        })

        return ecstacy.build().then(function (data) {
          assert.equal(data.hash, ecstacy.hash)
        })
      })

      it('should build again', function () {
        return ecstacy.build().then(function (data) {
          assert.equal(data.hash, ecstacy.hash)
        })
      })
    })

    describe('calc.css', function () {
      var ecstacy = Ecstacy.css({
        name: 'calc',
        code: fixture('calc'),
        transforms: [transforms.calc],
      })
      var data

      it('.then( data => )', function () {
        return ecstacy.build().then(function (_data) {
          assert(data = _data)
          assert(data.name)
          assert(data.date)
          assert(data.hash)
          assert(data.length)
          assert(data.length['.css'])
        })
      })

      it('.then( data => ) again', function () {
        return ecstacy.build().then(function (_data) {
          assert(data = _data)
          assert(data.name)
          assert(data.date)
          assert(data.hash)
          assert(data.length)
          assert(data.length['.css'])
        })
      })

      it('.read(name, .css)', function () {
        return ecstacy.read(data.name, '.css', 'utf8').then(function (css) {
          assert(!~css.indexOf('calc'))
        })
      })

      it('.read(name, .css) again', function () {
        return ecstacy.read(data.name, '.css')
      })

      it('.read(name, .min.css)', function () {
        return ecstacy.minify(data.name).then(function () {
          return ecstacy.read(data.name, '.min.css', 'utf8')
        }).then(function (js) {
          assert(!~js.indexOf('undefined'))
          assert(!~js.indexOf('sourceMappingURL'))
        })
      })

      it('.read(name, .min.css.gz)', function () {
        return ecstacy.gzip(data.name, '.min.css').then(function () {
          return ecstacy.read(data.name, '.min.css.gz')
        })
      })

      it('.stream(name, .min.css.gz)', function (done) {
        var stream = ecstacy.stream(data.name, '.min.css.gz')
        stream.resume()
        stream.once('end', done)
        stream.once('error', done)
      })
    })

    describe('flex.css', function () {
      var ecstacy = Ecstacy.css({
        name: 'flex',
        code: fixture('flex'),
        transforms: [transforms.autoprefixer],
      })
      var data

      it('.then( data => )', function () {
        return ecstacy.build().then(function (_data) {
          assert(data = _data)
          assert(data.name)
          assert(data.date)
          assert(data.hash)
          assert(data.length)
          assert(data.length['.css'])
        })
      })

      it('.read(name, .css)', function () {
        return ecstacy.read(data.name, '.css', 'utf8').then(function (css) {
          assert(~css.indexOf('-webkit'))
        })
      })
    })
  })
})

function fixture(name) {
  return fs.readFileSync(path.join(__dirname, 'fixtures', name + '.css'), 'utf8')
}
<|endoftext|>


<commit_before>var should    = require('should')
  , maxloader = require('../maxmind-loader.js')
;

describe('load free', function() {
    describe('successful loading GeoLiteCity.dat.gz', function() {

        var flag = false;
        beforeEach(function(done){
            this.timeout(15 * 60 * 1000); // allow test to run for 15 minutes
            maxloader({
                dest: '/tmp/'
            }, function(error, response) {
                flag = (error) ? error : true;
                done(); // complete the async beforeEach
            });

        });

        it("flag should be true", function(){
            flag.should.equal(true);
        });

    });

});<commit_msg>update test<commit_after>var should    = require('should')
  , maxloader = require('../maxmind-loader.js')
;

describe('load free', function() {
    describe('successful loading GeoLiteCity.dat.gz', function() {

        var flag = false;
        beforeEach(function(done){
            this.timeout(15 * 60 * 1000); // allow test to run for 15 minutes
            maxloader({
                dest: '/tmp/'
            }, function(error, datapath) {
                flag = (error) ? error : true;
                done(); // complete the async beforeEach
            });

        });

        it("flag should be true", function(){
            flag.should.equal(true);
        });

    });

});<|endoftext|>