<commit_before>/*
 * django-selectable UI widget
 * Source: https://bitbucket.org/mlavin/django-selectable
 * Docs: http://django-selectable.readthedocs.org/
 *
 * Depends:
 *   - jQuery 1.4.3+
 *   - jQuery UI 1.8 widget factory
 *
 * Copyright 2010-2012, Mark Lavin
 * BSD License
 *
*/
(function($) {

	$.widget("ui.djselectable", {

        options: {
            removeIcon: "ui-icon-close",
            comboboxIcon: "ui-icon-triangle-1-s",
            prepareQuery: null,
            highlightMatch: true,
            formatLabel: null
        },

        _initDeck: function() {
            /* Create list display for currently selected items for multi-select */
            var self = this;
            var data = $(this.element).data();
            var style = data.selectablePosition || data['selectable-position'] || 'bottom';
            this.deck = $('
').addClass('ui-widget selectable-deck selectable-deck-' + style);
            if (style === 'bottom' || style === 'bottom-inline') {
                $(this.element).after(this.deck);
            } else {
                $(this.element).before(this.deck);
            }
            $(self.hiddenMultipleSelector).each(function(i, input) {
                self._addDeckItem(input);
            });
        },

        _addDeckItem: function(input) {
            /* Add new deck list item from a given hidden input */
            var self = this;
            $('
')
            .text($(input).attr('title'))
            .addClass('selectable-deck-item')
            .appendTo(this.deck)
            .append(
                $('
')
                .addClass('selectable-deck-remove')
                .append(
                    $('')
                    .attr('href', '#')
                    .button({
                        icons: {
                            primary: self.options.removeIcon
                        },
                        text: false
                    })
                    .click(function() {
                        $(input).remove();
                        $(this).closest('li').remove();
                        return false;
                    })
                )
            );
        },

        select: function(item) {
            /* Trigger selection of a given item.
            Item should contain two properties: id and value */
            var self = this,
            input = this.element;
            $(input).removeClass('ui-state-error');
            if (item) {
                if (self.allowMultiple) {
                    $(input).val("");
                    $(input).data("autocomplete").term = "";
                    if ($(self.hiddenMultipleSelector + '[value=' + item.id + ']').length === 0) {
                        var newInput = $('<input />', {
                            'type': 'hidden',
                            'name': self.hiddenName,
                            'value': item.id,
                            'title': item.value,
                            'data-selectable-type': 'hidden-multiple'
                        });
                        $(input).after(newInput);
                        self._addDeckItem(newInput);
                        return false;
                    }
                } else {
                    $(input).val(item.value);
                    var ui = {item: item};
                    $(input).trigger('autocompleteselect', [ui ]);
                }
            }
        },

        _create: function() {
            /* Initialize a new selectable widget */
            var self = this,
            input = this.element,
            data = $(input).data();
            self.allowNew = data.selectableAllowNew || data['selectable-allow-new'];
            self.allowMultiple = data.selectableMultiple || data['selectable-multiple'];
            self.textName = $(input).attr('name');
            self.hiddenName = self.textName.replace('_0', '_1');
            self.hiddenSelector = ':input[data-selectable-type=hidden][name=' + self.hiddenName + ']';
            self.hiddenMultipleSelector = ':input[data-selectable-type=hidden-multiple][name=' + self.hiddenName + ']';
            if (self.allowMultiple) {
                self.allowNew = false;
                $(input).val("");
                this._initDeck();
            }

            function dataSource(request, response) {
                /* Custom data source to uses the lookup url with pagination
                Adds hook for adjusting query parameters.
                Includes timestamp to prevent browser caching the lookup. */
                var url = data.selectableUrl || data['selectable-url'];
                var now = new Date().getTime();
                var query = {term: request.term, timestamp: now};
                if (self.options.prepareQuery) {
                    self.options.prepareQuery(query);
                }
                var page = $(input).data("page");
                if (page) {
                    query.page = page;
                }
				$.getJSON(url, query, response);
            }
            // Create base auto-complete lookup
            $(input).autocomplete({
                source: dataSource,
                change: function(event, ui) {
                    $(input).removeClass('ui-state-error');
                    if ($(input).val() && !ui.item) {
                        if (!self.allowNew) {
                            $(input).addClass('ui-state-error');
                        }
                    }
                    if (self.allowMultiple && !$(input).hasClass('ui-state-error')) {
                        $(input).val("");
                        $(input).data("autocomplete").term = "";
                    }
                },
                select: function(event, ui) {
                    $(input).removeClass('ui-state-error');
                    if (ui.item && ui.item.page) {
                        // Set current page value
                        $(input).data("page", ui.tem.page);
                        $('.selectable-paginator', self.menu).remove();
                        // Search for next page of results
                        $(input).autocomplete("search");
                        return false;
                    }
                    self.select(ui.item);
                }
            }).addClass("ui-widget ui-widget-content ui-corner-all");
            // Override the default auto-complete render.
            $(input).data("autocomplete")._renderItem = function(ul, item) {
                /* Adds hook for additional formatting, allows HTML in the label,
                highlights term matches and handles pagination. */
                var label = item.label;
                if (self.options.formatLabel) {
                    label = self.options.formatLabel(label, item);
                }
                if (self.options.highlightMatch) {
                    var re = new RegExp("(?![^&;]+;)(?!<[^<>]*)(" +
                    $.ui.autocomplete.escapeRegex(this.term) +
                    ")(?![^<>]*>)(?![^&;]+;)", "gi");
                    label = label.replace(re, "$1");
                }
                var li =  $("

")
                    .data("item.autocomplete", item)
                    .append($("").append(label))
                    .appendTo(ul);
                if (item.page) {
                    li.addClass('selectable-paginator');
                }
                return li;
            };
            // Override the default auto-complete suggest.
            $(input).data("autocomplete")._suggest = function(items) {
                /* Needed for handling pagination links */
                var page = $(input).data('page');
                var ul = this.menu.element;
                if (!page) {
                    ul.empty();
                }
                $(input).data('page', null);
                ul.zIndex(this.element.zIndex() + 1);
                this._renderMenu(ul, items);
                this.menu.deactivate();
                this.menu.refresh();
                // size and position menu
                ul.show();
                this._resizeMenu();
                ul.position($.extend({of: this.element}, this.options.position));
                if (this.options.autoFocus) {
                    this.menu.next(new $.Event("mouseover"));
                }
            };
            // Additional work for combobox widgets
            var selectableType = data.selectableType || data['selectable-type'];
            if (selectableType === 'combobox') {
                // Change auto-complete options
                $(input).autocomplete("option", {
                    delay: 0,
                    minLength: 0
                })
                .removeClass("ui-corner-all")
                .addClass("ui-corner-left ui-combo-input");
                // Add show all items button
                $("<button> </button>").attr("tabIndex", -1).attr("title", "Show All Items")
                .insertAfter($(input))
                .button({
                    icons: {
                        primary: self.options.comboboxIcon
                    },
                    text: false
                })
                .removeClass("ui-corner-all")
                .addClass("ui-corner-right ui-button-icon ui-combo-button")
                .click(function() {
                    // close if already visible
                    if ($(input).autocomplete("widget").is(":visible")) {
                        $(input).autocomplete("close");
                        return false;
                    }
                    // pass empty string as value to search for, displaying all results
                    $(input).autocomplete("search", "");
                    $(input).focus();
                    return false;
                });
            }
        }
	});
})(jQuery);

function bindSelectables(context) {
    /* Bind all selectable widgets in a given context.
    Automatically called on document.ready.
    Additional calls can be made for dynamically added widgets.
    */
    $(":input[data-selectable-type=text]", context).djselectable();
    $(":input[data-selectable-type=combobox]", context).djselectable();
    $(":input[data-selectable-type=hidden]", context).each(function(i, elem) {
        var hiddenName = $(elem).attr('name');
        var textName = hiddenName.replace('_1', '_0');
        $(":input[name=" + textName + "][data-selectable-url]").bind(
            "autocompletechange autocompleteselect",
            function(event, ui) {
                if (ui.item && ui.item.id) {
                    $(elem).val(ui.item.id);
                } else {
                    $(elem).val("");
                }
            }
        );
    });
}

/* Monkey-patch Django's dynamic formset, if defined */
if (typeof(django) !== "undefined" && typeof(django.jQuery) !== "undefined") {
    if (django.jQuery.fn.formset) {
        var oldformset = django.jQuery.fn.formset;
        django.jQuery.fn.formset = function(opts) {
            var options = $.extend({}, opts);
            var addedevent = function(row) {
                bindSelectables($(row));
            };
            var added = null;
            if (options.added) {
                // Wrap previous added function and include call to bindSelectables
                var oldadded = options.added;
                added = function(row) { oldadded(row); addedevent(row); };
            }
            options.added = added || addedevent;
            return oldformset.call(this, options);
        };
    }
}

/* Monkey-patch Django's dismissAddAnotherPopup(), if defined */
if (typeof(dismissAddAnotherPopup) !== "undefined" && typeof(windowname_to_id) !== "undefined" && typeof(html_unescape) !== "undefined") {
    var django_dismissAddAnotherPopup = dismissAddAnotherPopup;
    dismissAddAnotherPopup = function(win, newId, newRepr) {
        /* See if the popup came from a selectable field.
           If not, pass control to Django's code.
           If so, handle it. */
        var fieldName = windowname_to_id(win.name); /* e.g. "id_fieldname" */
        var field = $('#' + fieldName);
        var multiField = $('#' + fieldName + '_0');
        /* Check for bound selectable */
        var singleWidget = field.data('djselectable');
        var multiWidget = multiField.data('djselectable');
        if (singleWidget || multiWidget) {
            // newId and newRepr are expected to have previously been escaped by
            // django.utils.html.escape.
            var item =  {
                id: html_unescape(newId),
                value: html_unescape(newRepr)
            };
            if (singleWidget) {
                field.djselectable('select', item);
            }
            if (multiWidget) {
                multiField.djselectable('select', item);
            }
            win.close();
        } else {
            /* Not ours, pass on to original function. */
            return django_dismissAddAnotherPopup(win, newId, newRepr);
        }
    };
}

$(document).ready(function() {
    // Bind existing widgets on document ready
    bindSelectables('body');
});
<commit_msg>Allow disabling the auto-bind behavior of all seletable widgets on page load.<commit_after>/*
 * django-selectable UI widget
 * Source: https://bitbucket.org/mlavin/django-selectable
 * Docs: http://django-selectable.readthedocs.org/
 *
 * Depends:
 *   - jQuery 1.4.3+
 *   - jQuery UI 1.8 widget factory
 *
 * Copyright 2010-2012, Mark Lavin
 * BSD License
 *
*/
(function($) {

	$.widget("ui.djselectable", {

        options: {
            removeIcon: "ui-icon-close",
            comboboxIcon: "ui-icon-triangle-1-s",
            prepareQuery: null,
            highlightMatch: true,
            formatLabel: null
        },

        _initDeck: function() {
            /* Create list display for currently selected items for multi-select */
            var self = this;
            var data = $(this.element).data();
            var style = data.selectablePosition || data['selectable-position'] || 'bottom';
            this.deck = $('
').addClass('ui-widget selectable-deck selectable-deck-' + style);
            if (style === 'bottom' || style === 'bottom-inline') {
                $(this.element).after(this.deck);
            } else {
                $(this.element).before(this.deck);
            }
            $(self.hiddenMultipleSelector).each(function(i, input) {
                self._addDeckItem(input);
            });
        },

        _addDeckItem: function(input) {
            /* Add new deck list item from a given hidden input */
            var self = this;
            $('
')
            .text($(input).attr('title'))
            .addClass('selectable-deck-item')
            .appendTo(this.deck)
            .append(
                $('
')
                .addClass('selectable-deck-remove')
                .append(
                    $('')
                    .attr('href', '#')
                    .button({
                        icons: {
                            primary: self.options.removeIcon
                        },
                        text: false
                    })
                    .click(function() {
                        $(input).remove();
                        $(this).closest('li').remove();
                        return false;
                    })
                )
            );
        },

        select: function(item) {
            /* Trigger selection of a given item.
            Item should contain two properties: id and value */
            var self = this,
            input = this.element;
            $(input).removeClass('ui-state-error');
            if (item) {
                if (self.allowMultiple) {
                    $(input).val("");
                    $(input).data("autocomplete").term = "";
                    if ($(self.hiddenMultipleSelector + '[value=' + item.id + ']').length === 0) {
                        var newInput = $('<input />', {
                            'type': 'hidden',
                            'name': self.hiddenName,
                            'value': item.id,
                            'title': item.value,
                            'data-selectable-type': 'hidden-multiple'
                        });
                        $(input).after(newInput);
                        self._addDeckItem(newInput);
                        return false;
                    }
                } else {
                    $(input).val(item.value);
                    var ui = {item: item};
                    $(input).trigger('autocompleteselect', [ui ]);
                }
            }
        },

        _create: function() {
            /* Initialize a new selectable widget */
            var self = this,
            input = this.element,
            data = $(input).data();
            self.allowNew = data.selectableAllowNew || data['selectable-allow-new'];
            self.allowMultiple = data.selectableMultiple || data['selectable-multiple'];
            self.textName = $(input).attr('name');
            self.hiddenName = self.textName.replace('_0', '_1');
            self.hiddenSelector = ':input[data-selectable-type=hidden][name=' + self.hiddenName + ']';
            self.hiddenMultipleSelector = ':input[data-selectable-type=hidden-multiple][name=' + self.hiddenName + ']';
            if (self.allowMultiple) {
                self.allowNew = false;
                $(input).val("");
                this._initDeck();
            }

            function dataSource(request, response) {
                /* Custom data source to uses the lookup url with pagination
                Adds hook for adjusting query parameters.
                Includes timestamp to prevent browser caching the lookup. */
                var url = data.selectableUrl || data['selectable-url'];
                var now = new Date().getTime();
                var query = {term: request.term, timestamp: now};
                if (self.options.prepareQuery) {
                    self.options.prepareQuery(query);
                }
                var page = $(input).data("page");
                if (page) {
                    query.page = page;
                }
				$.getJSON(url, query, response);
            }
            // Create base auto-complete lookup
            $(input).autocomplete({
                source: dataSource,
                change: function(event, ui) {
                    $(input).removeClass('ui-state-error');
                    if ($(input).val() && !ui.item) {
                        if (!self.allowNew) {
                            $(input).addClass('ui-state-error');
                        }
                    }
                    if (self.allowMultiple && !$(input).hasClass('ui-state-error')) {
                        $(input).val("");
                        $(input).data("autocomplete").term = "";
                    }
                },
                select: function(event, ui) {
                    $(input).removeClass('ui-state-error');
                    if (ui.item && ui.item.page) {
                        // Set current page value
                        $(input).data("page", ui.tem.page);
                        $('.selectable-paginator', self.menu).remove();
                        // Search for next page of results
                        $(input).autocomplete("search");
                        return false;
                    }
                    self.select(ui.item);
                }
            }).addClass("ui-widget ui-widget-content ui-corner-all");
            // Override the default auto-complete render.
            $(input).data("autocomplete")._renderItem = function(ul, item) {
                /* Adds hook for additional formatting, allows HTML in the label,
                highlights term matches and handles pagination. */
                var label = item.label;
                if (self.options.formatLabel) {
                    label = self.options.formatLabel(label, item);
                }
                if (self.options.highlightMatch) {
                    var re = new RegExp("(?![^&;]+;)(?!<[^<>]*)(" +
                    $.ui.autocomplete.escapeRegex(this.term) +
                    ")(?![^<>]*>)(?![^&;]+;)", "gi");
                    label = label.replace(re, "$1");
                }
                var li =  $("

")
                    .data("item.autocomplete", item)
                    .append($("").append(label))
                    .appendTo(ul);
                if (item.page) {
                    li.addClass('selectable-paginator');
                }
                return li;
            };
            // Override the default auto-complete suggest.
            $(input).data("autocomplete")._suggest = function(items) {
                /* Needed for handling pagination links */
                var page = $(input).data('page');
                var ul = this.menu.element;
                if (!page) {
                    ul.empty();
                }
                $(input).data('page', null);
                ul.zIndex(this.element.zIndex() + 1);
                this._renderMenu(ul, items);
                this.menu.deactivate();
                this.menu.refresh();
                // size and position menu
                ul.show();
                this._resizeMenu();
                ul.position($.extend({of: this.element}, this.options.position));
                if (this.options.autoFocus) {
                    this.menu.next(new $.Event("mouseover"));
                }
            };
            // Additional work for combobox widgets
            var selectableType = data.selectableType || data['selectable-type'];
            if (selectableType === 'combobox') {
                // Change auto-complete options
                $(input).autocomplete("option", {
                    delay: 0,
                    minLength: 0
                })
                .removeClass("ui-corner-all")
                .addClass("ui-corner-left ui-combo-input");
                // Add show all items button
                $("<button> </button>").attr("tabIndex", -1).attr("title", "Show All Items")
                .insertAfter($(input))
                .button({
                    icons: {
                        primary: self.options.comboboxIcon
                    },
                    text: false
                })
                .removeClass("ui-corner-all")
                .addClass("ui-corner-right ui-button-icon ui-combo-button")
                .click(function() {
                    // close if already visible
                    if ($(input).autocomplete("widget").is(":visible")) {
                        $(input).autocomplete("close");
                        return false;
                    }
                    // pass empty string as value to search for, displaying all results
                    $(input).autocomplete("search", "");
                    $(input).focus();
                    return false;
                });
            }
        }
	});
})(jQuery);

function bindSelectables(context) {
    /* Bind all selectable widgets in a given context.
    Automatically called on document.ready.
    Additional calls can be made for dynamically added widgets.
    */
    $(":input[data-selectable-type=text]", context).djselectable();
    $(":input[data-selectable-type=combobox]", context).djselectable();
    $(":input[data-selectable-type=hidden]", context).each(function(i, elem) {
        var hiddenName = $(elem).attr('name');
        var textName = hiddenName.replace('_1', '_0');
        $(":input[name=" + textName + "][data-selectable-url]").bind(
            "autocompletechange autocompleteselect",
            function(event, ui) {
                if (ui.item && ui.item.id) {
                    $(elem).val(ui.item.id);
                } else {
                    $(elem).val("");
                }
            }
        );
    });
}

/* Monkey-patch Django's dynamic formset, if defined */
if (typeof(django) !== "undefined" && typeof(django.jQuery) !== "undefined") {
    if (django.jQuery.fn.formset) {
        var oldformset = django.jQuery.fn.formset;
        django.jQuery.fn.formset = function(opts) {
            var options = $.extend({}, opts);
            var addedevent = function(row) {
                bindSelectables($(row));
            };
            var added = null;
            if (options.added) {
                // Wrap previous added function and include call to bindSelectables
                var oldadded = options.added;
                added = function(row) { oldadded(row); addedevent(row); };
            }
            options.added = added || addedevent;
            return oldformset.call(this, options);
        };
    }
}

/* Monkey-patch Django's dismissAddAnotherPopup(), if defined */
if (typeof(dismissAddAnotherPopup) !== "undefined" && typeof(windowname_to_id) !== "undefined" && typeof(html_unescape) !== "undefined") {
    var django_dismissAddAnotherPopup = dismissAddAnotherPopup;
    dismissAddAnotherPopup = function(win, newId, newRepr) {
        /* See if the popup came from a selectable field.
           If not, pass control to Django's code.
           If so, handle it. */
        var fieldName = windowname_to_id(win.name); /* e.g. "id_fieldname" */
        var field = $('#' + fieldName);
        var multiField = $('#' + fieldName + '_0');
        /* Check for bound selectable */
        var singleWidget = field.data('djselectable');
        var multiWidget = multiField.data('djselectable');
        if (singleWidget || multiWidget) {
            // newId and newRepr are expected to have previously been escaped by
            // django.utils.html.escape.
            var item =  {
                id: html_unescape(newId),
                value: html_unescape(newRepr)
            };
            if (singleWidget) {
                field.djselectable('select', item);
            }
            if (multiWidget) {
                multiField.djselectable('select', item);
            }
            win.close();
        } else {
            /* Not ours, pass on to original function. */
            return django_dismissAddAnotherPopup(win, newId, newRepr);
        }
    };
}

$(document).ready(function() {
    // Bind existing widgets on document ready
    if (typeof(djselectableAutoLoad) === "undefined" || djselectableAutoLoad) {
        bindSelectables('body');
    }
});
<|endoftext|>


<commit_before>var assert = require('chai').assert;
var os = require('os');
var request = require('request');
var mongoose = require('mongoose');
var async = require('async');
var utils = require(__dirname + '/../services/utils');

var properties = require(__dirname + '/../properties/properties');
var default_properties = properties;

var port = process.env.PORT || 3000;
var server_url = 'http://' + os.hostname() + ':' + port;

var api_controller;
var userDb_controller;

describe('Esup otp api', function () {
    it('Server is running', function (done) {
        var port = process.env.PORT || 3000;
        request({url: server_url}, function (error, response, body) {
            if (error) throw error;
            done();
        });
    });

    describe('Simple user api', function () {
        beforeEach(function (done) {
            create_user('test_user', function () {
                done();
            })
        });

        it('get test_user', function (done) {
            var url = server_url + '/user/test_user/' + utils.get_hash('test_user')[1]
            request({url: url}, function (error, response, body) {
                if (error) throw error;
                assert(JSON.parse(body).code == 'Ok');
                done();
            });
        })

        it('get test_user with wrong hash', function (done) {
            var url = server_url + '/user/test_user/turlututuchapeaupointu'
            request({url: url}, function (error, response, body) {
                if (error) throw error;
                assert(JSON.parse(body).code == 'ForbiddenError');
                done();
            });
        })

        it('get unknown user with auto_create', function (done) {
            toggle_auto_create_user(true, function () {
                var url = server_url + '/user/unknown_user/' + utils.get_hash('unknown_user')[1]
                request({url: url}, function (error, response, body) {
                    if (error) throw error;
                    assert(JSON.parse(body).code == 'Ok');
                    done();
                });
            })
        })

        it('get unknown user without auto_create', function (done) {
            toggle_auto_create_user(false, function () {
                var url = server_url + '/user/unknown_user/' + utils.get_hash('unknown_user')[1]
                request({url: url}, function (error, response, body) {
                    if (error) throw error;
                    assert(JSON.parse(body).message == properties.messages.error.user_not_found);
                    done();
                });
            })
        })

        it('get test_user totp method secret, qrCode must be empty', function (done) {
                var url = server_url + '/protected/user/test_user/method/totp/secret/' +properties.esup.api_password
                request({url: url}, function (error, response, body) {
                    if (error) throw error;
                    assert(JSON.parse(body).qrCode == '');
                    done();
                });
        })

        it('get test_user bypass method secret response must be an error message', function (done) {
            var url = server_url + '/protected/user/test_user/method/bypass/secret/' +properties.esup.api_password
            request({url: url}, function (error, response, body) {
                if (error) throw error;
                assert(JSON.parse(body).message == properties.messages.error.unvailable_method_operation);
                done();
            });
        })

        it('get test_user random_code method secret response must be an error message', function (done) {
            var url = server_url + '/protected/user/test_user/method/random_code/secret/' +properties.esup.api_password
            request({url: url}, function (error, response, body) {
                if (error) throw error;
                assert(JSON.parse(body).message == properties.messages.error.unvailable_method_operation);
                done();
            });
        })

        it('get test_user totp method generate secret', function (done) {
            var url = server_url + '/protected/user/test_user/method/totp/secret/' +properties.esup.api_password
            request({url: url, method : "POST"}, function (error, response, body) {
                if (error) throw error;
                assert(JSON.parse(body).code == 'Ok');
                done();
            });
        })

        afterEach(function (done) {
            properties = default_properties;
            toggle_auto_create_user(true, function () {
                remove_user('test_user', function () {
                    remove_user('unknown_user', function () {
                        done();
                    })
                })
            })
        })
    })
});

function toggle_auto_create_user(activate, callback) {
    var bool = 'deactivate'
    if (activate)bool = 'activate';
    var url = server_url + '/test/auto_create/' + bool + '/' + properties.esup.api_password;
    request({url: url, method: 'PUT'}, function (error, response, body) {
        if (error)throw error;
        if (typeof(callback) === 'function')callback();
    });
}

function create_user(uid, callback) {
    var url = server_url + '/test/user/' + uid + '/' + properties.esup.api_password;
    request({url: url, method: 'POST'}, function (error, response, body) {
        if (error)throw error;
        if (typeof(callback) === 'function')callback();
    });
}

function remove_user(uid, callback) {
    var url = server_url + '/test/user/' + uid + '/' + properties.esup.api_password;
    request({url: url, method: 'DELETE'}, function (error, response, body) {
        if (error)throw error;
        if (typeof(callback) === 'function')callback();
    });
}<commit_msg>test_user name stored in a variable<commit_after>var assert = require('chai').assert;
var os = require('os');
var request = require('request');
var mongoose = require('mongoose');
var async = require('async');
var utils = require(__dirname + '/../services/utils');

var properties = require(__dirname + '/../properties/properties');
var default_properties = properties;

var port = process.env.PORT || 3000;
var server_url = 'http://' + os.hostname() + ':' + port;

var test_user = 'karlito'

describe('Esup otp api', function () {
    it('Server is running', function (done) {
        var port = process.env.PORT || 3000;
        request({url: server_url}, function (error, response, body) {
            if (error) throw error;
            done();
        });
    });

    describe('Simple user api', function () {
        beforeEach(function (done) {
            create_user(test_user, function () {
                done();
            })
        });

        it('get test_user', function (done) {
            var url = server_url + '/user/'+test_user+'/' + utils.get_hash(test_user)[1]
            request({url: url}, function (error, response, body) {
                if (error) throw error;
                assert(JSON.parse(body).code == 'Ok');
                done();
            });
        })

        it('get test_user with wrong hash', function (done) {
            var url = server_url + '/user/'+test_user+'/turlututuchapeaupointu'
            request({url: url}, function (error, response, body) {
                if (error) throw error;
                assert(JSON.parse(body).code == 'ForbiddenError');
                done();
            });
        })

        it('get unknown user with auto_create', function (done) {
            toggle_auto_create_user(true, function () {
                var url = server_url + '/user/unknown_user/' + utils.get_hash('unknown_user')[1]
                request({url: url}, function (error, response, body) {
                    if (error) throw error;
                    if(properties.esup.userDb=='mongodb')assert(JSON.parse(body).code == 'Ok');
                    assert(JSON.parse(body).message == properties.messages.error.user_not_found);
                    done();
                });
            })
        })

        it('get unknown user without auto_create', function (done) {
            toggle_auto_create_user(false, function () {
                var url = server_url + '/user/unknown_user/' + utils.get_hash('unknown_user')[1]
                request({url: url}, function (error, response, body) {
                    if (error) throw error;
                    assert(JSON.parse(body).message == properties.messages.error.user_not_found);
                    done();
                });
            })
        })

        it('get test_user totp method secret, qrCode must be empty', function (done) {
                var url = server_url + '/protected/user/'+test_user+'/method/totp/secret/' +properties.esup.api_password
                request({url: url}, function (error, response, body) {
                    if (error) throw error;
                    assert(JSON.parse(body).qrCode == '');
                    done();
                });
        })

        it('get test_user bypass method secret response must be an error message', function (done) {
            var url = server_url + '/protected/user/'+test_user+'/method/bypass/secret/' +properties.esup.api_password
            request({url: url}, function (error, response, body) {
                if (error) throw error;
                assert(JSON.parse(body).message == properties.messages.error.unvailable_method_operation);
                done();
            });
        })

        it('get test_user random_code method secret response must be an error message', function (done) {
            var url = server_url + '/protected/user/'+test_user+'/method/random_code/secret/' +properties.esup.api_password
            request({url: url}, function (error, response, body) {
                if (error) throw error;
                assert(JSON.parse(body).message == properties.messages.error.unvailable_method_operation);
                done();
            });
        })

        it('get test_user totp method generate secret', function (done) {
            var url = server_url + '/protected/user/'+test_user+'/method/totp/secret/' +properties.esup.api_password
            request({url: url, method : "POST"}, function (error, response, body) {
                if (error) throw error;
                assert(JSON.parse(body).code == 'Ok');
                done();
            });
        })

        afterEach(function (done) {
            properties = default_properties;
            toggle_auto_create_user(true, function () {
                remove_user(test_user, function () {
                    remove_user('unknown_user', function () {
                        done();
                    })
                })
            })
        })
    })
});

function toggle_auto_create_user(activate, callback) {
    var bool = 'deactivate'
    if (activate)bool = 'activate';
    var url = server_url + '/test/auto_create/' + bool + '/' + properties.esup.api_password;
    request({url: url, method: 'PUT'}, function (error, response, body) {
        if (error)throw error;
        if (typeof(callback) === 'function')callback();
    });
}

function create_user(uid, callback) {
    var url = server_url + '/test/user/' + uid + '/' + properties.esup.api_password;
    request({url: url, method: 'POST'}, function (error, response, body) {
        if (error)throw error;
        if (typeof(callback) === 'function')callback();
    });
}

function remove_user(uid, callback) {
    var url = server_url + '/test/user/' + uid + '/' + properties.esup.api_password;
    request({url: url, method: 'DELETE'}, function (error, response, body) {
        if (error)throw error;
        if (typeof(callback) === 'function')callback();
    });
}<|endoftext|>


<commit_before>/**
 * ethereumjs-connect unit tests
 * @author Jack Peterson (jack@tinybike.net)
 */

"use strict";

var join = require("path").join;
var assert = require("chai").assert;
var connector = require("../");
connector.debug = true;

var TIMEOUT = 48000;
var IPCPATH = process.env.GETH_IPC;

require('it-each')({testPerIteration: true});

var custom_contracts = {
    "buyAndSellShares": "0x1",
    "closeMarket": "0x2",
    "closeMarketEight": "0x3",
    "closeMarketFour": "0x4",
    "closeMarketOne": "0x5",
    "closeMarketTwo": "0x6",
    "collectFees": "0x7",
    "completeSets": "0x8",
    "compositeGetters": "0x9",
    "consensus": "0x10",
    "createBranch": "0x11",
    "createMarket": "0x12",
    "createSingleEventMarket": "0x13",
    "eventResolution": "0x14",
    "faucets": "0x15",
    "forkPenalize": "0x16",
    "forking": "0x17",
    "makeReports": "0x18",
    "penalizationCatchup": "0x19",
    "penalizeNotEnoughReports": "0x20",
    "roundTwo": "0x21",
    "roundTwoPenalize": "0x22",
    "sendReputation": "0x23",
    "slashRep": "0x24",
    "trade": "0x25",
    "backstops": "0x26",
    "branches": "0x27",
    "cash": "0x28",
    "consensusData": "0x29",
    "events": "0x30",
    "expiringEvents": "0x31",
    "fxpFunctions": "0x32",
    "info": "0x33",
    "markets": "0x34",
    "reporting": "0x35",
    "trades": "0x36"
};

describe("has_value", function () {

    var test = function (t) {
        it(JSON.stringify(t.object) + " has value " + t.value + " -> " + t.expected, function () {
            assert.strictEqual(connector.has_value(t.object, t.value), t.expected);
        });
    };

    test({
        object: {"augur": 42},
        value: 42,
        expected: "augur"
    });
    test({
        object: {"augur": 42},
        value: "augur",
        expected: undefined
    });
    test({
        object: {"augur": 42},
        value: 41,
        expected: undefined
    });
    test({
        object: {"augur": 42, "whee": "thereum"},
        value: "thereum",
        expected: "whee"
    });
    test({
        object: {"augur": 42, "whee": "thereum"},
        value: 42,
        expected: "augur"
    });
    test({
        object: {"augur": 42, "whee": "thereum"},
        value: "42",
        expected: undefined
    });
    test({
        object: {"augur": 42, "whee": "thereum"},
        value: "whee",
        expected: undefined
    });
    test({
        object: {"augur": 42, "whee": "thereum"},
        value: -42,
        expected: undefined
    });
    test({
        object: {"augur": 42, "whee": "thereum"},
        value: undefined,
        expected: undefined
    });
    test({
        object: {"augur": 42, "whee": "thereum"},
        value: null,
        expected: undefined
    });
    test({
        object: {"augur": null, "whee": "thereum"},
        value: null,
        expected: "augur"
    });
    test({
        object: {"augur": 42, "whee": "thereum"},
        value: "0x42",
        expected: undefined
    });
    test({
        object: {},
        value: null,
        expected: undefined
    });
    test({
        object: {},
        value: undefined,
        expected: undefined
    });
    test({
        object: {},
        value: 0,
        expected: undefined
    });
});

describe("connect", function () {

    describe("hosted node fallback", function () {
        var test = function (t) {
            it("[async] " + JSON.stringify(t), function (done) {
                this.timeout(TIMEOUT);
                delete require.cache[require.resolve("../")];
                var connector = require("../");
                connector.connect(t, function (connection) {
                    assert.deepEqual(connection, t.expected);
                    assert.strictEqual(connector.rpc.wsUrl, t.expected.ws);
                    assert.strictEqual(connector.rpc.ipcpath, t.expected.ipc);
                    done();
                });
            });
            it("[sync] " + JSON.stringify(t), function () {
                delete require.cache[require.resolve("../")];
                var connector = require("../");
                var connection = connector.connect(t);
                assert.deepEqual(connection.http, t.expected.http);
                if (t.expected.ws !== null) {
                    assert.strictEqual(connector.rpc.wsUrl, t.expected.ws);
                }
                if (t.expected.ipc !== null) {
                    assert.strictEqual(connector.rpc.ipcpath, t.expected.ipc);
                }
            });
        };
        test({
            http: "https://eth3.augur.net",
            ws: "wss://ws.augur.net",
            expected: {
                http: "https://eth3.augur.net",
                ws: "wss://ws.augur.net",
                ipc: null
            }
        });
        test({
            http: "https://eth3.augur.net",
            ws: "wss://lulz.augur.net",
            expected: {
                http: "https://eth3.augur.net",
                ws: null,
                ipc: null
            }
        });
        test({
            http: "https://lulz.augur.net",
            ws: null,
            expected: {
                http: ["https://eth3.augur.net"],
                ws: "wss://ws.augur.net",
                ipc: null
            }
        });
        test({
            http: "https://eth3.augur.net",
            ws: null,
            expected: {
                http: "https://eth3.augur.net",
                ws: null,
                ipc: null
            }
        });
        test({
            http: "https://lulz.augur.net",
            ws: "wss://ws.augur.net",
            expected: {
                http: ["https://eth3.augur.net"],
                ws: "wss://ws.augur.net",
                ipc: null
            }
        });
        test({
            http: "https://lulz.augur.net",
            ws: "wss://lulz.augur.net",
            expected: {
                http: ["https://eth3.augur.net"],
                ws: "wss://ws.augur.net",
                ipc: null
            }
        });
        test({
            http: "https://not.a.real.url",
            ws: "wss://not.a.real.url",
            expected: {
                http: ["https://eth3.augur.net"],
                ws: "wss://ws.augur.net",
                ipc: null
            }
        });
        test({
            http: "http://127.0.0.2:2121",
            ws: "ws://127.0.0.2:1212",
            expected: {
                http: ["https://eth3.augur.net"],
                ws: "wss://ws.augur.net",
                ipc: null
            }
        });
        if (process.env.INTEGRATION_TESTS) {
            test({
                http: "http://127.0.0.1:8545",
                ws: "ws://127.0.0.1:8546",
                expected: {
                    http: "http://127.0.0.1:8545",
                    ws: "ws://127.0.0.1:8546",
                    ipc: null
                }
            });
        }
    });

    describe("hosted nodes", function () {
        var test = function (t) {
            it("[sync] " + JSON.stringify(t.node), function () {
                this.timeout(TIMEOUT);
                delete require.cache[require.resolve("../")];
                var connector = require("../");
                var conn = connector.connect(t.node);
                assert.isObject(conn);
                assert.strictEqual(conn.http, t.node.http);
                assert.strictEqual(conn.ws, t.node.ws);
                assert.isNull(conn.ipc);
                assert.strictEqual(connector.coinbase, t.address);
            });
            it("[async] " + JSON.stringify(t.node), function () {
                this.timeout(TIMEOUT);
                delete require.cache[require.resolve("../")];
                var connector = require("../");
                connector.connect(t.node, function (conn) {
                    assert.isObject(conn);
                    assert.strictEqual(conn.http, t.node.http);
                    assert.strictEqual(conn.ws, t.node.ws);
                    assert.isNull(conn.ipc);
                    assert.strictEqual(connector.coinbase, t.address);
                });
            });
        };
        test({
            node: {http: "https://eth3.augur.net"},
            address: "0x00bae5113ee9f252cceb0001205b88fad175461a"
        });
        test({
            node: {http: "https://eth3.augur.net", ws: "wss://ws.augur.net"},
            address: "0x00bae5113ee9f252cceb0001205b88fad175461a"
        });
    });

    if (process.env.ETHEREUMJS_INTEGRATION_TESTS) {
        describe("local node", function () {
            var connectOptions = [
                {http: "http://localhost:8545"},
                {http: "http://127.0.0.1:8545"}
            ];
            it.each(connectOptions,
                "[sync] connect to",
                ["element"],
                function (element, next) {
                    this.timeout(TIMEOUT);
                    delete require.cache[require.resolve("../")];
                    var connector = require("../");
                    var conn = connector.connect(element);
                    assert.isObject(conn);
                    assert.strictEqual(conn.http, element.http);
                    assert.strictEqual(conn.ws, element.ws);
                    assert.strictEqual(conn.ipc, element.ipc);
                    assert.isTrue(connector.connected());
                    assert.isString(connector.coinbase);
                    next();
                }
            );
            it.each(connectOptions,
                "[sync] connect with custom contracts",
                ["element"],
                function (element, next) {
                    this.timeout(TIMEOUT);
                    delete require.cache[require.resolve("../")];
                    var connector = require("../");
                    var options = element;
                    options.contracts = custom_contracts;
                    var conn = connector.connect(options);
                    assert.isObject(conn);
                    assert.strictEqual(conn.http, element.http);
                    assert.strictEqual(conn.ws, element.ws);
                    assert.strictEqual(conn.ipc, element.ipc);
                    assert.isTrue(connector.connected());
                    assert.isString(connector.coinbase);
                    assert.deepEqual(connector.contracts, custom_contracts);
                    assert.deepEqual(connector.init_contracts, custom_contracts);
                    assert.deepEqual(connector.custom_contracts, custom_contracts);
                    next();
                }
            );
            it.each(connectOptions,
                "[sync] connect with IPC support",
                ["element"],
                function (element, next) {
                    this.timeout(TIMEOUT);
                    delete require.cache[require.resolve("../")];
                    var connector = require("../");
                    var options = element;
                    options.ipc = IPCPATH;
                    var conn = connector.connect(options);
                    assert.isObject(conn);
                    assert.strictEqual(conn.http, element.http);
                    assert.strictEqual(conn.ws, element.ws);
                    assert.strictEqual(conn.ipc, element.ipc);
                    assert.isTrue(connector.connected());
                    assert.isString(connector.coinbase);
                    next();
                }
            );
            it.each(connectOptions,
                "[async] connect to",
                ["element"],
                function (element, next) {
                    this.timeout(TIMEOUT);
                    delete require.cache[require.resolve("../")];
                    var connector = require("../");
                    connector.connect(element, function (conn) {
                        assert.isObject(conn);
                        assert.strictEqual(conn.http, element.http);
                        assert.strictEqual(conn.ws, element.ws);
                        assert.strictEqual(conn.ipc, element.ipc);
                        assert.isTrue(connector.connected());
                        assert.isString(connector.coinbase);
                        next();
                    });
                }
            );
            it.each(connectOptions,
                "[async] connect to",
                ["element"],
                function (element, next) {
                    this.timeout(TIMEOUT);
                    delete require.cache[require.resolve("../")];
                    var connector = require("../");
                    connector.connect(element, function (conn) {
                        assert.isObject(conn);
                        assert.strictEqual(conn.http, element.http);
                        assert.strictEqual(conn.ws, element.ws);
                        assert.strictEqual(conn.ipc, element.ipc);
                        assert.isTrue(connector.connected());
                        assert.isString(connector.coinbase);
                        next();
                    });
                }
            );
            it.each(connectOptions,
                "[async] connect with custom contracts",
                ["element"],
                function (element, next) {
                    this.timeout(TIMEOUT);
                    delete require.cache[require.resolve("../")];
                    var connector = require("../");
                    var options = element;
                    options.contracts = custom_contracts;
                    connector.connect(options, function (conn) {
                        assert.isObject(conn);
                        assert.strictEqual(conn.http, element.http);
                        assert.strictEqual(conn.ws, element.ws);
                        assert.strictEqual(conn.ipc, element.ipc);
                        assert.isTrue(connector.connected());
                        assert.isString(connector.coinbase);
                        assert.deepEqual(connector.contracts, custom_contracts);
                        assert.deepEqual(connector.init_contracts, custom_contracts);
                        assert.deepEqual(connector.custom_contracts, custom_contracts);
                        next();
                    });
                }
            );
            it.each(connectOptions,
                "[async] connect with IPC support",
                ["element"],
                function (element, next) {
                    this.timeout(TIMEOUT);
                    delete require.cache[require.resolve("../")];
                    var connector = require("../");
                    var options = element;
                    options.ipc = IPCPATH;
                    connector.connect(options, function (conn) {
                        assert.isObject(conn);
                        assert.strictEqual(conn.http, element.http);
                        assert.strictEqual(conn.ws, element.ws);
                        assert.strictEqual(conn.ipc, element.ipc);
                        assert.isTrue(connector.connected());
                        assert.isString(connector.coinbase);
                        next();
                    });
                }
            );
        });

        it("[sync] unlocked", function () {
            this.timeout(TIMEOUT);
            delete require.cache[require.resolve("../")];
            var connector = require("../");
            var conn = connector.connect({http: "http://localhost:8545"});
            assert.isNotNull(connector.rpc.nodes.local);
            assert.isTrue(connector.rpc.unlocked(connector.coinbase));
        });
        it("[async] unlocked", function (done) {
            this.timeout(TIMEOUT);
            delete require.cache[require.resolve("../")];
            var connector = require("../");
            connector.connect({http: "http://localhost:8545"}, function (conn) {
                connector.rpc.unlocked(connector.coinbase, function (unlocked) {
                    assert.isNotNull(connector.rpc.nodes.local);
                    assert.isTrue(unlocked);
                    done();
                });
            });
        });
    }

    it("[sync] unlocked", function () {
        this.timeout(TIMEOUT);
        delete require.cache[require.resolve("../")];
        var connector = require("../");
        var conn = connector.connect({http: "https://eth3.augur.net"});
        assert.isNotNull(connector.rpc.nodes.local);
        assert.isTrue(connector.rpc.unlocked(connector.coinbase));
    });
    it("[async] unlocked", function (done) {
        this.timeout(TIMEOUT);
        delete require.cache[require.resolve("../")];
        var connector = require("../");
        connector.connect({http: "https://eth3.augur.net"}, function (conn) {
            connector.rpc.unlocked(connector.coinbase, function (unlocked) {
                assert.isNotNull(connector.rpc.nodes.local);
                assert.isTrue(unlocked);
                done();
            });
        });
    });

    it("network_id = 0, 1, 2, 7, or 10101", function () {
        delete require.cache[require.resolve("../")];
        var connector = require("../");
        connector.connect();
        assert.include(["0", "1", "2", "7", "10101"], connector.network_id);
    });

});
<commit_msg>Updated hosted node unlocked assertions<commit_after>/**
 * ethereumjs-connect unit tests
 * @author Jack Peterson (jack@tinybike.net)
 */

"use strict";

var join = require("path").join;
var assert = require("chai").assert;
var connector = require("../");
connector.debug = true;

var TIMEOUT = 48000;
var IPCPATH = process.env.GETH_IPC;

require('it-each')({testPerIteration: true});

var custom_contracts = {
    "buyAndSellShares": "0x1",
    "closeMarket": "0x2",
    "closeMarketEight": "0x3",
    "closeMarketFour": "0x4",
    "closeMarketOne": "0x5",
    "closeMarketTwo": "0x6",
    "collectFees": "0x7",
    "completeSets": "0x8",
    "compositeGetters": "0x9",
    "consensus": "0x10",
    "createBranch": "0x11",
    "createMarket": "0x12",
    "createSingleEventMarket": "0x13",
    "eventResolution": "0x14",
    "faucets": "0x15",
    "forkPenalize": "0x16",
    "forking": "0x17",
    "makeReports": "0x18",
    "penalizationCatchup": "0x19",
    "penalizeNotEnoughReports": "0x20",
    "roundTwo": "0x21",
    "roundTwoPenalize": "0x22",
    "sendReputation": "0x23",
    "slashRep": "0x24",
    "trade": "0x25",
    "backstops": "0x26",
    "branches": "0x27",
    "cash": "0x28",
    "consensusData": "0x29",
    "events": "0x30",
    "expiringEvents": "0x31",
    "fxpFunctions": "0x32",
    "info": "0x33",
    "markets": "0x34",
    "reporting": "0x35",
    "trades": "0x36"
};

describe("has_value", function () {

    var test = function (t) {
        it(JSON.stringify(t.object) + " has value " + t.value + " -> " + t.expected, function () {
            assert.strictEqual(connector.has_value(t.object, t.value), t.expected);
        });
    };

    test({
        object: {"augur": 42},
        value: 42,
        expected: "augur"
    });
    test({
        object: {"augur": 42},
        value: "augur",
        expected: undefined
    });
    test({
        object: {"augur": 42},
        value: 41,
        expected: undefined
    });
    test({
        object: {"augur": 42, "whee": "thereum"},
        value: "thereum",
        expected: "whee"
    });
    test({
        object: {"augur": 42, "whee": "thereum"},
        value: 42,
        expected: "augur"
    });
    test({
        object: {"augur": 42, "whee": "thereum"},
        value: "42",
        expected: undefined
    });
    test({
        object: {"augur": 42, "whee": "thereum"},
        value: "whee",
        expected: undefined
    });
    test({
        object: {"augur": 42, "whee": "thereum"},
        value: -42,
        expected: undefined
    });
    test({
        object: {"augur": 42, "whee": "thereum"},
        value: undefined,
        expected: undefined
    });
    test({
        object: {"augur": 42, "whee": "thereum"},
        value: null,
        expected: undefined
    });
    test({
        object: {"augur": null, "whee": "thereum"},
        value: null,
        expected: "augur"
    });
    test({
        object: {"augur": 42, "whee": "thereum"},
        value: "0x42",
        expected: undefined
    });
    test({
        object: {},
        value: null,
        expected: undefined
    });
    test({
        object: {},
        value: undefined,
        expected: undefined
    });
    test({
        object: {},
        value: 0,
        expected: undefined
    });
});

describe("connect", function () {

    describe("hosted node fallback", function () {
        var test = function (t) {
            it("[async] " + JSON.stringify(t), function (done) {
                this.timeout(TIMEOUT);
                delete require.cache[require.resolve("../")];
                var connector = require("../");
                connector.connect(t, function (connection) {
                    assert.deepEqual(connection, t.expected);
                    assert.strictEqual(connector.rpc.wsUrl, t.expected.ws);
                    assert.strictEqual(connector.rpc.ipcpath, t.expected.ipc);
                    done();
                });
            });
            it("[sync] " + JSON.stringify(t), function () {
                delete require.cache[require.resolve("../")];
                var connector = require("../");
                var connection = connector.connect(t);
                assert.deepEqual(connection.http, t.expected.http);
                if (t.expected.ws !== null) {
                    assert.strictEqual(connector.rpc.wsUrl, t.expected.ws);
                }
                if (t.expected.ipc !== null) {
                    assert.strictEqual(connector.rpc.ipcpath, t.expected.ipc);
                }
            });
        };
        test({
            http: "https://eth3.augur.net",
            ws: "wss://ws.augur.net",
            expected: {
                http: "https://eth3.augur.net",
                ws: "wss://ws.augur.net",
                ipc: null
            }
        });
        test({
            http: "https://eth3.augur.net",
            ws: "wss://lulz.augur.net",
            expected: {
                http: "https://eth3.augur.net",
                ws: null,
                ipc: null
            }
        });
        test({
            http: "https://lulz.augur.net",
            ws: null,
            expected: {
                http: ["https://eth3.augur.net"],
                ws: "wss://ws.augur.net",
                ipc: null
            }
        });
        test({
            http: "https://eth3.augur.net",
            ws: null,
            expected: {
                http: "https://eth3.augur.net",
                ws: null,
                ipc: null
            }
        });
        test({
            http: "https://lulz.augur.net",
            ws: "wss://ws.augur.net",
            expected: {
                http: ["https://eth3.augur.net"],
                ws: "wss://ws.augur.net",
                ipc: null
            }
        });
        test({
            http: "https://lulz.augur.net",
            ws: "wss://lulz.augur.net",
            expected: {
                http: ["https://eth3.augur.net"],
                ws: "wss://ws.augur.net",
                ipc: null
            }
        });
        test({
            http: "https://not.a.real.url",
            ws: "wss://not.a.real.url",
            expected: {
                http: ["https://eth3.augur.net"],
                ws: "wss://ws.augur.net",
                ipc: null
            }
        });
        test({
            http: "http://127.0.0.2:2121",
            ws: "ws://127.0.0.2:1212",
            expected: {
                http: ["https://eth3.augur.net"],
                ws: "wss://ws.augur.net",
                ipc: null
            }
        });
        if (process.env.INTEGRATION_TESTS) {
            test({
                http: "http://127.0.0.1:8545",
                ws: "ws://127.0.0.1:8546",
                expected: {
                    http: "http://127.0.0.1:8545",
                    ws: "ws://127.0.0.1:8546",
                    ipc: null
                }
            });
        }
    });

    describe("hosted nodes", function () {
        var test = function (t) {
            it("[sync] " + JSON.stringify(t.node), function () {
                this.timeout(TIMEOUT);
                delete require.cache[require.resolve("../")];
                var connector = require("../");
                var conn = connector.connect(t.node);
                assert.isObject(conn);
                assert.strictEqual(conn.http, t.node.http);
                assert.strictEqual(conn.ws, t.node.ws);
                assert.isNull(conn.ipc);
                assert.strictEqual(connector.coinbase, t.address);
            });
            it("[async] " + JSON.stringify(t.node), function () {
                this.timeout(TIMEOUT);
                delete require.cache[require.resolve("../")];
                var connector = require("../");
                connector.connect(t.node, function (conn) {
                    assert.isObject(conn);
                    assert.strictEqual(conn.http, t.node.http);
                    assert.strictEqual(conn.ws, t.node.ws);
                    assert.isNull(conn.ipc);
                    assert.strictEqual(connector.coinbase, t.address);
                });
            });
        };
        test({
            node: {http: "https://eth3.augur.net"},
            address: "0x00bae5113ee9f252cceb0001205b88fad175461a"
        });
        test({
            node: {http: "https://eth3.augur.net", ws: "wss://ws.augur.net"},
            address: "0x00bae5113ee9f252cceb0001205b88fad175461a"
        });
    });

    if (process.env.ETHEREUMJS_INTEGRATION_TESTS) {
        describe("local node", function () {
            var connectOptions = [
                {http: "http://localhost:8545"},
                {http: "http://127.0.0.1:8545"}
            ];
            it.each(connectOptions,
                "[sync] connect to",
                ["element"],
                function (element, next) {
                    this.timeout(TIMEOUT);
                    delete require.cache[require.resolve("../")];
                    var connector = require("../");
                    var conn = connector.connect(element);
                    assert.isObject(conn);
                    assert.strictEqual(conn.http, element.http);
                    assert.strictEqual(conn.ws, element.ws);
                    assert.strictEqual(conn.ipc, element.ipc);
                    assert.isTrue(connector.connected());
                    assert.isString(connector.coinbase);
                    next();
                }
            );
            it.each(connectOptions,
                "[sync] connect with custom contracts",
                ["element"],
                function (element, next) {
                    this.timeout(TIMEOUT);
                    delete require.cache[require.resolve("../")];
                    var connector = require("../");
                    var options = element;
                    options.contracts = custom_contracts;
                    var conn = connector.connect(options);
                    assert.isObject(conn);
                    assert.strictEqual(conn.http, element.http);
                    assert.strictEqual(conn.ws, element.ws);
                    assert.strictEqual(conn.ipc, element.ipc);
                    assert.isTrue(connector.connected());
                    assert.isString(connector.coinbase);
                    assert.deepEqual(connector.contracts, custom_contracts);
                    assert.deepEqual(connector.init_contracts, custom_contracts);
                    assert.deepEqual(connector.custom_contracts, custom_contracts);
                    next();
                }
            );
            it.each(connectOptions,
                "[sync] connect with IPC support",
                ["element"],
                function (element, next) {
                    this.timeout(TIMEOUT);
                    delete require.cache[require.resolve("../")];
                    var connector = require("../");
                    var options = element;
                    options.ipc = IPCPATH;
                    var conn = connector.connect(options);
                    assert.isObject(conn);
                    assert.strictEqual(conn.http, element.http);
                    assert.strictEqual(conn.ws, element.ws);
                    assert.strictEqual(conn.ipc, element.ipc);
                    assert.isTrue(connector.connected());
                    assert.isString(connector.coinbase);
                    next();
                }
            );
            it.each(connectOptions,
                "[async] connect to",
                ["element"],
                function (element, next) {
                    this.timeout(TIMEOUT);
                    delete require.cache[require.resolve("../")];
                    var connector = require("../");
                    connector.connect(element, function (conn) {
                        assert.isObject(conn);
                        assert.strictEqual(conn.http, element.http);
                        assert.strictEqual(conn.ws, element.ws);
                        assert.strictEqual(conn.ipc, element.ipc);
                        assert.isTrue(connector.connected());
                        assert.isString(connector.coinbase);
                        next();
                    });
                }
            );
            it.each(connectOptions,
                "[async] connect to",
                ["element"],
                function (element, next) {
                    this.timeout(TIMEOUT);
                    delete require.cache[require.resolve("../")];
                    var connector = require("../");
                    connector.connect(element, function (conn) {
                        assert.isObject(conn);
                        assert.strictEqual(conn.http, element.http);
                        assert.strictEqual(conn.ws, element.ws);
                        assert.strictEqual(conn.ipc, element.ipc);
                        assert.isTrue(connector.connected());
                        assert.isString(connector.coinbase);
                        next();
                    });
                }
            );
            it.each(connectOptions,
                "[async] connect with custom contracts",
                ["element"],
                function (element, next) {
                    this.timeout(TIMEOUT);
                    delete require.cache[require.resolve("../")];
                    var connector = require("../");
                    var options = element;
                    options.contracts = custom_contracts;
                    connector.connect(options, function (conn) {
                        assert.isObject(conn);
                        assert.strictEqual(conn.http, element.http);
                        assert.strictEqual(conn.ws, element.ws);
                        assert.strictEqual(conn.ipc, element.ipc);
                        assert.isTrue(connector.connected());
                        assert.isString(connector.coinbase);
                        assert.deepEqual(connector.contracts, custom_contracts);
                        assert.deepEqual(connector.init_contracts, custom_contracts);
                        assert.deepEqual(connector.custom_contracts, custom_contracts);
                        next();
                    });
                }
            );
            it.each(connectOptions,
                "[async] connect with IPC support",
                ["element"],
                function (element, next) {
                    this.timeout(TIMEOUT);
                    delete require.cache[require.resolve("../")];
                    var connector = require("../");
                    var options = element;
                    options.ipc = IPCPATH;
                    connector.connect(options, function (conn) {
                        assert.isObject(conn);
                        assert.strictEqual(conn.http, element.http);
                        assert.strictEqual(conn.ws, element.ws);
                        assert.strictEqual(conn.ipc, element.ipc);
                        assert.isTrue(connector.connected());
                        assert.isString(connector.coinbase);
                        next();
                    });
                }
            );
        });

        it("[sync] unlocked", function () {
            this.timeout(TIMEOUT);
            delete require.cache[require.resolve("../")];
            var connector = require("../");
            var conn = connector.connect({http: "http://localhost:8545"});
            assert.isNotNull(connector.rpc.nodes.local);
            assert.isTrue(connector.rpc.unlocked(connector.coinbase));
        });
        it("[async] unlocked", function (done) {
            this.timeout(TIMEOUT);
            delete require.cache[require.resolve("../")];
            var connector = require("../");
            connector.connect({http: "http://localhost:8545"}, function (conn) {
                connector.rpc.unlocked(connector.coinbase, function (unlocked) {
                    assert.isNotNull(connector.rpc.nodes.local);
                    assert.isTrue(unlocked);
                    done();
                });
            });
        });
    }

    it("[sync] unlocked", function () {
        this.timeout(TIMEOUT);
        delete require.cache[require.resolve("../")];
        var connector = require("../");
        var conn = connector.connect({http: "https://eth3.augur.net"});
        assert.isNotNull(connector.rpc.nodes.local);
        assert.isFalse(connector.rpc.unlocked(connector.coinbase));
    });
    it("[async] unlocked", function (done) {
        this.timeout(TIMEOUT);
        delete require.cache[require.resolve("../")];
        var connector = require("../");
        connector.connect({http: "https://eth3.augur.net"}, function (conn) {
            connector.rpc.unlocked(connector.coinbase, function (unlocked) {
                assert.isNotNull(connector.rpc.nodes.local);
                assert.isFalse(unlocked);
                done();
            });
        });
    });

    it("network_id = 0, 1, 2, 7, or 10101", function () {
        delete require.cache[require.resolve("../")];
        var connector = require("../");
        connector.connect();
        assert.include(["0", "1", "2", "7", "10101"], connector.network_id);
    });

});
<|endoftext|>


<commit_before>function GameBoyAdvanceKeypad() {
	this.KEYCODE_LEFT = 37;
	this.KEYCODE_UP = 38;
	this.KEYCODE_RIGHT = 39;
	this.KEYCODE_DOWN = 40;
	this.KEYCODE_START = 13;
	this.KEYCODE_SELECT = 8;
	this.KEYCODE_A = 90;
	this.KEYCODE_B = 88;
	this.KEYCODE_L = 65;
	this.KEYCODE_R = 83;

	this.A = 0;
	this.B = 1;
	this.SELECT = 2;
	this.START = 3;
	this.RIGHT = 4;
	this.LEFT = 5;
	this.UP = 6;
	this.DOWN = 7;
	this.R = 8;
	this.L = 9;

	this.currentDown = 0x03FF;

	var self = this;
	this.keyboardHandler = function(e) {
		var toggle = 0;
		switch (e.keyCode) {
		case this.KEYCODE_START:
			toggle = this.START;
			break;
		case this.KEYCODE_SELECT:
			toggle = this.SELECT;
			break;
		case this.KEYCODE_A:
			toggle = this.A;
			break;
		case this.KEYCODE_B:
			toggle = this.B;
			break;
		case this.KEYCODE_L:
			toggle = this.L;
			break;
		case this.KEYCODE_R:
			toggle = this.R;
			break;
		case this.KEYCODE_UP:
			toggle = this.UP;
			break;
		case this.KEYCODE_RIGHT:
			toggle = this.RIGHT;
			break;
		case this.KEYCODE_DOWN:
			toggle = this.DOWN;
			break;
		case this.KEYCODE_LEFT:
			toggle = this.LEFT;
			break;
		default:
			return;
		}

		toggle = 1 << toggle;
		if (e.type == "keydown") {
			this.currentDown &= ~toggle;
		} else {
			this.currentDown |= toggle;
		}
	};
};

GameBoyAdvanceKeypad.prototype.registerKeyboardHandlers = function() {
	window.addEventListener("keydown", this.keyboardHandler.bind(this), true);
	window.addEventListener("keyup", this.keyboardHandler.bind(this), true);
};
<commit_msg>Remap select<commit_after>function GameBoyAdvanceKeypad() {
	this.KEYCODE_LEFT = 37;
	this.KEYCODE_UP = 38;
	this.KEYCODE_RIGHT = 39;
	this.KEYCODE_DOWN = 40;
	this.KEYCODE_START = 13;
	this.KEYCODE_SELECT = 92;
	this.KEYCODE_A = 90;
	this.KEYCODE_B = 88;
	this.KEYCODE_L = 65;
	this.KEYCODE_R = 83;

	this.A = 0;
	this.B = 1;
	this.SELECT = 2;
	this.START = 3;
	this.RIGHT = 4;
	this.LEFT = 5;
	this.UP = 6;
	this.DOWN = 7;
	this.R = 8;
	this.L = 9;

	this.currentDown = 0x03FF;

	var self = this;
	this.keyboardHandler = function(e) {
		var toggle = 0;
		switch (e.keyCode) {
		case this.KEYCODE_START:
			toggle = this.START;
			break;
		case this.KEYCODE_SELECT:
			toggle = this.SELECT;
			break;
		case this.KEYCODE_A:
			toggle = this.A;
			break;
		case this.KEYCODE_B:
			toggle = this.B;
			break;
		case this.KEYCODE_L:
			toggle = this.L;
			break;
		case this.KEYCODE_R:
			toggle = this.R;
			break;
		case this.KEYCODE_UP:
			toggle = this.UP;
			break;
		case this.KEYCODE_RIGHT:
			toggle = this.RIGHT;
			break;
		case this.KEYCODE_DOWN:
			toggle = this.DOWN;
			break;
		case this.KEYCODE_LEFT:
			toggle = this.LEFT;
			break;
		default:
			return;
		}

		toggle = 1 << toggle;
		if (e.type == "keydown") {
			this.currentDown &= ~toggle;
		} else {
			this.currentDown |= toggle;
		}
	};
};

GameBoyAdvanceKeypad.prototype.registerKeyboardHandlers = function() {
	window.addEventListener("keydown", this.keyboardHandler.bind(this), true);
	window.addEventListener("keyup", this.keyboardHandler.bind(this), true);
};
<|endoftext|>


<commit_before>import test from 'ava';
import fs from 'fs';
import rssFinder from '../';
import {createServer} from './_server';

let s;

test.before('setup', async t => {
    s = await createServer();

    function event(file, contentType) {
        return (req, res) => {
            const data = fs.readFileSync(file);
            res.statusCode = 200;
            res.setHeader('Content-Type', contentType);
            res.write(data);
            res.end();
        }
    }

    s.on('/html', event('./data/index.html', 'text/html'));
    s.on('/html/', event('./data/index.html', 'text/html'));
    s.on('/rss', event('./data/rss.xml', 'text/xml'));
    s.on('/nofavicon', event('./data/nofavicon.html', 'text/html'));
    s.on('/nourl', event('./data/nourl.xml', 'text/xml'));

    s.on('/favicon.ico', (req, res) => {
        res.statusCode = 500;
        res.end();
    });

    s.on('/fail', event('./data/fail.xml', 'text/xml'));

    await s.listen(s.port);
});

test('check response', async t => {
    const res1 = await rssFinder(`${s.url}/html`);
    const res2 = await rssFinder(`${s.url}/html/`);
    const res3 = await rssFinder(`${s.url}/rss`);
    const res4 = await rssFinder(`${s.url}/nofavicon`);
    const res5 = await rssFinder(`${s.url}/nourl`);

    function testResponse(res) {
        t.is(res.site.title, 'RSSFinder');
        t.is(res.site.favicon, `${s.url}/favicon.ico`);
        t.is(res.site.url, `${s.url}/html`);
        t.is(res.feedUrls[0].title, 'RSS');
        t.is(res.feedUrls[0].url, `${s.url}/rssfinder.xml`);
    }

    testResponse(res1);
    testResponse(res2);

    t.is(res3.site.title, 'NYT > Home Page');
    t.is(res3.site.favicon, 'http://www.nytimes.com/favicon.ico');
    t.is(res3.site.url, 'http://www.nytimes.com/pages/index.html?partner=rss&emc=rss');
    t.is(res3.feedUrls[0].title, 'NYT > Home Page');
    t.is(res3.feedUrls[0].url, 'http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml');

    t.is(res4.site.title, 'RSSFinder');
    t.is(res4.site.favicon, null);
    t.is(res4.site.url, `${s.url}/nofavicon`);
    t.is(res4.feedUrls[0].title, 'RSS');
    t.is(res4.feedUrls[0].url, `${s.url}/rssfinder.xml`);

    t.is(res5.site.title, 'Index - 24óra');
    t.is(res5.site.favicon, 'http://index.hu/favicon.ico');
    t.is(res5.site.url, 'http://index.hu/24ora/');
    t.is(res5.feedUrls[0].title, 'Index - 24óra');
    t.is(res5.feedUrls[0].url, `${s.url}/nourl`);
});

test('fail xml', async t => {
    try {
        await rssFinder(`${s.url}/fail`);
        t.fail('Exception was not thrown');
    } catch (err) {
        t.is(err.message, 'Not a feed');
    }
});

test('not http url is provided', async t => {
    try {
        await rssFinder('');
        t.fail('Exception was not thrown');
    } catch (err) {
        t.is(err.message, 'Not HTTP URL is provided.');
    }
});

test('parameter `opts` must be a string or object', async t => {
    try {
        await rssFinder([]);
        t.fail('Exception was not thrown');
    } catch (err) {
        t.is(err.message, 'Parameter `opts` must be a string or object.');
    }
});

test('catch errors', async t => {
    try {
        await rssFinder({
            url: 'http://url.noexists',
            gotOptions: {
                retries: 0
            }
        });
        t.fail('Exception was not thrown');
    } catch (err) {
        t.regex(err.message, /getaddrinfo ENOTFOUND/);
    }
});

test.after('cleanup', async t => {
    await s.close();
});
<commit_msg>fix test<commit_after>import test from 'ava';
import fs from 'fs';
import rssFinder from '../';
import {createServer} from './_server';

let s;

test.before('setup', async t => {
    s = await createServer();

    function event(file, contentType) {
        return (req, res) => {
            const data = fs.readFileSync(`${__dirname}/${file}`);
            res.statusCode = 200;
            res.setHeader('Content-Type', contentType);
            res.write(data);
            res.end();
        }
    }

    s.on('/html', event('data/index.html', 'text/html'));
    s.on('/html/', event('data/index.html', 'text/html'));
    s.on('/rss', event('data/rss.xml', 'text/xml'));
    s.on('/nofavicon', event('data/nofavicon.html', 'text/html'));
    s.on('/nourl', event('data/nourl.xml', 'text/xml'));

    s.on('/favicon.ico', (req, res) => {
        res.statusCode = 500;
        res.end();
    });

    s.on('/fail', event('./data/fail.xml', 'text/xml'));

    await s.listen(s.port);
});

test('check response', async t => {
    const res1 = await rssFinder(`${s.url}/html`);
    const res2 = await rssFinder(`${s.url}/html/`);
    const res3 = await rssFinder(`${s.url}/rss`);
    const res4 = await rssFinder(`${s.url}/nofavicon`);
    const res5 = await rssFinder(`${s.url}/nourl`);

    function testResponse(res) {
        t.is(res.site.title, 'RSSFinder');
        t.is(res.site.favicon, `${s.url}/favicon.ico`);
        t.is(res.site.url, `${s.url}/html`);
        t.is(res.feedUrls[0].title, 'RSS');
        t.is(res.feedUrls[0].url, `${s.url}/rssfinder.xml`);
    }

    testResponse(res1);
    testResponse(res2);

    t.is(res3.site.title, 'NYT > Home Page');
    t.is(res3.site.favicon, 'http://www.nytimes.com/favicon.ico');
    t.is(res3.site.url, 'http://www.nytimes.com/pages/index.html?partner=rss&emc=rss');
    t.is(res3.feedUrls[0].title, 'NYT > Home Page');
    t.is(res3.feedUrls[0].url, 'http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml');

    t.is(res4.site.title, 'RSSFinder');
    t.is(res4.site.favicon, null);
    t.is(res4.site.url, `${s.url}/nofavicon`);
    t.is(res4.feedUrls[0].title, 'RSS');
    t.is(res4.feedUrls[0].url, `${s.url}/rssfinder.xml`);

    t.is(res5.site.title, 'Index - 24óra');
    t.is(res5.site.favicon, 'http://index.hu/favicon.ico');
    t.is(res5.site.url, 'http://index.hu/24ora/');
    t.is(res5.feedUrls[0].title, 'Index - 24óra');
    t.is(res5.feedUrls[0].url, `${s.url}/nourl`);
});

test('fail xml', async t => {
    try {
        await rssFinder(`${s.url}/fail`);
        t.fail('Exception was not thrown');
    } catch (err) {
        t.is(err.message, 'Not a feed');
    }
});

test('not http url is provided', async t => {
    try {
        await rssFinder('');
        t.fail('Exception was not thrown');
    } catch (err) {
        t.is(err.message, 'Not HTTP URL is provided.');
    }
});

test('parameter `opts` must be a string or object', async t => {
    try {
        await rssFinder([]);
        t.fail('Exception was not thrown');
    } catch (err) {
        t.is(err.message, 'Parameter `opts` must be a string or object.');
    }
});

test('catch errors', async t => {
    try {
        await rssFinder({
            url: 'http://url.noexists',
            gotOptions: {
                retries: 0
            }
        });
        t.fail('Exception was not thrown');
    } catch (err) {
        t.regex(err.message, /getaddrinfo ENOTFOUND/);
    }
});

test.after('cleanup', async t => {
    await s.close();
});
<|endoftext|>


<commit_before>var chai = require('chai');
var chaihttp = require('chai-http');
chai.use(chaihttp);
var expect = chai.expect;

process.env.MONGOLAB_URI = "mongodb://localhost/productdb";
require(__dirname + '/../index'); // Starts server for testing
var mongoose = require('mongoose');
var productModel = require(__dirname + '/../models/productModel');

/*describe('client router', function() {
  it('should be able to view vendor lists', function() {

  });

  it('should be able to make a new list', function() {

  });

  it('should be able to add a selected vendor item to a list', function() {

  });

  it('should be able to remove a vendor item from a list', function() {

  });

  it('should get a list of products on a get request', function() {

    });

  it('should be able to search for a specific product', function() {

  });
});*/

describe('vendor router', function() {
   after(function(done) {
    mongoose.connection.db.dropDatabase(function() {
      done();
    });
  });

  it('should be able to add a product', function(done) {
    var productData = {name: 'test product'};
    chai.request('localhost:3000')
      .post('/api/product')
      .send(productData)
      .end(function(err, res) {
        expect(err).to.eql(null);
        expect(res.body.name).to.eql('test product');
        expect(res.body).to.have.property('_id');
      });
  });

/*  it('should be able to update a product', function() {

  });

  it('should be able to remove a product', function() {

  });*/
});
<commit_msg>first draft test vendor route CRUD<commit_after>var chai = require('chai');
var chaihttp = require('chai-http');
chai.use(chaihttp);
var expect = chai.expect;

process.env.MONGOLAB_URI = "mongodb://localhost/productdb";
require(__dirname + '/../index'); // Starts server for testing
var mongoose = require('mongoose');
var productModel = require(__dirname + '/../models/productModel');

/*describe('client router', function() {
  it('should be able to view vendor lists', function() {

  });

  it('should be able to make a new list', function() {

  });

  it('should be able to add a selected vendor item to a list', function() {

  });

  it('should be able to remove a vendor item from a list', function() {

  });

  it('should get a list of products on a get request', function() {

    });

  it('should be able to search for a specific product', function() {

  });
});*/

describe('vendor router', function() {
   after(function(done) {
    mongoose.connection.db.dropDatabase(function() {
      done();
    });
  });

  it('should be able to add a product', function(done) {
    var productData = {name: 'test product'};
    chai.request('localhost:3000')
      .post('/vendor/product')
      .send(productData)
      .end(function(err, res) {
        expect(err).to.eql(null);
        expect(res.body.name).to.eql('test product');
        expect(res.body).to.have.property('_id');
        done();
      });
  });

  describe('tests which require a product in db', function() {
    beforeEach(function(done) {
      (new Product({name: 'test product'})).save(function(err, data) {
        expect(err).to.eql(null);
        this.product = data;
        done();
      }.bind(this));
    });

    it('should be able to update a product', function() {
      chai.request('localhost:3000')
        .patch('/vendor/product' + this.product._id)
        .send({name: 'a different product name'})
        .end(function(err, res) {
          expect(err).to.eql(null);
          expect(res.body.msg).to.eql('success!');
          done();
        })
    });

    it('should be able to remove a product', function() {
      chai.request('localhost:3000')
        .delete('vendor/product' + this.product._id)
        .end(function(err, res) {
          expect(err).to.eql(null);
          expect(res.body.msg).to.eql('success!');
          done();
        });
    });
  });
});
<|endoftext|>