示例#1
0
        public void SchedulerParentContextPreserved()
        {
            // This test was added due to a lot of paranoia around how the subcontext call stack is created.
            // It's taking the existing call stack and just shoving on change_a. The interpreter then runs
            // through everything as normal. What I expect to happen then is that after change_a finishes,
            // it attempts to run the parent context. This is a no-no! This test will show if this happens
            // based on the result of the variable 'b'. If it's greater than 1, then it got run more than
            // once.
            //
            // We use an external entity to track this because its reference is independent of different
            // contexts.
            var intHaver = new GotAnInt();

            runBasicTest(
                "import sys\n" +
                "\n" +
                "a = 0\n" +
                "def change_a():\n" +
                "   global a\n" +
                "   a = 1\n" +
                "\n" +
                "b.TheInt += 1\n" +
                "sys.scheduler.schedule(change_a)\n",
                new Dictionary <string, object>()
            {
                { "b", intHaver }
            }, new VariableMultimap(new TupleList <string, object>
            {
                { "a", PyInteger.Create(1) },
            }), 2);

            Assert.That(intHaver.TheInt, Is.EqualTo(1));
        }
示例#2
0
 public void ComprehensiveArithmeticOperators()
 {
     runBasicTest(
         "x = 10\n" +
         "a = x + 2\n" +
         "b = x - 2\n" +
         "c = x * 2\n" +
         "d = x / 2\n" +
         "e = x % 9\n" +
         "f = x // 3\n" +
         "g = x ** 2\n" +
         "h = x & 2\n" +
         "i = x | 14\n" +
         "j = x ^ 2\n" +
         "k = x >> 2\n" +
         "l = x << 2\n"
         , new VariableMultimap(new TupleList <string, object>
     {
         { "a", PyInteger.Create(12) },
         { "b", PyInteger.Create(8) },
         { "c", PyInteger.Create(20) },
         { "d", PyFloat.Create(5.0) },
         { "e", PyInteger.Create(1) },
         { "f", PyInteger.Create(3) },
         { "g", PyInteger.Create(100) },
         { "h", PyInteger.Create(2) },
         { "i", PyInteger.Create(14) },
         { "j", PyInteger.Create(8) },
         { "k", PyInteger.Create(2) },
         { "l", PyInteger.Create(40) }
     }), 1);
 }
示例#3
0
        public PyDataType ItemGetInfo(PyInteger itemID, CallInformation call)
        {
            int callerCharacterID = call.Client.EnsureCharacterIsSelected();

            ItemEntity item = this.ItemFactory.LoadItem(itemID);

            if (item.OwnerID != callerCharacterID && item.OwnerID != call.Client.CorporationID)
            {
                throw new TheItemIsNotYoursToTake(itemID);
            }

            return(new Row(
                       new PyList <PyString>(5)
            {
                [0] = "itemID",
                [1] = "invItem",
                [2] = "activeEffects",
                [3] = "attributes",
                [4] = "time"
            },
                       new PyList(5)
            {
                [0] = item.ID,
                [1] = item.GetEntityRow(),
                [2] = item.GetEffects(),
                [3] = item.Attributes,
                [4] = DateTime.UtcNow.ToFileTimeUtc()
            }
                       ));
        }
示例#4
0
        protected override BoundService CreateBoundInstance(PyDataType objectData, CallInformation call)
        {
            if (objectData is PyInteger == false)
            {
                throw new CustomError("Cannot bind reprocessingSvc service to unknown object");
            }

            PyInteger stationID = objectData as PyInteger;

            if (this.MachoResolveObject(stationID, 0, call) != this.BoundServiceManager.Container.NodeID)
            {
                throw new CustomError("Trying to bind an object that does not belong to us!");
            }

            Station station = this.ItemFactory.GetStaticStation(stationID);

            // check if the station has the required services
            if (station.HasService(StaticData.Inventory.Station.Service.ReprocessingPlant) == false)
            {
                throw new CustomError("This station does not allow for reprocessing plant services");
            }
            // ensure the player is in this station
            if (station.ID != call.Client.StationID)
            {
                throw new CanOnlyDoInStations();
            }

            Corporation   corporation = this.ItemFactory.GetItem <Corporation>(station.OwnerID);
            ItemInventory inventory   = this.ItemFactory.MetaInventoryManager.RegisterMetaInventoryForOwnerID(station, call.Client.EnsureCharacterIsSelected());

            return(new reprocessingSvc(this.ReprocessingDB, this.StandingDB, corporation, station, inventory, this.ItemFactory, this.BoundServiceManager, call.Client));
        }
示例#5
0
        public void IsNoneIsNotNone()
        {
            runBasicTest("b = a is None\n" +
                         "c = a is not None\n",
                         new Dictionary <string, object>
            {
                { "a", NoneType.Instance }
            },
                         new VariableMultimap(new TupleList <string, object>
            {
                { "a", NoneType.Instance },
                { "b", PyBool.True },
                { "c", PyBool.False }
            }), 1);

            // Now let's flip A around and make sure we're still cool.
            runBasicTest("b = a is None\n" +
                         "c = a is not None\n",
                         new Dictionary <string, object>
            {
                { "a", PyInteger.Create(10) }
            },
                         new VariableMultimap(new TupleList <string, object>
            {
                { "a", PyInteger.Create(10) },
                { "b", PyBool.False },
                { "c", PyBool.True }
            }), 1);
        }
示例#6
0
        public async Task DefaultCombinations()
        {
            string program =
                "def defaults_math(a=1, b=3):\n" +
                "   return a + 10 * b\n" +
                "a = defaults_math()\n" +
                "b = defaults_math(2)\n" +
                "c = defaults_math(2, 4)\n" +
                "d = defaults_math(a=2, b=4)\n" +
                "e = defaults_math(a=4, b=2)\n" +
                "f = defaults_math(a=2)\n" +
                "g = defaults_math(b=4)\n";

            await runBasicTest(program,
                               new VariableMultimap(new TupleList <string, object>
            {
                { "a", PyInteger.Create(31) },
                { "b", PyInteger.Create(32) },
                { "c", PyInteger.Create(42) },
                { "d", PyInteger.Create(42) },
                { "e", PyInteger.Create(24) },
                { "f", PyInteger.Create(32) },
                { "g", PyInteger.Create(41) },
            }), 3);                     // a=1 and b=3 are all their own iterations

            AssertNoDotNetExceptions();
        }
示例#7
0
        public PyDataType CharGetNewTransactions(PyInteger sellBuy, PyInteger typeID, PyNone clientID,
                                                 PyInteger quantity, PyNone fromDate, PyNone maxPrice, PyInteger minPrice, CallInformation call)
        {
            int callerCharacterID = call.Client.EnsureCharacterIsSelected();

            TransactionType transactionType = TransactionType.Either;

            if (sellBuy is PyInteger)
            {
                switch ((int)(sellBuy as PyInteger))
                {
                case 0:
                    transactionType = TransactionType.Sell;
                    break;

                case 1:
                    transactionType = TransactionType.Buy;
                    break;
                }
            }

            return(this.DB.CharGetNewTransactions(
                       callerCharacterID, clientID, transactionType, typeID as PyInteger, quantity, minPrice
                       ));
        }
示例#8
0
        public PyBool GrantCertificate(PyInteger certificateID, CallInformation call)
        {
            int callerCharacterID = call.Client.EnsureCharacterIsSelected();

            // TODO: WE MIGHT WANT TO CHECK AND ENSURE THAT THE CHARACTER BELONGS TO US BEFORE DOING ANYTHING ELSE HERE
            if (this.ItemManager.IsItemLoaded(callerCharacterID) == false)
            {
                throw new CustomError("This request should arrive on the node that has this character loaded, not here");
            }

            List <CertificateRelationship> requirements = this.DB.GetCertificateRequirements(certificateID);
            Character character = this.ItemManager.LoadItem(callerCharacterID) as Character;

            Dictionary <int, Skill> skills = character.InjectedSkillsByTypeID;

            foreach (CertificateRelationship relationship in requirements)
            {
                if (skills.ContainsKey(relationship.ParentTypeID) == false || skills[relationship.ParentTypeID].Level < relationship.ParentLevel)
                {
                    return(false);
                }
            }

            // if this line is reached, the character has all the requirements for this cert
            this.DB.GrantCertificate(callerCharacterID, certificateID);

            return(true);
        }
示例#9
0
 private void ExtractExtraCharacterAppearance(PyDictionary data, out PyInteger accessoryID,
                                              out PyInteger beardID, out PyInteger decoID, out PyInteger lipstickID, out PyInteger makeupID,
                                              out PyDecimal morph1e, out PyDecimal morph1n, out PyDecimal morph1s, out PyDecimal morph1w,
                                              out PyDecimal morph2e, out PyDecimal morph2n, out PyDecimal morph2s, out PyDecimal morph2w,
                                              out PyDecimal morph3e, out PyDecimal morph3n, out PyDecimal morph3s, out PyDecimal morph3w,
                                              out PyDecimal morph4e, out PyDecimal morph4n, out PyDecimal morph4s, out PyDecimal morph4w)
 {
     data.TryGetValue("accessoryID", out accessoryID);
     data.TryGetValue("beardID", out beardID);
     data.TryGetValue("decoID", out decoID);
     data.TryGetValue("lipstickID", out lipstickID);
     data.TryGetValue("makeupID", out makeupID);
     data.TryGetValue("morph1e", out morph1e);
     data.TryGetValue("morph1n", out morph1n);
     data.TryGetValue("morph1s", out morph1s);
     data.TryGetValue("morph1w", out morph1w);
     data.TryGetValue("morph2e", out morph2e);
     data.TryGetValue("morph2n", out morph2n);
     data.TryGetValue("morph2s", out morph2s);
     data.TryGetValue("morph2w", out morph2w);
     data.TryGetValue("morph3e", out morph3e);
     data.TryGetValue("morph3n", out morph3n);
     data.TryGetValue("morph3s", out morph3s);
     data.TryGetValue("morph3w", out morph3w);
     data.TryGetValue("morph4e", out morph4e);
     data.TryGetValue("morph4n", out morph4n);
     data.TryGetValue("morph4s", out morph4s);
     data.TryGetValue("morph4w", out morph4w);
 }
示例#10
0
        public PyBool CanBeKickedOut(PyInteger characterID, CallInformation call)
        {
            int callerCharacterID = call.Client.EnsureCharacterIsSelected();

            // can personel manager kick other players? are there other conditions?
            return(characterID == callerCharacterID || CorporationRole.Director.Is(call.Client.CorporationRole));
        }
示例#11
0
        public PyDataType TrashItems(PyList itemIDs, CallInformation call)
        {
            foreach (PyDataType itemID in itemIDs)
            {
                // ignore non integer values and the current
                if (itemID is PyInteger integer == false)
                {
                    continue;
                }
                PyInteger value = itemID as PyInteger;

                // do not trash the active ship
                if (value == call.Client.ShipID)
                {
                    throw new CantMoveActiveShip();
                }

                ItemEntity item = this.ItemManager.GetItem(itemID as PyInteger);
                // store it's location id
                int oldLocationID = item.LocationID;
                // remove the item off the ItemManager
                this.ItemManager.DestroyItem(item);
                // notify the client of the change
                call.Client.NotifyItemLocationChange(item, item.Flag, oldLocationID);
            }

            return(null);
        }
示例#12
0
文件: LSC.cs 项目: sn0opy/EVESharp
        public PyDataType AccessControl(PyInteger channelID, PyInteger characterID, PyInteger accessLevel, CallInformation call)
        {
            int callerCharacterID = call.Client.EnsureCharacterIsSelected();

            if (this.DB.IsCharacterOperatorOrAdminOfChannel(channelID, callerCharacterID) == false)
            {
                throw new LSCCannotAccessControl("Insufficient permissions");
            }

            this.DB.UpdatePermissionsForCharacterOnChannel(channelID, characterID, accessLevel);

            PyTuple args = new PyTuple(6)
            {
                [0] = characterID,
                [1] = accessLevel,
                [2] = new PyNone(),
                [3] = accessLevel,
                [4] = "",
                [5] = accessLevel == ChatDB.CHATROLE_CREATOR
            };

            PyDataType notification = GenerateLSCNotification("AccessControl", channelID, args, call.Client);

            // get users in the channel that are online now
            PyList characters = this.DB.GetOnlineCharsOnChannel(channelID);

            call.Client.ClusterConnection.SendNotification("OnLSC", "charid", characters, notification);

            // TODO: CHECK IF THIS IS A CHARACTER'S ADDRESS BOOK AND CHECK FOR OTHER CHARACTER'S ADDRESSBOOK STATUS
            // TODO: TO ENSURE THEY DON'T HAVE US BLOCKED

            return(null);
        }
示例#13
0
文件: LSC.cs 项目: sn0opy/EVESharp
        public PyDataType DestroyChannel(PyInteger channelID, CallInformation call)
        {
            int callerCharacterID = call.Client.EnsureCharacterIsSelected();

            // ensure the character has enough permissions
            if (this.DB.IsCharacterAdminOfChannel(channelID, callerCharacterID) == false)
            {
                throw new LSCCannotDestroy("Insufficient permissions");
            }

            // get users in the channel that are online now
            PyList characters = this.DB.GetOnlineCharsOnChannel(channelID);

            // remove channel off the database
            this.DB.DestroyChannel(channelID);

            // notify everyone in the channel only when it should
            PyDataType notification =
                GenerateLSCNotification("DestroyChannel", channelID, new PyTuple(0), call.Client);

            // notify all characters in the channel
            call.Client.ClusterConnection.SendNotification("OnLSC", "charid", characters, notification);

            return(null);
        }
示例#14
0
文件: LSC.cs 项目: sn0opy/EVESharp
        public PyDataType LeaveChannels(PyList channels, PyDataType boolUnsubscribe, PyInteger role, CallInformation call)
        {
            foreach (PyDataType channelInfo in channels)
            {
                if (channelInfo is PyTuple == false)
                {
                    Log.Error("LSC received a channel identifier in LeaveChannels that doesn't resemble anything we know");
                    continue;
                }

                PyTuple tuple = channelInfo as PyTuple;

                if (tuple.Count != 2)
                {
                    Log.Error(
                        "LSC received a tuple for channel in LeaveChannels that doesn't resemble anything we know");
                    return(null);
                }

                PyDataType channelID = tuple[0];
                PyBool     announce  = tuple[1] as PyBool;

                this.LeaveChannel(channelID, announce, call);
            }

            return(null);
        }
示例#15
0
 // This is the actual payload.
 public async Task <object> wrappedMethodBody(IInterpreter interpreter)
 {
     // We're just having it wait off one tick as a pause since we don't actually have something on the
     // other end of this that will block.
     await new YieldTick(((Interpreter)interpreter).Scheduler, context);
     return(PyInteger.Create(1));                // TODO: Helpers to box/unbox between .NET and Python types.
 }
示例#16
0
        public PyDataType DestroyFitting(PyInteger itemID, CallInformation call)
        {
            ItemEntity item = this.mInventory.Items[itemID];

            if (item.IsInRigSlot() == false)
            {
                throw new CannotDestroyFittedItem();
            }

            if (item is ShipModule module)
            {
                // disable passive effects
                module.StopApplyingPassiveEffects(Client);
            }

            int   oldLocationID = item.LocationID;
            Flags oldFlag       = item.Flag;

            // destroy the rig
            this.ItemFactory.DestroyItem(item);

            // notify the client about the change
            call.Client.NotifyMultiEvent(OnItemChange.BuildLocationChange(item, oldFlag, oldLocationID));

            return(null);
        }
示例#17
0
        public async Task DefaultsVargsArgsKwargs()
        {
            string program =
                "def mad1(initial, addon=0, *numbers, **kwargs):\n" +
                "   ret_sum = initial\n" +
                "   for number in numbers:\n" +
                "      ret_sum += kwargs['mult1'] * number + addon\n" +
                "   return ret_sum\n" +
                "\n" +
                "def mad2(initial, *numbers, addon=0, **kwargs):\n" +
                "   ret_sum = initial\n" +
                "   for number in numbers:\n" +
                "      ret_sum += kwargs['mult2'] * number + addon\n" +
                "   return ret_sum\n" +
                "\n" +
                "kwarg = { 'mult1': 10, 'mult2': 100 }\n" +
                "a = mad1(1, 7, 11, kwarg)\n" +
                "b = mad1(1, addon=6, 11, kwarg)\n" +
                "c = mad1(1, addon=1, 11, 12, kwarg)\n" +
                "d = mad2(1, 7, 11, kwarg)\n" +
                "e = mad2(1, 11, addon=6, kwarg)\n" +
                "f = mad2(1, 11, 12, addon=1, kwarg)\n";

            await runBasicTest(program,
                               new VariableMultimap(new TupleList <string, object>
            {
                // These values have not been properly established yet since we're not even sure what are legal calls and what they do yet.
                { "a", PyInteger.Create(19) },
                { "b", PyInteger.Create(19) },
                { "c", PyInteger.Create(19) },
                { "d", PyInteger.Create(19) },
                { "e", PyInteger.Create(19) },
                { "f", PyInteger.Create(19) }
            }), 1);
        }
示例#18
0
        public PyDataType SetCloneTypeID(PyInteger cloneTypeID, CallInformation call)
        {
            int callerCharacterID = call.Client.EnsureCharacterIsSelected();
            int stationID         = call.Client.EnsureCharacterIsInStation();

            Character character    = this.ItemFactory.GetItem <Character>(callerCharacterID);
            Type      newCloneType = this.TypeManager[cloneTypeID];

            if (newCloneType.Group.ID != (int)Groups.Clone)
            {
                throw new CustomError("Only clone types allowed!");
            }
            if (character.ActiveClone.Type.BasePrice > newCloneType.BasePrice)
            {
                throw new MedicalThisCloneIsWorse();
            }

            Station station = this.ItemFactory.GetStaticStation(stationID);

            using Wallet wallet = this.WalletManager.AcquireWallet(character.ID, 1000);
            {
                wallet.EnsureEnoughBalance(newCloneType.BasePrice);
                wallet.CreateTransactionRecord(TransactionType.Buy, this.ItemFactory.LocationSystem.ID, newCloneType.ID, 1, newCloneType.BasePrice, station.ID);
            }

            // update active clone's information
            character.ActiveClone.Type = newCloneType;
            character.ActiveClone.Name = newCloneType.Name;
            character.ActiveClone.Persist();
            character.Persist();

            return(null);
        }
示例#19
0
        public void NotifyByCharacterID(PyPacket packet, PyAddressBroadcast destination)
        {
            lock (this.Clients)
            {
                PyList idlist = destination.IDsOfInterest;

                foreach (PyDataType idData in idlist)
                {
                    PyInteger id = idData as PyInteger;

                    foreach (KeyValuePair <long, ClientConnection> entry in this.Clients)
                    {
                        if (entry.Value.CharacterID == id)
                        {
                            // use the key instead of AccountID as this should be faster
                            packet.UserID = entry.Key;
                            // change the ids of interest to hide the character's we've notified
                            destination.IDsOfInterest = new PyDataType[] { id };
                            // queue the packet for the user
                            entry.Value.Socket.Send(packet);
                        }
                    }
                }
            }
        }
示例#20
0
        public PyDataType GetMapConnections(PyInteger itemID, PyDataType isRegion, PyDataType isConstellation,
                                            PyDataType isSolarSystem, PyDataType isCelestial, PyInteger unknown2 = null, CallInformation call = null)
        {
            bool isRegionBool        = false;
            bool isConstellationBool = false;
            bool isSolarSystemBool   = false;
            bool isCelestialBool     = false;

            if (isRegion is PyBool regionBool)
            {
                isRegionBool = regionBool;
            }
            if (isRegion is PyInteger regionInt)
            {
                isRegionBool = regionInt.Value == 1;
            }
            if (isConstellation is PyBool constellationBool)
            {
                isConstellationBool = constellationBool;
            }
            if (isConstellation is PyInteger constellationInt)
            {
                isConstellationBool = constellationInt.Value == 1;
            }
            if (isSolarSystem is PyBool solarSystemBool)
            {
                isSolarSystemBool = solarSystemBool;
            }
            if (isSolarSystem is PyInteger solarSystemInt)
            {
                isSolarSystemBool = solarSystemInt.Value == 1;
            }
            if (isCelestial is PyBool celestialBool)
            {
                isCelestialBool = celestialBool;
            }
            if (isCelestial is PyInteger celestialInt)
            {
                isCelestialBool = celestialInt.Value == 1;
            }

            if (isRegionBool == true)
            {
                return(this.DB.GetMapRegionConnection(itemID));
            }
            if (isConstellationBool == true)
            {
                return(this.DB.GetMapConstellationConnection(itemID));
            }
            if (isSolarSystemBool == true)
            {
                return(this.DB.GetMapSolarSystemConnection(itemID));
            }
            if (isCelestialBool == true)
            {
                Log.Error("GetMapConnections called with celestial id. Not implemented yet!");
            }

            return(null);
        }
示例#21
0
        public PyDataType DestroyInstalledClone(PyInteger jumpCloneID, CallInformation call)
        {
            // if the clone is not loaded the clone cannot be removed, players can only remove clones from where they're at
            int callerCharacterID = call.Client.EnsureCharacterIsSelected();

            if (this.ItemManager.IsItemLoaded(jumpCloneID) == false)
            {
                throw new JumpCantDestroyNonLocalClone();
            }

            ItemEntity clone = this.ItemManager.LoadItem(jumpCloneID);

            if (clone.LocationID != call.Client.LocationID)
            {
                throw new JumpCantDestroyNonLocalClone();
            }
            if (clone.OwnerID != callerCharacterID)
            {
                throw new MktNotOwner();
            }

            // finally destroy the clone, this also destroys all the implants in it
            this.ItemManager.DestroyItem(clone);

            // let the client know that the clones were updated
            call.Client.NotifyCloneUpdate();

            return(null);
        }
示例#22
0
 /// <summary>
 /// Converts the given <paramref name="data"/> to it's byte array representation.
 /// Integers are encoded based on their value, which determines it's size in the byte stream
 ///
 /// The following opcodes are supported
 /// <seealso cref="Opcode.IntegerOne" /> 1 byte, value = 1
 /// <seealso cref="Opcode.IntegerZero" /> 1 byte, value = 0
 /// <seealso cref="Opcode.IntegerMinusOne" /> 1 byte, value = -1
 /// <seealso cref="Opcode.IntegerByte" /> 2 bytes, value is one byte after the opcode, signed byte
 /// <seealso cref="Opcode.IntegerSignedShort" /> 3 bytes, value is two bytes after the opcode, signed short
 /// <seealso cref="Opcode.IntegerLong" /> 5 bytes, value is four bytes after the opcode, signed integer
 /// <seealso cref="Opcode.IntegerLongLong" /> 9 bytes, value is eight bytes after the opcode, signed long
 /// </summary>
 /// <param name="writer">Where to write the encoded data to</param>
 /// <param name="data">The value to write</param>
 private static void ProcessInteger(BinaryWriter writer, PyInteger data)
 {
     if (data == 1)
     {
         writer.WriteOpcode(Opcode.IntegerOne);
     }
     else if (data == 0)
     {
         writer.WriteOpcode(Opcode.IntegerZero);
     }
     else if (data == -1)
     {
         writer.WriteOpcode(Opcode.IntegerMinusOne);
     }
     else if (data > sbyte.MinValue && data < sbyte.MaxValue)
     {
         writer.WriteOpcode(Opcode.IntegerByte);
         writer.Write((byte)data.Value);
     }
     else if (data > short.MinValue && data < short.MaxValue)
     {
         writer.WriteOpcode(Opcode.IntegerSignedShort);
         writer.Write((short)data.Value);
     }
     else if (data > int.MinValue && data < int.MaxValue)
     {
         writer.WriteOpcode(Opcode.IntegerLong);
         writer.Write((int)data.Value);
     }
     else
     {
         writer.WriteOpcode(Opcode.IntegerLongLong);
         writer.Write(data.Value);
     }
 }
示例#23
0
 public void SimpleAssignment()
 {
     runBasicTest("a = 10\n", new VariableMultimap(new TupleList <string, object>
     {
         { "a", PyInteger.Create(10) }
     }), 1);
 }
示例#24
0
        public void DeclareBasicDictionary()
        {
            // The peephole optimizer figures out basic, constant dictionaries and diverts them to
            // BUILD_CONST_KEY_MAP, so I have to use a more obtuse example here to show BUILD_MAP.
            // return_foo() just returns "foo":
            //
            // >>> def dict_name_maker():
            // ...   return {return_foo(): "bar", "number": 1}
            // ...
            // >>> dis.dis(dict_name_maker)
            //   2           0 LOAD_GLOBAL              0 (return_foo)
            //               2 CALL_FUNCTION            0
            //               4 LOAD_CONST               1 ('bar')
            //               6 LOAD_CONST               2 ('number')
            //               8 LOAD_CONST               3 (1)
            //              10 BUILD_MAP                2
            //              12 RETURN_VALUE
            //
            var interpreter = runProgram("a = { \"foo\": \"bar\", \"number\": 1 }\n", new Dictionary <string, object>(), 1);
            var variables   = interpreter.DumpVariables();

            Assert.That(variables.ContainsKey("a"));
            Assert.That(variables["a"], Is.EquivalentTo(new Dictionary <PyString, object> {
                { PyString.Create("foo"), PyString.Create("bar") },
                { PyString.Create("number"), PyInteger.Create(1) }
            }));
        }
示例#25
0
        public void WhileElse()
        {
            string program =
                "while a < 3:\n" +
                "   a = a + 1\n" +
                "else:\n" +
                "   a = a + 100\n";

            // Runs while loop, then the else clause
            runBasicTest(program,
                         new Dictionary <string, object>
            {
                { "a", PyInteger.Create(0) }
            }, new VariableMultimap(new TupleList <string, object>
            {
                { "a", PyInteger.Create(103) }
            }), 1);

            // Skips the while loop, runs the else clause
            runBasicTest(program,
                         new Dictionary <string, object>
            {
                { "a", PyInteger.Create(10) }
            }, new VariableMultimap(new TupleList <string, object>
            {
                { "a", PyInteger.Create(110) }
            }), 1);
        }
示例#26
0
        public PyDataType GetCachableObject(PyInteger shared, PyString objectID, PyTuple objectVersion, PyInteger nodeID, CallInformation call)
        {
            // TODO: CHECK CACHEOK EXCEPTION ON CLIENT
            Log.Debug($"Received cache request for {objectID.Value}");

            return(this.CacheStorage.Get(objectID));
        }
示例#27
0
 public void RepeatedArithmeticOperators()
 {
     // Making sure that we're properly parsing and generating all of these when there's multiples of the operator.
     runBasicTest(
         "x = 100\n" +
         "a = x + 2 + 3\n" +
         "b = x - 2 - 3\n" +
         "c = x * 2 * 3\n" +
         "d = x / 4 / 2\n" +
         "e = x % 9 % 3\n" +
         "f = x // 2 // 3\n" +
         "g = x ** 2 ** 3\n" +
         "h = x & 3 & 2\n" +
         "i = x | 13 | 1 \n" +
         "j = x ^ 2 ^ 1\n" +
         "k = x >> 2 >> 3\n" +
         "l = x << 2 << 3\n"
         , new VariableMultimap(new TupleList <string, object>
     {
         { "a", PyInteger.Create(100 + 2 + 3) },
         { "b", PyInteger.Create(100 - 2 - 3) },
         { "c", PyInteger.Create(100 * 2 * 3) },
         { "d", PyFloat.Create(100.0 / 4.0 / 2.0) },
         { "e", PyInteger.Create(100 % 9 % 3) },
         { "f", PyInteger.Create(100 / 2 / 3) },
         { "g", PyInteger.Create((BigInteger)Math.Pow(100.0, 8.0)) },           // 2 ** 3 gets evaluated first and becomes 8. This is what CPython does too!
         { "h", PyInteger.Create(100 & 3 & 2) },
         { "i", PyInteger.Create(100 | 13 | 1) },
         { "j", PyInteger.Create(100 ^ 2 ^ 1) },
         { "k", PyInteger.Create(100 >> 2 >> 3) },
         { "l", PyInteger.Create(100 << 2 << 3) }
     }), 1);
 }
示例#28
0
        public void AccessClassMethod()
        {
            //>>> def make_foo():
            //...   class Foo:
            //...     def __init__(self):
            //...       self.a = 1
            //...     def change_a(self, new_a):
            //...       self.a = new_a
            //...
            //>>> dis(make_foo)
            //  2           0 LOAD_BUILD_CLASS
            //              2 LOAD_CONST               1 (<code object Foo at 0x0000021BD5908D20, file "<stdin>", line 2>)
            //              4 LOAD_CONST               2 ('Foo')
            //              6 MAKE_FUNCTION            0
            //              8 LOAD_CONST               2 ('Foo')
            //             10 CALL_FUNCTION            2
            //             12 STORE_FAST               0 (Foo)
            //             14 LOAD_CONST               0 (None)
            //             16 RETURN_VALUE
            var interpreter = runProgram("class Foo:\n" +
                                         "   def __init__(self):\n" +
                                         "      self.a = 1\n" +
                                         "\n" +
                                         "   def change_a(self, new_a):\n" +
                                         "      self.a = new_a\n" +
                                         "\n" +
                                         "bar = Foo()\n" +
                                         "bar.change_a(2)\n", new Dictionary <string, object>(), 1);
            var variables = new VariableMultimap(interpreter);
            var bar       = (PyObject)variables.Get("bar");

            Assert.That(bar.__dict__["a"], Is.EqualTo(PyInteger.Create(2)));
        }
示例#29
0
        public PyList <PyString> LogAttribute(PyInteger itemID, PyInteger attributeID, PyString reason, CallInformation call)
        {
            int role     = call.Client.Role;
            int roleMask = (int)(Roles.ROLE_GDH | Roles.ROLE_QA | Roles.ROLE_PROGRAMMER | Roles.ROLE_GMH);

            if ((role & roleMask) == 0)
            {
                throw new CustomError("Not allowed!");
            }

            ItemEntity item = this.ItemFactory.GetItem(itemID);

            if (item.Attributes.AttributeExists(attributeID) == false)
            {
                throw new CustomError("The given attribute doesn't exists in the item");
            }

            // we don't know the actual values of the returned function
            // but it should be enough to fill the required data by the client
            return(new PyList <PyString>(5)
            {
                [0] = null,
                [1] = null,
                [2] = $"Server value: {item.Attributes[attributeID]}",
                [3] = $"Base value: {AttributeManager.DefaultAttributes[item.Type.ID][attributeID]}",
                [4] = $"Reason: {reason}"
            });
        }
        public async Task ArrayWritePyInteger()
        {
            var array = new int[] { 1 };
            await SubscriptHelper.StoreSubscript(interpreter, context, array, PyInteger.Create(0), 2);

            Assert.That(array[0], Is.EqualTo(2));
        }