package com.sonymusic

import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test

import static org.junit.jupiter.api.Assertions.assertThrows
import static org.junit.jupiter.api.Assertions.assertTrue

class WithEcrTest extends BaseGlobalVarTest {
    def withEcr

    @BeforeEach
    void setUp() {
        super.setUp()
        withEcr = loadScript("vars/withEcr.groovy")
        helper.registerAllowedMethod('sh')
    }
    @Test
    void testCallWithDefaultRegistries() {
        def closureCalled = false
        withEcr {
            closureCalled = true
        }

        assertTrue(closureCalled)

        assertMethodCalledTimes('sh', 3)
        assertMethodCalledNthWith('sh', 0, 'aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 437795906767.dkr.ecr.us-east-1.amazonaws.com')
        assertMethodCalledNthWith('sh', 1, 'aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 086679231553.dkr.ecr.us-east-1.amazonaws.com')
        assertMethodCalledNthWith('sh', 2, 'aws ecr get-login-password --region us-east-2 | docker login --username AWS --password-stdin 086679231553.dkr.ecr.us-east-2.amazonaws.com')
    }

    @Test
    void testCallWithRegistryMissingAccountId() {
        assertThrows(AssertionError.class, {
            withEcr.call(registries: [region: 'us-east-1']) {}
        })
    }

    @Test
    void testCallWithRegistryMissingRegion() {
        assertThrows(AssertionError.class, {
            withEcr.call(registries: [accountId: '123456789012']) {}
        })
    }

    @Test
    void testCallSuccess() {
        def closureCalled = false
        withEcr(
            registries: [
                [accountId: '123456789012', region: 'us-east-1'],
                [accountId: '234567890123', region: 'us-west-2']
            ],
        ) {
            closureCalled = true
        }

        assertTrue(closureCalled)

        assertMethodCalledTimes('sh', 2)
        assertMethodCalledNthWith('sh', 0, 'aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 123456789012.dkr.ecr.us-east-1.amazonaws.com')
        assertMethodCalledNthWith('sh', 1, 'aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin 234567890123.dkr.ecr.us-west-2.amazonaws.com')
    }
}
