lundi 3 janvier 2022

Spring Factory Design Pattern Unit Test

I have a factory design pattern which returns particular service according to the enum type and it works perfectly when I run the application but factory throws error on unit test.

@Service
public class GaServiceFactory {

    @Autowired
    private ApplicationContext appContext;

    public IGaService getInstance(GaType type) {

        if (MAN.equals(type)) {
            return appContext.getBean(ManGaService.class);
        }

        throw new RuntimeException("No matching service could be created");
    }

}

Here's my controller class;

@RestController
@RequestMapping(GA)
public class GaController {

    @Autowired
    private GaServiceFactory factory;

    @PostMapping(value = INITIALIZE, produces = APPLICATION_JSON_VALUE)
    public ResponseEntity<GaDTO> initialize() {
        return status(CREATED).body(factory.getInstance(MAN).initialize());
    }

And here's my unit test;

@WebMvcTest(value = GaController.class)
class GaControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private GaServiceFactory factory;

    @Mock
    private ApplicationContext appContext;

    private GaDTO gaDTO;

    private List<GaDTO> gaDTOList;

    @BeforeEach
    void setUp() {
        gaDTOList= new ArrayList<>();
        Ga ga = new Ga();
        gaDTO = new GaDTO();
        gaDTO.setId(ga.getId());
        gaDTOList.add(gaDTO);
    }

    @Test
    public void initialize_success() throws Exception {
        when(factory.getInstance(MAN).initialize()).thenReturn(gaDTO);

        mockMvc.perform(post(GA + INITIALIZE)
                        .contentType(APPLICATION_JSON))
                .andExpect(status().isCreated())
                .andExpect(jsonPath("$.id", is(gaDTO.getId())));
    }

ApplicationContext in the factory returns null and it throws an error when I expect the initialize method in the service to work. How can I mock the factory to work as expected.

How can I add a decorator pattern to a chain of responsibility?

I created the following UML. It's basically a currency converter. As it is now, it is a Chain of Responsibility. But now I want to add a Decorator pattern. So, for example, add a fixed processing amount. How can I insert a Decorator pattern here? Thanks for the help!

COR

dimanche 2 janvier 2022

Python:Need advice on the design of my small project

So my requirement is to write a script for creaing a VM in Google Cloud Platform. I have gotten all the requirements and determined all the must to have parameters for create_vm API. The inputs can be broadly classified into following sections (both as per the API and as per my requirement.)

  1. Boot Disk Details
  2. Other Disk Details
  3. Network Details
  4. Additional Details
  5. VM Machine Details

So for this i have planned to implement it using python class as below.

 class CreateVM:

def __init__():
    //initialize the template
    pass

def ValidateMachineDetails(self):
    try:
        //call relevant list apis
    except HTTP Error:
        pass
    else:
        // Update other VM machine details parameters in the template
    
    
def BootDiskDetails(self, <parameters for Boot Disk Part>):
    try:
        //call relevant list apis
    except HTTP Error:
        pass
    else:
        // Update boot disk details parameters in the template
        
def OtherDiskDetails(self, <parameters for other disk details>):
    try:
        //call relevant list apis
    except HTTP Error:
        pass
    else:
        // Update other disk details parameters in the template
        
def NetworkDetailsDetails(self, <parameters for network details>):
    try:
        //call relevant list apis
    except HTTP Error:
        pass
    else:
        // Update network details parameters in the template

def AdditionalDetails(self, <parameters for AdditionalDetails):
    try:
        //call relevant list apis
    except HTTP Error:
        pass
    else:
        // Update additional details parameters in the template

I have following questions

  1. Is this solution better implemented with only function or is it correct design to use the classes for this solution?
  2. If so is my design of the class a correct approach?
  3. If not, what should i do to improve my apprach?

The base template which i am update is as below:

{

        "name": "",  # Mandatory
        "tags": {
            "items": [],
        },
        "machineType": "",  # Mandatory

        "canIpForward": False,
        "networkInterfaces": [
            {
                "network": "",
                "subnetwork": "",
                "networkIP": "",
                "name": "",
                "accessConfigs": [
                    {
                        "name": 'External NAT',
                        "natIP": "",
                    }
                ],

                "aliasIpRanges": [],  # Needed only if CIDR Blocks are added
                "stackType": 'IPV4_ONLY',
            }
        ],
        "disks": [
            {
                "type": '',
                "mode": '',
                "source": '',  # Only for persistent disks
                "deviceName": '',  # Only for persistent disks

                "boot": False,
                "initializeParams": {
                    "diskName": '',
                    'sourceImage': '',
                    "diskSizeGb": 0,
                    "diskType": '',
                    "sourceImageEncryptionKey": {
                        "rawKey": '',  # Either this key or rsaEncryptedKey must be provided
                        "rsaEncryptedKey": '',
                        "kmsKeyName": '',
                        "kmsKeyServiceAccount": ''
                        # If not provided compute engine default service account is used.
                    },
                    "labels": {
                        '': '',  # Key Value pair only available for persistent disks

                    },
                    "sourceSnapshot": '',
                    "sourceSnapshotEncryptionKey": {
                        "rawKey": '',  # Either this key or rsaEncryptedKey must be provided
                        "rsaEncryptedKey": '',
                        "kmsKeyName": '',
                        "kmsKeyServiceAccount": ''
                        # If not provided compute engine default service account is used.
                    },

                },
                "autoDelete": False,

                "interface": '',

                "diskEncryptionKey": {
                    "kmsKeyServiceAccount": '',
                    "rawKey": '',
                    "rsaEncryptedKey": '',
                    "kmsKeyName": ''

                },
                "diskSizeGb": '',

            }
        ],
        "metadata": {

            "items": [
                {
                    "key": '',
                    "value": ''
                }
            ],
        },
        "serviceAccounts": [
            {
                "email": '',
                "scopes": []
            }
        ],
        "scheduling": {
            "onHostMaintenance": 'MIGRATE',
            "automaticRestart": True,
            "preemptible": False,
            "nodeAffinities": [
                {
                    "key": '',
                    "operator": '',
                    "values": []
                }
            ],

        },
        "cpuPlatform": '',
        "labels": {
        },

        "guestAccelerators": [
            {
                "acceleratorType": '',
                "acceleratorCount": 0
            }
        ],

        "deletionProtection": False,
        "resourcePolicies": [],  # Array of Strings
        "reservationAffinity": {
            "consumeReservationType": '',

        },
        "hostname": '',
        "displayDevice": {
            "enableDisplay": False
        },
        "shieldedInstanceConfig": {
            "enableSecureBoot": False,
            "enableVtpm": True,
            "enableIntegrityMonitoring": True
        },

        "confidentialInstanceConfig": {
            "enableConfidentialCompute": False
        },
        "privateIpv6GoogleAccess": 'INHERIT_FROM_SUBNETWORK ',
        "advancedMachineFeatures": {
            "enableNestedVirtualization": False,
        },

        "networkPerformanceConfig": {
            "totalEgressBandwidthTier": ""
        },
        "kind": ""
    }

samedi 1 janvier 2022

Design issue with matching a generic type on the same type with a parent class as parameter

I'm trying to work out some design issues on code for a rather basic reinforcement learning library I'm working on, but can't seem to figure out where the flaw is. There's this base code which relies on generics:

public abstract class Action {...}

public abstract class State<TAction>
    where TAction : Action
{
    ...

    public abstract TAction[] GetAllowedActions();
    
    public virtual Pair<TAction, State<TAction>> GetPair(TAction action)
    {
        return new Pair<TAction, State<TAction>>(this, action);
    }
}

public class Pair<TAction, TState>
    where TAction : Action
    where TState : State<TAction>
{
    public Pair(TState state, TAction action) {...}

    public virtual IEnumerable EquivalentPairs()
    {
        yield return this;
    }
}

Now I want to build on given code by extending the classes for a certain game I want to train my agent on:

public class GameAction : Action {...}

public class GameState : State<GameAction>
{
    public override Pair<GameAction, State<GameAction>> GetPair(GameAction action)
    {
        return new GamePair(this, action); // CS0029 - GamePair cannot be converted to Pair<GameAction, GameState> 
    }
}

public class GamePair : Pair<GameAction, GameState> // implements additionally required behavior
{
    public GamePair(GameState state, GameAction action) : base(state, action) {...}
}

While Pair wouldn't necessarily have to be extended, it does in this case where certain states being equivalent want to be accounted for, with their corresponding actions adapted accordingly - e.g. in Connect Four, where you additionally could mirror the current game state and the according column being picked to improve training. That's why I'd like additional behavior on this class to be allowed.

This brings me across the problem though, that I can't generally return GamePair with GetPair(...), since it's not recognized as a viable subclass of Pair<GameAction, State<GameAction>>, although GameState is a subclass of State<GameAction>. How to deal with this?

Decorator pattern on a winform panel

I am trying to make a decorator pattern with an IPanel interface but when I try to access the base class I get NullReferenceException. I would use composite but I am forced to use decorator on this one.

Thats the decoration I implemented:

public interface IPanel
    {
        void Operation();
    }

    public class CorePanel : Panel, IPanel
    {
        public void Operation() { }
    }
    public class PanelDecorator : IPanel
    {
        protected IPanel m_Decorated;
        public PanelDecorator(IPanel i_Decorated)
        { m_Decorated = i_Decorated; }

        public virtual void Operation()
        { m_Decorated.Operation(); }

    }
    public class VScrollPanel : PanelDecorator
    {
        public VScrollPanel(IPanel i_Decorated) :
        base(i_Decorated){ }
        public override void Operation()
        {
            Scroll();
        }
        private void Scroll()
        {
            (this.m_Decorated as Panel).Visible = false;
        }
    }
       private void InitializeComponent()
    {
        // 
        // panel1
        // 
        this.panel1.Location = new System.Drawing.Point(29, 81);
        this.panel1.Name = "panel1";
        this.panel1.Size = new System.Drawing.Size(409, 341);
        this.panel1.TabIndex = 5;
        // 
        // DecoratedPanel
        // 
        this.ZodiacIPanel = new VScrollPanel(new CorePanel());
        (this.ZodiacIPanel as CorePanel).Visible = false;{this one gives the null ptr error}

#endregion
    private IPanel ZodiacIPanel;
    private System.Windows.Forms.Panel panel1;

What does

I was digging into some infrastructure code, when I came across this method declaration:

<T> T resolve(Class<T> var1);

Is this some kind of pattern or technique? If so, what's its purpose?

Edit: I understand generics, etc. I'm more wondering in what case would a method of that form (taking a Class and returning an instance of it) be useful?

Here's more of the context, in case it helps:

public interface Environment {
  String domain();

  Client client();

  Config config();

  Environment.RoutingEngine routingEngine();

  Closer closer();

  <T> T resolve(Class<T> var1);

  public interface RoutingEngine {
    Environment.RoutingEngine registerAutoRoutes(RouteProvider var1);

    Environment.RoutingEngine registerAutoRoute(Route<? extends AsyncHandler<?>> var1);

    Environment.RoutingEngine registerRoutes(Stream<? extends Route<? extends AsyncHandler<? extends Response<ByteString>>>> var1);

    Environment.RoutingEngine registerRoute(Route<? extends AsyncHandler<? extends Response<ByteString>>> var1);
  }
}

And an example use of it, though I doubt it helps:

  static void configure(final Environment environment) {
    final GrpcServer grpcServer = environment.resolve(GrpcServer.class);
    grpcServer.addService(new ExampleResource());
  }

Composition Relationship - What if the subclass wants access to base class properties?

I have a User class, and the user has multiple devices, but only one can be activated in a session i.e. active device. The device should be able to access the authentication status of the user from the User class, I don't want to store that variable in the device class, as it's a property of the User and not the device, but device will only operate if the user is authenticated.

Any suggestions how I would achieve this in C++?