def stats():
    try:
        logging.info("stats route::enter")
        main_obj = Main()
        file_handle = open(session['filename'], encoding="utf8", mode="r")
        main_obj.file_contents = file_handle.read()
        friend1 = Friend()
        friend2 = Friend()
        date_object = Dates()
        main_obj.prepare_stats(friend1, friend2, date_object)

        @after_this_request
        def remove_file(response):
            try:
                logging.debug("remove_file::enter")
                file_handle.close()
                os.remove(session['filename'])
                logging.debug("remove_file::exit")
            except Exception as error:
                app.logger.error(
                    "Error removing or closing downloaded file handle", error)
            return response

        logging.info("stats route::exit")
        return render_template("stats.html",
                               main_obj=main_obj,
                               friend1=friend1,
                               friend2=friend2,
                               date_object=date_object)
    except Exception as e:
        logging.exception("Exception in stats route handler")
Example #2
0
class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.main = Main(self, bg="#c6c6c6")

        self.main.pack(side="top", fill="both", expand=True)
Example #3
0
def test_addIngredient_weightIngredient_to_burger():
    main = Main('wrap')
    lettuce = WeightIngredient(1, 'lettuce', 'm', 2000, 50, 100, 150, .50, 1, 1.5)
    main.addIngredient(lettuce, 1, 's')
    assert main.ingredients[0][0] == lettuce  
    assert main.ingredients[0][1] == 1
    assert main.ingredients[0][2] == 's'
    assert main.price == 4
Example #4
0
def test_remIngredient_incorrect_input_no_ings_in_order():
    sys = System()
    wrap = Main('wrap')
    sys.addQuantityIngredient('beef patty', 'm', 50, 1.50)
    ing1 = sys.ingredients[0]

    with pytest.raises(UserError) as error:
        wrap.remIngredient(ing1, 1, None)
    assert "You don't have any ingredients in your main to remove." in str(error.value)
Example #5
0
def main(event, context):
    print(str(event))
    #    if str(event['report']).lower() == "true":
    if event['report']:
        pu = PercentUnscannedReport()
        pu.report()
    else:
        main = Main()
        main.run()
Example #6
0
def test_add_patty_to_burger_within_range():
    main=Main('burger')
    patty=QuantityIngredient(1, 'patty', 'm', 25, 5)
    main.addIngredient(patty, 3, None)
    assert main.ingredients[0][0] == patty
    assert main.ingredients[0][1] == 3
    assert main.price == 18 
    assert main.nBun == 0
    assert main.nPatty == 3
    assert main.type == 'burger'
Example #7
0
def test_addIngredient_tomato_to_burger_enough_stock():
    main = Main('burger')
    tomato = QuantityIngredient(1, 'tomato', 'm', 20, 1)
    main.addIngredient(tomato, 5, None)
    assert main.ingredients[0][0] == tomato  
    assert main.ingredients[0][1] == 5
    assert main.price == 8
    assert main.nBun == 0
    assert main.nPatty == 0
    assert main.type == 'burger'
Example #8
0
def test_add_bun_to_burger_within_range():
    main = Main('burger')
    bun = QuantityIngredient(1, 'bun', 'm', 10, 1.5)
    main.addIngredient(bun, 3, None)
    assert main.ingredients[0][0] == bun 
    assert main.ingredients[0][1] == 3
    assert main.price == 7.5 
    assert main.nBun == 3
    assert main.nPatty == 0
    assert main.type == 'burger'
Example #9
0
 def add_main(self, type):
     if type == 'burger':
         main = Main('burger')
         self._mains.append(main)
         return main
     elif type == 'wrap':
         main = Main('wrap')
         self._mains.append(main)
         return main
     else:
         raise DevError('type should be either "burger" or "wrap"')
class TestHTTPIErequest(unittest.TestCase):
    def setUp(self):
        self.temp = Main()

    def test_received(self):
        with patch.object(requests, 'get') as get_mock:
            get_mock.return_value.status_code = 200
            get_mock.return_value.text = "Allu"
            assert self.temp.Make_request() == "Allu" and type(
                self.temp.Make_request()) == str

    def test_not_received(self):
        with patch.object(requests, 'get') as get_mock:
            get_mock.return_value.status_code.return_value = 404
            assert self.temp.Make_request() == "Goodbye"
Example #11
0
def test_del_main_incorrect_input():
    order = Order(1)
    order.add_main('burger')
    wrong_main = Main('wrap')
    with pytest.raises(DevError) as e:
        order.del_main(wrong_main)
    assert "main that you're trying to delete doesn't exist in this order" in str(e.value)
Example #12
0
def test_cancel(os):
    # ===== CREATING 3 ORDERS =====

    order1 = Order()
    m = Main("burger", b_ingres)
    order1.add_main(m)
    os.add_order(order1)

    order2 = Order()
    order2.add_main(m)
    os.add_order(order2)

    order3 = Order()
    order3.add_main(m)
    os.add_order(order3)

    # ==== CANCELLING 3 ORDERS ====
    os.cancel_order(order1._order_id)
    assert len(os._orders) == 2
    assert len(os._completed_orders) == 0
    os.cancel_order(order3._order_id)
    assert len(os._orders) == 1
    assert len(os._completed_orders) == 0
    os.cancel_order(order2._order_id)
    assert len(os._orders) == 0
    assert len(os._completed_orders) == 0
Example #13
0
def test_completed(os):

    # ===== CREATING 3 ORDERS =====

    order1 = Order()
    m = Main("burger", b_ingres)
    order1.add_main(m)
    os.add_order(order1)

    order2 = Order()
    order2.add_main(m)
    os.add_order(order2)

    order3 = Order()
    order3.add_main(m)
    os.add_order(order3)

    assert len(os._orders) == 3

    # ===== COMPLETING ORDERS =====
    os.complete_order(order1._order_id)
    assert len(os._orders) == 2
    assert len(os._completed_orders) == 1
    os.complete_order(order3._order_id)
    assert len(os._orders) == 1
    assert len(os._completed_orders) == 2
    os.complete_order(order2._order_id)
    assert len(os._orders) == 0
    assert len(os._completed_orders) == 3
Example #14
0
def test_order_status(os):
    # ===== CREATING 3 ORDERS =====

    order1 = Order()
    m = Main("burger", b_ingres)
    order1.add_main(m)
    os.add_order(order1)

    order2 = Order()
    order2.add_main(m)
    os.add_order(order2)

    order3 = Order()
    order3.add_main(m)
    os.add_order(order3)

    # ===== COMPLETING ORDERS =====
    assert order3._completed == False
    os.complete_order(order1._order_id)
    assert len(os._orders) == 2
    assert len(os._completed_orders) == 1
    assert order1._completed == True

    assert order3._completed == False
    os.complete_order(order3._order_id)
    assert len(os._orders) == 1
    assert len(os._completed_orders) == 2
    assert order3._completed == True

    assert order2._completed == False
    os.complete_order(order2._order_id)
    assert len(os._orders) == 0
    assert len(os._completed_orders) == 3
    assert order2._completed == True
    def main(choice):
        try:
            assert LooseVersion(tf.__version__) in [LooseVersion('1.0.0'), LooseVersion(
                '1.0.1')], 'This project requires TensorFlow version 1.0  You are using {}' \
                .format(tf.__version__)
            print('TensorFlow Version: {}'.format(tf.__version__))
            print('*****Author: Satyaki Sanyal*****')
            print('***This project must only be used for educational purpose***')
            if choice == 1:
                if not tf.test.gpu_device_name():
                    print('*** ERROR: No GPU found. Please use a GPU to train your neural network. ***')
                else:
                    print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
                    Main().main()

            elif choice == 2:
                Translate().translate()

            elif choice == 3:
                Plot().plot()

            else:
                print('*** Error: Wrong choice ***')
        except Exception as exc:
            print('*** Error: ' + str(exc) + ' ***')
Example #16
0
def test_invalid_order_main(os):
    # ===== ORDERS A BURGER WITH TOO MANY BUNS =====
    b_ingres = []
    x1 = Ingredient("sesame", "bun", "sesame bun", 1000, 1.5)
    x2 = Ingredient("lettuce", "vegetable", 2, 0.5)
    b_ingres.append(x1)
    b_ingres.append(x2)

    order1 = Order()
    bunQ = ing_quantity("sesame", "bun")
    m1 = Main("Burger", b_ingres)
    order1.add_main(m1)

    # ===== MAKES SURE THE ERROR IS CATCHED AND THE CORRECT MESSAGE IS DISPLAYED =====
    try:
        os.add_order(order1)
        assert False

    except Exception as err:
        assert str(err) == "Not enough ingredients available."
        assert True

    # ===== MAKE SURE INVENTORY WASN'T UPDATED =====
    assert ing_quantity("sesame", "bun") == bunQ
    # ASSERT NO ORDER LOGGED
    assert len(os._orders) == 0
Example #17
0
class Test_LogIn(unittest.TestCase):
    logIn = LogIn()
    main = Main()
    Customers = Customers()

    fakeUsers = ['csmi', 'aarc']

    def __init__(self, methodName: str = ...):
        __init__(methodName)
        self.ReadCSVFile = None

    def test_CustomerInfo(self):
        customerInfo = self.ReadCSVFile.getFileData("Customer/", "customer.csv")
        customerColumns = customerInfo[0]
        self.assertEqual(customerColumns, ["Customers", ])

    def test_mockSingleResult(self):
        propertyData = []
        propertyData.append("Customers")
        propertyData.append("csmi, aarc")

        self.logIn.property = []
        self.logIn.config.getConfig = MagicMock(return_value=propertyData)
        result = self.logIn.getCustomers()

        self.assertEqual(['Customers'], result)


    def test_mockEnterUserPassword(self):
        LogIn.getUserInfo = MagicMock(return_value='aarc')
        self.assertEqual('Enter password', self.logIn())
def main():
    num_epochs = 70
    batch_size = 128
    rnn_size = 256
    embed_dim = 256
    seq_length = 15
    learning_rate = 0.01
    show_every_n_batches = 10
    while True:
        try:
            ip = int(
                input(
                    'Enter 1. to train model, 2. to print scripts, 3. Exit \n>> '
                ))
            if ip == 1 or ip == 2:
                Main().assert_v(num_epochs, batch_size, rnn_size, embed_dim,
                                seq_length, learning_rate,
                                show_every_n_batches, ip)
            if ip == 3:
                print('*** Thank you ***')
                break
            else:
                print('*** Input not recognized. Try Again! ***')
        except Exception as e:
            print('***** EXCEPTION FACED: ' + str(e) + ' *****')
Example #19
0
def bootstrap_system():
    system = OrderingSystem()

    order1 = Order()

    custom_ingredients = deepcopy(g_ingredients)

    custom_ingredients = [x for x in custom_ingredients if x.i_type != "wrap"]
    for i in custom_ingredients:
        i.amount = 1

    main1 = Main("burger", custom_ingredients)
    order1.add_main(main1)

    nuggets1 = Nuggets(6)
    order1.add_side(nuggets1)

    fries1 = Fries("large")
    order1.add_side(fries1)

    drink1 = Drink("pepsi", "can", 2)
    order1.add_drink(drink1)

    system.add_order(order1)

    order2 = Order()
    order2.add_main(main1)
    order2.add_side(nuggets1)
    order2.add_side(fries1)
    order2.add_drink(drink1)

    system.add_order(order2)

    return system
class Main_ceasar_decoding_Matchers(unittest.TestCase):
    def setUp(self):
        self.temp = Main()

    def test_Ceasar_decoding_check_result_same_length__string__and__letters_same_case_but_with_space(
            self):
        argument = 'MMMii doah'
        assert_that(
            self.temp.Ceasar_coding(argument)
        ).check_result_same_length__string__and__letters_same_case(argument)

    def test_Ceasar_decoding_check_result_same_length__string__and__letters_same_case(
            self):
        argument = 'ConnORmCgregor'
        assert_that(
            self.temp.Ceasar_coding(argument)
        ).check_result_same_length__string__and__letters_same_case(argument)
class Main_ceasar_coding_Matchers(unittest.TestCase):
    def setUp(self):
        self.temp = Main()

    def test_Ceasar_coding_check_result_same_length__string__and__letters_same_case(
            self):
        argument = 'wiKtOOOr'
        assert_that(
            self.temp.Ceasar_coding(argument)
        ).check_result_same_length__string__and__letters_same_case(argument)

    def test_Ceasar_coding_check_result_same_length__string__and__letters_same_case_but_with_space(
            self):
        argument = 'wKK OKA'
        assert_that(
            self.temp.Ceasar_coding(argument)
        ).check_result_same_length__string__and__letters_same_case(argument)
class Main_morse_coding_Matchers(unittest.TestCase):
    def setUp(self):
        self.temp = Main()

    def test_Morse_coding_check_result_length_higher_and_string_and_contain_spaces(
            self):
        argument = 'wiktor 1'
        assert_that(
            self.temp.Morse_coding(argument)
        ).check_result_length_higher_and_string_and_contain_spaces(argument)

    def test_Morse_coding_check_result_contain_single_spaces_beetween_morse(
            self):
        argument = 'Testowanie'
        assert_that(
            self.temp.Morse_coding(argument)
        ).check_result_contain_single_spaces_beetween_morse(argument)
Example #23
0
File: app.py Project: Artie18/goto
def main(argv):
    __keyword, __path = '', ''
    try:
        opts, args = getopt.getopt(argv, 'a:p:', ['list'])
    except getopt.GetoptError:
        raise Exception('Something went wrong')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-a':
            __keyword = arg
        elif opt == '-p':
            __path = arg
        elif opt == '--list':
            Main.list()
    if '-a' in sys.argv[1:]:
        Main.add_shortcut(__keyword, __path)
        print('{0} is added with a pass {1}'.format(__keyword, __path))
def sample():
    try:
        logging.info("sample route::enter")
        main_obj = Main()
        file_handle = open('sample.txt', encoding="utf8", mode="r")
        main_obj.file_contents = file_handle.read()
        friend1 = Friend()
        friend2 = Friend()
        date_object = Dates()
        main_obj.prepare_stats(friend1, friend2, date_object)
        logging.info("sample route::exit")
        return render_template("stats.html",
                               main_obj=main_obj,
                               friend1=friend1,
                               friend2=friend2,
                               date_object=date_object)
    except Exception as e:
        logging.exception("Exception in stats route handler")
Example #25
0
File: goto.py Project: Artie18/goto
def cli(arg1, arg2):
    if len(arg2) > 1:
        keyword, path = arg2[0], arg2[1]
    else:
        keyword, path = arg2[0], ''
    if arg1 != '':
        keywordClass = Keyword(arg1)
        result = Main.execute(keywordClass, keyword, path)
        if result != True:
            sys.stdout.write(result)
Example #26
0
def test_make_full_order(os):
    # ===== MAKE A LIST OF INGREDIENTS AND MAKE A MAIN =====
    w_ingres = []
    x1 = Ingredient("plain", "wrap", "plain wrap", 1, 2)

    x2 = Ingredient("lettuce", "vegetable", "lettuce", 2, 0.5)

    x3 = Ingredient("tomato", "vegetable", "tomato", 2, 1)

    x4 = Ingredient("cheddar", "cheese", "cheddar cheese", 4, 1)

    for x in [x1, x2, x3, x4]:
        w_ingres.append(x)

    m1 = Main("wrap", w_ingres)

    # ===== STORE INVENTORY LEVELS =====
    wrapQ = ing_quantity("plain", "wrap")
    letQ = ing_quantity("lettuce", "vegetable")
    tomQ = ing_quantity("tomato", "vegetable")
    cheQ = ing_quantity("cheddar", "cheese")
    ojQ = drink_quantity("orange juice", "")
    pepsi_q = drink_quantity("pepsi", "can")
    nuggetQ = side_quantity(Nuggets(6))
    friesQ = side_quantity(Fries(""))

    # ===== ADD MAIN, DRINK AND SIDES TO ORDER =====
    order1 = Order()
    order1.add_main(m1)
    order1.add_drink(Drink("orange juice", "small", 250))
    order1.add_drink(Drink("pepsi", "can", 2))
    order1.add_side(Fries("large"))
    order1.add_side(Nuggets(6))

    # ===== ADD ORDER TO ORDERING SYSTEM =====
    assert os.add_order(order1) == True
    # ===== ASSERT ORDER WAS LOGGED =====
    assert len(os._orders) == 1
    # ===== CHECK PRICE =====
    assert order1.calculate_price() == 21
    # ===== MAKE SURE CORRECT NUMBER OF ITEMS HAVE BEEN PUT INTO THE ORDER =====
    assert len(order1.mains) == 1
    assert len(order1.sides) == 2
    assert len(order1.drinks) == 2
    assert len(order1.mains[0]._ingredients) == 4

    # ===== MAKE SURE INVENTORY LEVELS WERE UPDATED CORRECTLY =====
    assert ing_quantity("plain", "wrap") == wrapQ - 1
    assert ing_quantity("lettuce", "vegetable") == letQ - 2
    assert ing_quantity("tomato", "vegetable") == tomQ - 2
    assert ing_quantity("cheddar", "cheese") == cheQ - 4
    assert side_quantity(Nuggets(6)) == nuggetQ - 6
    assert side_quantity(Fries("")) == friesQ - 640
    assert drink_quantity("orange juice", "") == ojQ - 250
    assert drink_quantity("pepsi", "can") == pepsi_q - 2
Example #27
0
def test_check_burger_invalid():
    main = Main('burger')
    bun = QuantityIngredient(1, 'bun','m', 10, 1.5)
    main.addIngredient(bun, 1, None)
    with pytest.raises(UserError) as err:
        main.checkBurger()
    assert  "You must finish your burger before moving on. It needs at least 2 buns to be finished." in str(err.value)
Example #28
0
class TestAffine(unittest.TestCase):
    def setUp(self):
        self.temp = Main()

    @parameterized.expand([('VENI', 3, 12, 'XYZK'), ('cAbM', 3, 12, 'sMpW'),
                           ('iueghish', 7, 8, 'mskyfmef'),
                           ('kolokwium', 19, 16, 'ywrwysmgk')])
    def test_Affine_coding_equal_string(self, text, a, b, expected):
        self.assertEqual(self.temp.Affine_coding(text, a, b), expected)

    @parameterized.expand([('VENI VICI', 9, 123, 'ADGN ANLN'),
                           ('Na Statek Kamraci', 15, 12, 'Zm Wlmlug Gmkhmqc'),
                           ('DO wozu BRACIE', 15, 8, 'BK aktw XDIMYQ'),
                           ('kolokwium jest za dwa dni', 21, 6,
                            'iodoiasky nmup lg rag rts')])
    def test_Affine_coding_equal_string_with_space(self, text, a, b, expected):
        self.assertEqual(self.temp.Affine_coding(text, a, b), expected)

    @parameterized.expand([('dawdawdwadaw', 9, 123),
                           ('NNNNa St KOMANDORE', 15, 12), ('AKODWANI', 15, 8),
                           ('kol', 21, 6), ('    ', 19, 16)])
    def test_Affine_coding_equal_string_lengths(self, text, a, b):
        self.assertEqual(len(self.temp.Affine_coding(text, a, b)), len(text))
Example #29
0
def test_remIngredient_correct_input():
    sys = System()
    sys.addQuantityIngredient('beef patty', 'm', 50, 1.50)
    sys.addQuantityIngredient('cheese', 'm', 50, 1.00)
    sys.addQuantityIngredient('egg', 'm', 50, 1.50)
    ing1 = sys.ingredients[0]
    ing2 = sys.ingredients[1]
    ing3 = sys.ingredients[2]

    wrap = Main('wrap')
    wrap.addIngredient(ing1, 2, None)
    wrap.addIngredient(ing2, 2, None)
    wrap.addIngredient(ing3, 1, None)

    wrap.remIngredient(ing3, 1, None)
    assert len(wrap.ingredients) == 2
    assert sys.ingredients[2].stock == 50
Example #30
0
def test_cancel_main(os):
    # ===== MAKE LIST OF INGREDIENTS =====
    b_ingres = []
    x1 = Ingredient("sesame", "bun", "sesame bun", 3, 1.5)

    x2 = Ingredient("beef", "patty", "beef patty", 2, 3.0)

    x3 = Ingredient("tomato", "vegetable", "tomato", 2, 0.5)

    x4 = Ingredient("cheddar", "cheese", "cheddar cheese", 2, 1)

    x5 = Ingredient("tomato", "sauce", "tomato sauce", 2, 0.5)

    for x in [x1, x2, x3, x4, x5]:
        b_ingres.append(x)

    # ===== STORE CURRENT INVENTORY LEVELS =====
    bunQ = ing_quantity("sesame", "bun")
    pattyQ = ing_quantity("beef", "patty")
    vegQ = ing_quantity("tomato", "vegetable")
    cheQ = ing_quantity("cheddar", "cheese")
    sauQ = ing_quantity("tomato", "sauce")
    # ===== ORDER A MAIN =====
    order1 = Order()
    m1 = Main("burger", b_ingres)
    order1.add_main(m1)
    os.add_order(order1)

    assert len(os._orders) == 1
    assert order1.calculate_price() == 14.5
    assert len(order1.mains) == 1
    assert len(order1.mains[0]._ingredients) == 5

    # ===== MAKE SURE INVENTORY UPDATED CORRECTLY =====
    assert ing_quantity("sesame", "bun") == bunQ - 3
    assert ing_quantity("beef", "patty") == pattyQ - 2
    assert ing_quantity("tomato", "vegetable") == vegQ - 2
    assert ing_quantity("cheddar", "cheese") == cheQ - 2
    assert ing_quantity("tomato", "sauce") == sauQ - 2

    os.cancel_order(order1._order_id)
    # ===== IF AN ORDER IS CANCELLED MAKE SURE THE INGREDIENTS ARE PUT BACK IN THE INVENTORY SYSTEM =====
    assert ing_quantity("sesame", "bun") == bunQ
    assert ing_quantity("beef", "patty") == pattyQ
    assert ing_quantity("tomato", "vegetable") == vegQ
    assert ing_quantity("cheddar", "cheese") == cheQ
    assert ing_quantity("tomato", "sauce") == sauQ
class Test_LogIn(unittest.TestCase):
    logIn = LogIn()
    main = Main()
    customers = Customers()

    listOfFakeNumbers = ['07946450569', '07958963214']

    def __init__(self, methodName: str = ...):
        super().__init__(methodName)
        self.readCSVFile = None

    def test_CustomerInfo(self):
        customerInfo = self.readCSVFile.getFileData("Customer/",
                                                    "customer.csv")
        customerColumns = customerInfo[0]
        self.assertEqual(customerColumns, [
            "Customers",
        ])

    def test_mockSingleResult(self):
        propertyData = []
        propertyData.append("Customers")
        propertyData.append("07946450569, 07958963214")

        self.logIn.property = []
        self.logIn.config.getConfig = MagicMock(return_value=propertyData)
        result = self.logIn.getCustomers()

        self.assertEqual(['Customers'], result)

    def test_mockEnterUserPassword(self):
        LogIn.getUserInfo = MagicMock(return_value='07946450569')
        self.assertEqual('Enter password', self.logIn.display())

    def test_getCustomerDataFromStub(self):
        self.main.setConfig(CSVStub)
        customerData = self.main.property
        customerColumns = customerData[0]
        self.assertEqual(customerColumns, "phoneNumber")

    def test_FakeList(self):
        displayFakeList = LogIn()
        fakeNumbers = Test_LogIn.listOfFakeNumbers
        displayFakeList.getCustomers = MagicMock(
            return_value=fakeNumbers.pop())
        self.assertEqual('Enter password', displayFakeList.display())
Example #32
0
 def setUp(self):
     # setting directories
     program_dir = abspath(join(realpath(__file__), pardir, pardir))
     home_dir = join(program_dir, "tests", "testdata")
     cache_dir = home_dir
     # creating the main instance
     self.app = QApplication(sys.argv)
     self.main = Main(program_dir, home_dir)
     # cache directory
     self.main._CACHEDIR = cache_dir
     self.main._preferences["cacheDir"] = cache_dir
     self.main._mystorage._cache_dir = cache_dir
     self.hdir = home_dir
     self.pdir = program_dir
     # project file names
     self.pname = join(self.hdir, "swan.txt")
     self.vname = join(self.hdir, "swan_vum.vum")
     # avoids segmentation fault
     self.app.deleteLater()
Example #33
0
def createMain(main_type):
    print("\nWhat would you like in your %s?\n" % main_type)

    custom_ingredients = deepcopy(g_ingredients)

    if (main_type == "burger"):
        custom_ingredients = [
            x for x in custom_ingredients if x.i_type != "wrap"
        ]
    else:
        custom_ingredients = [
            x for x in custom_ingredients if x.i_type != "bun"
        ]

    for x in custom_ingredients:
        x.amount = int(input("How many %s? " % x))

    m = Main(main_type, custom_ingredients)

    return m
Example #34
0
class Test(unittest.TestCase):
    """
    Test class for testing :class:`src.main.Main`.

    """

    def setUp(self):
        # setting directories
        program_dir = abspath(join(realpath(__file__), pardir, pardir))
        home_dir = join(program_dir, "tests", "testdata")
        cache_dir = home_dir
        # creating the main instance
        self.app = QApplication(sys.argv)
        self.main = Main(program_dir, home_dir)
        # cache directory
        self.main._CACHEDIR = cache_dir
        self.main._preferences["cacheDir"] = cache_dir
        self.main._mystorage._cache_dir = cache_dir
        self.hdir = home_dir
        self.pdir = program_dir
        # project file names
        self.pname = join(self.hdir, "swan.txt")
        self.vname = join(self.hdir, "swan_vum.vum")
        # avoids segmentation fault
        self.app.deleteLater()
        
    def tearDown(self):
        # removing the created files
        if exists(self.pname):
            remove(self.pname)
        if exists(self.vname):
            remove(self.vname)
    
    def test01_NewProject_CreatingSuccess(self):
        # sessions to load
        files = [join(self.hdir, "l101015-001"),
                 join(self.hdir, "l101015-002")]
        channel = self.main._mystorage.get_channel()
        proname = self.main._preferences["defaultProName"]
        # has to successfully create the project
        success = self.main._mystorage.load_project(self.hdir, proname, channel, files)
        self.assertTrue(success)
    
    def test02_NewProject_CreatingFail(self):
        # no sessions given
        files = []
        channel = self.main._mystorage.get_channel()
        proname = self.main._preferences["defaultProName"]
        # has to fail creating the project
        success = self.main._mystorage.load_project(self.hdir, proname, channel, files)
        self.assertFalse(success)

    def test04_NewProject_SaveProject(self):
        # sessions to load
        files = [join(self.hdir, "l101015-001"),
                 join(self.hdir, "l101015-002")]
        channel = self.main._mystorage.get_channel()
        proname = self.main._preferences["defaultProName"]
        # has to successfully create the project files
        self.main._mystorage.load_project(self.hdir, proname, channel, files)
        # setting up a virtual unit map
        vumap = VirtualUnitMap()
        vumap.set_initial_map([1, 1])
        self.main._mystorage.store("vum", vumap)
        # has to successfully create the project files
        self.main.save_project()
        self.assertTrue(exists(self.pname))
        self.assertTrue(exists(self.vname))

    def test20_LoadConnectorMapSuccess(self):
        filename = join(self.hdir, "test_cmap_success.csv")
        # reading the channel ids from the file
        with open(filename, "rb") as cfile:
            creader = csv.reader(cfile, delimiter=',', quotechar='"')
            channels = [row[1] for row in creader]
        # is not allowed to raise an error
        self.main.load_connector_map(filename)
        # getting the channel ids
        channels_new = [item.channel for item in self.main.selector._items]
        i = 0
        tmp = channels
        channels = []
        for k in xrange(10):
            c = tmp[i:i+10]
            i += 10
            for el in reversed(c):
                channels.insert(0, int(el))
        # channels from program must be identical to the channel ids from the file
        self.assertListEqual(channels, channels_new)

    def test21_LoadConnectorMapFail(self):
        filename = join(self.hdir, "test_cmap_fail.csv")
        # getting the channel ids
        channels = [item.channel for item in self.main.selector._items]
        # must raise an error because the file could not be read
        self.assertRaises(ValueError, self.main.load_connector_map, filename)
        # getting the channel ids again
        channels_new = [item.channel for item in self.main.selector._items]
        # must be identical to the channel ids before calling the function
        self.assertListEqual(channels, channels_new)

    def test99_Quit(self):
        self.main.ui.action_Quit.trigger()
Example #35
0
File: swan.py Project: INM-6/swan
Can run the application just like :mod:`src.run` but it doesn't do 
additions and checks for the *sys.path*.

Don't use this to run the application.
This is only used by *py2exe*.
"""

if __name__ == '__main__':
    import sys
    import os
    from os.path import curdir, split, abspath, expanduser, join, realpath, pardir, isfile
    
    if len(sys.argv) > 1:
        home = sys.argv[1]
    else:
        #should only work on windows and unix
        home = expanduser("~")
    
#    p = abspath(join(realpath(__file__), pardir, pardir))
    p = sys.path[0]
    p = split(p)[0]
    if not p:
        p = curdir

    from src.main import Main
    from PyQt4.QtGui import QApplication
    
    app = QApplication(sys.argv)
    m = Main(abspath(p), home)
    m.show()
    sys.exit(app.exec_())
Example #36
0
File: app.py Project: Artie18/goto
def execute(__keyword):
    Main.goto(__keyword)